Java微信公众平台开发(13) 微信JSSDK中Config配置

2025-05-29 0 22

前端开发工程师和关注前端开发的开发者们在2015年中肯定被腾讯的jssdk引爆过,搞app的、搞前端的甚至是是搞后端的都跑过来凑热闹,一时之间也把微信jssdk捧得特别牛逼,但是在我们的技术眼里它的实现原理和根本是不能够被改变的,这篇文章就不对其js的实现做任何评价和解说了(因为我也不是很懂,哈哈),这里要说的是它的config配置实现,参考文档:http://mp.weixin.qq.com/wiki/11/74ad127cc054f6b80759c40f77ec03db.html !

微信js-sdk是微信公众平台面向网页开发者提供的基于微信内的网页开发工具包,通过使用微信js-sdk,网页开发者可借助微信高效地使用拍照、选图、语音、位置等手机系统的能力,同时可以直接使用微信分享、扫一扫、卡券、支付等微信特有的能力,为微信用户提供更优质的网页体验;本篇将面向网页开发者介绍微信js-sdk如何使用及相关注意事项!jssdk使用步骤:

步骤一:在微信公众平台绑定安全域名
步骤二:后端接口实现js-sdk配置需要的参数
步骤三:页面实现js-sdk中config的注入配置,并实现对成功和失败的处理

(一)在微信公众平台绑定安全域名

先登录微信公众平台进入“公众号设置”的“功能设置”里填写“js接口安全域名”(如下图),如果需要使用支付类接口,需要确保支付目录在支付的安全域名下,否则将无法完成支付!(注:登录后可在“开发者中心”查看对应的接口权限)

Java微信公众平台开发(13) 微信JSSDK中Config配置

(二)后端接口实现js-sdk配置需要的参数

?

1

2

3

4

5

6

7

8
wx.config({

debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。

appid: '', // 必填,公众号的唯一标识

timestamp: , // 必填,生成签名的时间戳

noncestr: '', // 必填,生成签名的随机串

signature: '',// 必填,签名,见附录1

jsapilist: [] // 必填,需要使用的js接口列表,所有js接口列表见附录2

});

我们查看js-sdk的配置文档和以上的代码可以发现config的配置需要4个必不可少的参数appid、timestamp、noncestr、signature,这里的signature就是我们生成的签名!

生成签名之前必须先了解一下jsapi_ticket,jsapi_ticket是公众号用于调用微信js接口的临时票据。正常情况下,jsapi_ticket的有效期为7200秒,通过access_token来获取。由于获取jsapi_ticket的api调用次数非常有限,频繁刷新jsapi_ticket会导致api调用受限,影响自身业务,开发者必须在自己的服务全局缓存jsapi_ticket ,所以这里我们将jsapi_ticket的获取放到定时任务中,因为它和token的生命周期是一致的,所以在这里我们将他们放到一起,将原有的定时任务中获取token的代码做如下修改:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54
package com.cuiyongzhi.wechat.common;

import java.text.simpledateformat;

import java.util.date;

import java.util.hashmap;

import java.util.map;

import net.sf.json.jsonobject;

import com.cuiyongzhi.web.util.globalconstants;

import com.cuiyongzhi.wechat.util.httputils;

/**

* classname: wechattask

* @description: 微信两小时定时任务体

* @author dapengniao

* @date 2016年3月10日 下午1:42:29

*/

public class wechattask {

/**

* @description: 任务执行体

* @param @throws exception

* @author dapengniao

* @date 2016年3月10日 下午2:04:37

*/

public void gettoken_getticket() throws exception {

map<string, string> params = new hashmap<string, string>();

//获取token执行体

params.put("grant_type", "client_credential");

params.put("appid", globalconstants.getinterfaceurl("appid"));

params.put("secret", globalconstants.getinterfaceurl("appsecret"));

string jstoken = httputils.sendget(

globalconstants.getinterfaceurl("tokenurl"), params);

string access_token = jsonobject.fromobject(jstoken).getstring(

"access_token"); // 获取到token并赋值保存

globalconstants.interfaceurlproperties.put("access_token", access_token);

//获取jsticket的执行体

params.clear();

params.put("access_token", access_token);

params.put("type", "jsapi");

string jsticket = httputils.sendget(

globalconstants.getinterfaceurl("ticketurl"), params);

string jsapi_ticket = jsonobject.fromobject(jsticket).getstring(

"ticket");

globalconstants.interfaceurlproperties

.put("jsapi_ticket", jsapi_ticket); // 获取到js-sdk的ticket并赋值保存

system.out.println("jsapi_ticket================================================" + jsapi_ticket);

system.out.println(new simpledateformat("yyyy-mm-dd hh:mm:ss").format(new date())+"token为=============================="+access_token);

}

}

然后我们根据【js-sdk使用权限签名算法】对参数进行签名得到signature,这里的url必须采用前端传递到后端,因为每次的url会有所变化,如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59
package com.cuiyongzhi.wechat.common;

import java.security.messagedigest;

import java.util.formatter;

import java.util.hashmap;

import java.util.uuid;

import com.cuiyongzhi.web.util.globalconstants;

/**

* classname: jssdk_config

* @description: 用户微信前端页面的jssdk配置使用

* @author dapengniao

* @date 2016年3月19日 下午3:53:23

*/

