前端開發(fā)工程師和關(guān)注前端開發(fā)的開發(fā)者們在2015年中肯定被騰訊的jssdk引爆過,搞app的、搞前端的甚至是是搞后端的都跑過來湊熱鬧,一時之間也把微信jssdk捧得特別牛逼,但是在我們的技術(shù)眼里它的實現(xiàn)原理和根本是不能夠被改變的,這篇文章就不對其js的實現(xiàn)做任何評價和解說了(因為我也不是很懂,哈哈),這里要說的是它的config配置實現(xiàn),參考文檔: http://mp.weixin.qq.com/wiki/11/74ad127cc054f6b80759c40f77ec03db.html !
微信js-sdk是微信公眾平臺面向網(wǎng)頁開發(fā)者提供的基于微信內(nèi)的網(wǎng)頁開發(fā)工具包,通過使用微信js-sdk,網(wǎng)頁開發(fā)者可借助微信高效地使用拍照、選圖、語音、位置等手機系統(tǒng)的能力,同時可以直接使用微信分享、掃一掃、卡券、支付等微信特有的能力,為微信用戶提供更優(yōu)質(zhì)的網(wǎng)頁體驗;本篇將面向網(wǎng)頁開發(fā)者介紹微信js-sdk如何使用及相關(guān)注意事項!jssdk使用步驟:
步驟一:在微信公眾平臺綁定安全域名
步驟二:后端接口實現(xiàn)js-sdk配置需要的參數(shù)
步驟三:頁面實現(xiàn)js-sdk中config的注入配置,并實現(xiàn)對成功和失敗的處理
(一)在微信公眾平臺綁定安全域名
先登錄微信公眾平臺進入“公眾號設(shè)置”的“功能設(shè)置”里填寫“js接口安全域名”(如下圖),如果需要使用支付類接口,需要確保支付目錄在支付的安全域名下,否則將無法完成支付!(注:登錄后可在“開發(fā)者中心”查看對應(yīng)的接口權(quán)限)
(二)后端接口實現(xiàn)js-sdk配置需要的參數(shù)
1
2
3
4
5
6
7
8
|
wx.config({ debug: true , // 開啟調(diào)試模式,調(diào)用的所有api的返回值會在客戶端alert出來,若要查看傳入的參數(shù),可以在pc端打開,參數(shù)信息會通過log打出,僅在pc端時才會打印。 appid: '' , // 必填,公眾號的唯一標識 noncestr: '' , // 必填,生成簽名的隨機串 signature: '' , // 必填,簽名,見附錄1 jsapilist: [] // 必填,需要使用的js接口列表,所有js接口列表見附錄2 }); |
我們查看js-sdk的配置文檔和以上的代碼可以發(fā)現(xiàn)config的配置需要4個必不可少的參數(shù)appid、timestamp、noncestr、signature,這里的signature就是我們生成的簽名!
生成簽名之前必須先了解一下jsapi_ticket,jsapi_ticket是公眾號用于調(diào)用微信js接口的臨時票據(jù)。正常情況下,jsapi_ticket的有效期為7200秒,通過access_token來獲取。由于獲取jsapi_ticket的api調(diào)用次數(shù)非常有限,頻繁刷新jsapi_ticket會導致api調(diào)用受限,影響自身業(yè)務(wù),開發(fā)者必須在自己的服務(wù)全局緩存jsapi_ticket ,所以這里我們將jsapi_ticket的獲取放到定時任務(wù)中,因為它和token的生命周期是一致的,所以在這里我們將他們放到一起,將原有的定時任務(wù)中獲取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: 微信兩小時定時任務(wù)體 * @author dapengniao * @date 2016年3月10日 下午1:42:29 */ public class wechattask { /** * @description: 任務(wù)執(zhí)行體 * @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執(zhí)行體 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的執(zhí)行體 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); // 獲取到j(luò)s-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); } } |
然后我們根據(jù)【js-sdk使用權(quán)限簽名算法】對參數(shù)進行簽名得到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頁面配置需要用到的配置參數(shù) * @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" ); // 注意這里參數(shù)名必須全部小寫,且必須有序 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的配置參數(shù) * @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的簽名參數(shù)的封裝就基本完成了,下一步就只需要我們前端調(diào)用就可以了!
(三)頁面實現(xiàn)js-sdk中config的注入配置,并實現(xiàn)對成功和失敗的處理
在第二步中我們將后端接口代碼完成了,這里新建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> |
最后我們運行代碼,查看運行結(jié)果:
如果提示是這樣,那么標識我們的配置是成功的,那么到這里微信jssdk的配置就基本完成了,下一篇講述【微信web開發(fā)者工具】的使用,歡迎你的翻閱,如有疑問可以留言討論!
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://www.cuiyongzhi.com/post/57.html