WeChat JS-SDK is a web development toolkit based on WeChat provided by WeChat public platform for web developers.
By using WeChat JS-SDK, web developers can use WeChat to efficiently use the capabilities of mobile phone systems such as taking pictures, selecting pictures, voice, and location. At the same time, they can directly use WeChat to share, scan, and coupons. WeChat’s unique capabilities such as payment provide WeChat users with a better web experience.
This document introduces how to use WeChat JS-SDK and related precautions for web developers.
Step 3: Inject permission verification configuration through the config interface
All pages that need to use JS-SDK must first inject configuration information, otherwise they will not be called (the same URL only needs to be called once, and the SPA web app that changes the URL can be called every time the URL changes. ,At present, the Android WeChat client does not support the new H5 features of pushState, so using pushState to implement the web app page will cause the signature to fail. This problem will be fixed in Android 6.2).
wx.config({ debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。 appId: '', // 必填,公众号的唯一标识 timestamp: , // 必填,生成签名的时间戳 nonceStr: '', // 必填,生成签名的随机串 signature: '',// 必填,签名,见附录1 jsApiList: [] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2 });
wx.ready(function(){ // config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。 });
wx.error(function(res){ // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。 });
The above functions all have a parameter of type object. In addition to the data returned by each interface itself, there is also a general attribute errMsg, whose value format is as follows:
/// <summary> /// 微信参数准备 /// </summary> private void WxSdkPramas(bool isShare) { var jsSdk = new JSSDKHelper(); //获取时间戳 var timestamp = JSSDKHelper.GetTimestamp(); //获取随机码 var nonceStr = JSSDKHelper.GetNoncestr(); var appId = WeiXinAppId; var appSecret = WeiXinAppSecret; //获取票证 var jsTicket = JsApiTicketContainer.TryGetTicket(appId, appSecret); //获取签名 var signature = jsSdk.GetSignature(jsTicket, nonceStr, timestamp, Request.Url.AbsoluteUri); ViewData["AppId"] = appId; ViewData["Timestamp"] = timestamp; ViewData["NonceStr"] = nonceStr; ViewData["Signature"] = signature; }
<head> <meta name="viewport" content="width=device-width" /> <title>公众号JSSDK演示</title> <script src="~/Scripts/jquery-1.7.1.min.js"></script> <script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script> <script> wx.config({ debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。 appId: '@ViewData["AppId"]', // 必填,公众号的唯一标识 timestamp: '@ViewData["Timestamp"]', // 必填,生成签名的时间戳 nonceStr: '@ViewData["NonceStr"]', // 必填,生成签名的随机串 signature: '@ViewData["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' ] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2。详见:http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html }); wx.error(function (res) { console.log(res); alert('验证失败'); }); wx.ready(function () { var url = 'http://weixin.senparc.com'; var link = url + '@(Request.Url.PathAndQuery)'; var imgUrl = url + '/images/v2/ewm_01.png'; //转发到朋友圈 wx.onMenuShareTimeline({ title: 'JSSDK朋友圈转发测试', link: link, imgUrl: imgUrl, success: function () { alert('转发成功!'); }, cancel: function () { alert('转发失败!'); } }); //转发给朋友 wx.onMenuShareAppMessage({ title: 'JSSDK朋友圈转发测试', desc: '转发给朋友', link: link, imgUrl: imgUrl, type: 'link', dataUrl: '', success: function () { alert('转发成功!'); }, cancel: function () { alert('转发失败!'); } }); }); </script> </head>
public class JSSDKHelper { public JSSDKHelper() { Parameters = new Hashtable(); } protected Hashtable Parameters; /// <summary> /// 设置参数值 /// </summary> /// <param name="parameter"></param> /// <param name="parameterValue"></param> private void SetParameter(string parameter, string parameterValue) { if (!string.IsNullOrEmpty(parameter)) { if (Parameters.Contains(parameter)) { Parameters.Remove(parameter); } Parameters.Add(parameter, parameterValue); } } private void ClearParameter() { Parameters.Clear(); } /// <summary> /// 获取随机字符串 /// </summary> /// <returns></returns> public static string GetNoncestr() { Random random = new Random(); return MD5Util.GetMD5(random.Next(1000).ToString(), "GBK"); } /// <summary> /// 获取时间戳 /// </summary> /// <returns></returns> public static string GetTimestamp() { TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); return Convert.ToInt64(ts.TotalSeconds).ToString(); } /// <summary> /// sha1加密 /// </summary> /// <returns></returns> private string CreateSha1() { StringBuilder sb = new StringBuilder(); ArrayList akeys = new ArrayList(Parameters.Keys); akeys.Sort(); foreach (string k in akeys) { string v = (string)Parameters[k]; if (sb.Length == 0) { sb.Append(k + "=" + v); } else { sb.Append("&" + k + "=" + v); } } return SHA1UtilHelper.GetSha1(sb.ToString()).ToString().ToLower(); } /// <summary> /// 生成cardSign的加密方法 /// </summary> /// <returns></returns> private string CreateCardSha1() { StringBuilder sb = new StringBuilder(); ArrayList akeys = new ArrayList(Parameters.Keys); akeys.Sort(); foreach (string k in akeys) { string v = (string)Parameters[k]; sb.Append(v); } return SHA1UtilHelper.GetSha1(sb.ToString()).ToString().ToLower(); } /// <summary> /// 获取JS-SDK权限验证的签名Signature /// </summary> /// <param name="ticket"></param> /// <param name="noncestr"></param> /// <param name="timestamp"></param> /// <param name="url"></param> /// <returns></returns> public string GetSignature(string ticket, string noncestr, string timestamp, string url) { //清空Parameters ClearParameter(); SetParameter("jsapi_ticket", ticket); SetParameter("noncestr", noncestr); SetParameter("timestamp", timestamp); SetParameter("url", url); return CreateSha1(); } /// <summary> /// 获取位置签名AddrSign /// </summary> /// <param name="appId"></param> /// <param name="appSecret"></param> /// <param name="noncestr"></param> /// <param name="timestamp"></param> /// <param name="url"></param> /// <returns></returns> public string GetAddrSign(string appId, string appSecret, string noncestr, string timestamp, string url) { //清空Parameters ClearParameter(); var accessToken = AccessTokenContainer.TryGetToken(appId, appSecret); SetParameter("appId", appId); SetParameter("noncestr", noncestr); SetParameter("timestamp", timestamp); SetParameter("url", url); SetParameter("accesstoken", accessToken); return CreateSha1(); } /// <summary> /// 获取卡券签名CardSign /// </summary> /// <param name="appId"></param> /// <param name="appSecret"></param> /// <param name="locationId"></param> /// <param name="noncestr"></param> /// <param name="timestamp"></param> /// <param name="cardId"></param> /// <param name="cardType"></param> /// <returns></returns> public string GetCardSign(string appId, string appSecret, string locationId, string noncestr, string timestamp, string cardId, string cardType) { //清空Parameters ClearParameter(); SetParameter("appId", appId); SetParameter("appsecret", appSecret); SetParameter("location_id", locationId); SetParameter("nonce_str", noncestr); SetParameter("times_tamp", timestamp); SetParameter("card_id", cardId); SetParameter("card_type", cardType); return CreateCardSha1(); } }