public class jssdk_config {

/**

* @description: 前端jssdk页面配置需要用到的配置参数

* @param @return hashmap {appid,timestamp,noncestr,signature}

* @param @throws exception

* @author dapengniao

* @date 2016年3月19日 下午3:53:23

*/

public static hashmap<string, string> jssdk_sign(string url) throws exception {

string nonce_str = create_nonce_str();

string timestamp=globalconstants.getinterfaceurl("timestamp");

string jsapi_ticket=globalconstants.getinterfaceurl("jsapi_ticket");

// 注意这里参数名必须全部小写,且必须有序

string string1 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str

+ "×tamp=" + timestamp + "&url=" + url;

messagedigest crypt = messagedigest.getinstance("sha-1");

crypt.reset();

crypt.update(string1.getbytes("utf-8"));

string signature = bytetohex(crypt.digest());

hashmap<string, string> jssdk=new hashmap<string, string>();

jssdk.put("appid", globalconstants.getinterfaceurl("appid"));

jssdk.put("timestamp", timestamp);

jssdk.put("noncestr", nonce_str);

jssdk.put("signature", signature);

return jssdk;

}

private static string bytetohex(final byte[] hash) {

formatter formatter = new formatter();

for (byte b : hash) {

formatter.format("%02x", b);

}

string result = formatter.tostring();

formatter.close();

return result;

}

private static string create_nonce_str() {

return uuid.randomuuid().tostring();

}

}

然后我们将后端签名的方法集成到controller层,形成代码如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42
package com.cuiyongzhi.wechat.controller;

import java.util.map;

import org.springframework.stereotype.controller;

import org.springframework.web.bind.annotation.requestmapping;

import org.springframework.web.bind.annotation.requestparam;

import com.cuiyongzhi.message;

import com.cuiyongzhi.wechat.common.jssdk_config;

/**

* classname: wechatcontroller

* @description: 前端用户微信配置获取

* @author dapengniao

* @date 2016年3月19日 下午5:57:36

*/

@controller

@requestmapping("/wechatconfig")

public class wechatcontroller {

/**

* @description: 前端获取微信jssdk的配置参数

* @param @param response

* @param @param request

* @param @param url

* @param @throws exception

* @author dapengniao

* @date 2016年3月19日 下午5:57:52

*/

@requestmapping("jssdk")

public message jssdk_config(

@requestparam(value = "url", required = true) string url) {

try {

system.out.println(url);

map<string, string> configmap = jssdk_config.jssdk_sign(url);

return message.success(configmap);

} catch (exception e) {

return message.error();

}

}

}

到这里我们后端对jssdk的签名参数的封装就基本完成了,下一步就只需要我们前端调用就可以了!

(三)页面实现js-sdk中config的注入配置,并实现对成功和失败的处理

在第二步中我们将后端接口代码完成了,这里新建jssdkconfig.jsp,在jsp页面用ajax方式获取并进行配置,并开启debug模式,打开之后就可以看到配置是否成功的提示,简单代码如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63
<%@ page language="java" contenttype="text/html; charset=utf-8"

pageencoding="utf-8"%>

<!doctype html >

<html>

<head>

<meta http-equiv="content-type" content="text/html; charset=utf-8">

<meta name="viewport" content="width=device-width" />

<title>jssdk配置</title>

<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>

<script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>

<script type="text/javascript">

function jssdk() {

$.ajax({

url : "http://wechat.cuiyongzhi.com/wechatconfig/jssdk",

type : 'post',

datatype : 'json',

contenttype : "application/x-www-form-urlencoded; charset=utf-8",

data : {

'url' : location.href.split('#')[0]

},

success : function(data) {

wx.config({

debug : true,

appid : data.data.appid,

timestamp : data.data.timestamp,

noncestr : data.data.noncestr,

signature : data.data.signature,

jsapilist : [ 'checkjsapi', 'onmenusharetimeline',

'onmenushareappmessage', 'onmenushareqq',

'onmenushareweibo', 'hidemenuitems',

'showmenuitems', 'hideallnonbasemenuitem',

'showallnonbasemenuitem', 'translatevoice',

'startrecord', 'stoprecord', 'onrecordend',

'playvoice', 'pausevoice', 'stopvoice',

'uploadvoice', 'downloadvoice', 'chooseimage',

'previewimage', 'uploadimage', 'downloadimage',

'getnetworktype', 'openlocation', 'getlocation',

'hideoptionmenu', 'showoptionmenu', 'closewindow',

'scanqrcode', 'choosewxpay',

'openproductspecificview', 'addcard', 'choosecard',

'opencard' ]

});

}

});

}

function isweixin5() {

var ua = window.navigator.useragent.tolowercase();

var reg = /micromessenger\\/[5-9]/i;

return reg.test(ua);

}

window.onload = function() {

// if (isweixin5() == false) {

// alert("您的微信版本低于5.0,无法使用微信支付功能,请先升级!");

// }

jssdk();

};

</script>

</head>

<body>

</body>

</html>

最后我们运行代码,查看运行结果:

Java微信公众平台开发(13) 微信JSSDK中Config配置

如果提示是这样,那么标识我们的配置是成功的,那么到这里微信jssdk的配置就基本完成了,下一篇讲述【微信web开发者工具】的使用,欢迎你的翻阅,如有疑问可以留言讨论!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。

原文链接:http://www.cuiyongzhi.com/post/57.html

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Java微信公众平台开发(13) 微信JSSDK中Config配置 https://www.kuaiidc.com/117089.html

相关文章

发表评论
暂无评论