Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of Wechat JSSDK developed by Wechat official account

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces the example analysis of Wechat JSSDK developed by Wechat official account. It is very detailed and has certain reference value. Interested friends must finish reading it.

Overview

Wechat JS-SDK is a web development kit based on Wechat provided by Wechat public platform for web developers.

By using Wechat JS-SDK, web developers can take advantage of Wechat's ability to efficiently use mobile systems such as photo, picture selection, voice, location and so on. At the same time, they can directly use Wechat's unique capabilities such as Wechat sharing, scanning, card coupons, and payment to provide Wechat users with a better web experience.

JSSDK use step 1: bind a domain name

Log in to the Wechat public platform and enter the "function Settings" of "official account Settings" to fill in "JS API Security Domain name".

Note: after logging in, you can view the corresponding API permissions in the developer Center.

Step 2: introduce the JS file

Introduce the following JS file (https is supported) on the page that needs to call the JS API: http://www.php.cn/

Note: AMD/CMD standard module loading method is supported.

Step 3: verify the configuration by injecting permissions through the config interface

All pages that need to use JS-SDK must first inject configuration information, otherwise they cannot be called (the same url only needs to be called once. Web app for SPA that changes url can be called each time the url changes. Currently, Android Wechat client does not support the new H5 feature of pushState, so pages using pushState to implement web app will cause signature failure, which will be fixed in Android6.2).

Wx.config ({debug: true, / / enables debug mode. The returned values of all api called will be displayed in the alert on the client side. To view the parameters passed, you can open them on the PC side, and the parameter information will be typed out through log and printed only on the PC side. AppId:'', / / required, unique identification of official account timestamp:, / / required, timestamp nonceStr:'', / / required to generate signature, random string signature:'', / / required, signature generated, see Appendix 1 jsApiList: [] / / required, list of JS APIs to be used, list of all JS APIs see Appendix 2}) Step 4: successfully verify the wx.ready through the ready API processing (function () {/ / config information verification will execute the ready method. All API calls must be performed after the config API obtains the result. Config is an asynchronous operation on the client side, so if you need to call the relevant API when the page is loaded, you must call the relevant API in the ready function to ensure correct execution. Interfaces that are called only when triggered by the user can be called directly and do not need to be placed in the ready function. Step 5: verify the failure of wx.error through the error API (function (res) {/ / config information verification failure will execute the error function. If the signature expires and the verification fails, the specific error information can be viewed in the debug mode of config or in the returned res parameter. For SPA, you can update the signature here. }); description of API call

All APIs are called through wx objects (you can also use jWeixin objects). The parameter is an object. In addition to the parameters to be passed by each API itself, there are also the following common parameters:

Success: the callback function that is executed when the API is called successfully.

Fail: the callback function that is executed when the API call fails.

Complete: the callback function that is executed when the API call is completed, regardless of success or failure.

Cancel: the callback function when the user clicks cancel. Only part of the api with the user canceling operation will be used.

Trigger: listens to the method that is triggered when a button is clicked in Menu. This method supports only the relevant interfaces in Menu.

Note: do not try to use ajax asynchronous request in trigger to modify the content of this sharing, because the client sharing operation is a synchronous operation, and the return packet using ajax has not yet been returned.

The above functions all take a parameter of type object, in addition to the data returned by each interface itself, there is also a general property errMsg, whose value format is as follows:

When the call is successful: "xxx:ok", where xxx is the API name of the call

When the user cancels: "xxx:cancel", where xxx is the name of the calling API

When the call fails: the value is the specific error message

/ Wechat parameter preparation / private void WxSdkPramas (bool isShare) {var jsSdk = new JSSDKHelper (); / / get the timestamp var timestamp = JSSDKHelper.GetTimestamp (); / / get the random code var nonceStr = JSSDKHelper.GetNoncestr (); var appId = WeiXinAppId Var appSecret = WeiXinAppSecret; / / get ticket var jsTicket = JsApiTicketContainer.TryGetTicket (appId, appSecret); / / get signature var signature = jsSdk.GetSignature (jsTicket, nonceStr, timestamp, Request.Url.AbsoluteUri); ViewData ["AppId"] = appId; ViewData ["Timestamp"] = timestamp ViewData ["NonceStr"] = nonceStr; ViewData ["Signature"] = signature;}

Here is the code related to js:

Official account JSSDK demonstrates wx.config ({debug: false, / / enable debug mode. The returned values of all api called will be displayed on the client side alert. To view the passed parameters, you can open them on the PC side, and the parameter information will be typed out via log and printed only on the PC side. AppId:'@ ViewData ["AppId"]', / / required, the unique ID of the official account timestamp:'@ ViewData ["Timestamp"]', / / required, the timestamp nonceStr:'@ ViewData ["NonceStr"]', / / required, and the random string signature:'@ ViewData ["Signature"]', / / required 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'] / / required A list of JS interfaces to be used. A list of all JS interfaces is shown in Appendix 2. For details, see: http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html}); wx.error (function (res) {console.log (res); alert ('verification failure');}); wx.ready (function () {var url = 'http://weixin.senparc.com'; Var link = url +'@ (Request.Url.PathAndQuery)'; var imgUrl = url +'/ images/v2/ewm_01.png' / / forward to wx.onMenuShareTimeline ({title: 'JSSDK WeChat moments forwarding test', link: link, imgUrl: imgUrl, success: function () {alert ('forwarding successful!') ;}, cancel: function () {alert ('forwarding failed!') ;}) / / forward to friends wx.onMenuShareAppMessage ({title: 'JSSDK moments retweet test', desc: 'forward to friends', link: link, imgUrl: imgUrl, type: 'link', dataUrl:'' Success: function () {alert ('forwarded successfully!') ;}, cancel: function () {alert ('forwarding failed!') ;}})

The Helper used above:

Public class JSSDKHelper {public JSSDKHelper () {Parameters = new Hashtable ();} protected Hashtable Parameters / set parameter value / 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 () } / get the random string / public static string GetNoncestr () {Random random = new Random (); return MD5Util.GetMD5 (random.Next (1000) .ToString (), "GBK") } / public static string GetTimestamp () {TimeSpan ts = DateTime.UtcNow-new DateTime (1970, 1, 1, 0, 0, 0, 0); return Convert.ToInt64 (ts.TotalSeconds). ToString () } / sha1 encryption / 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 () } / the encryption method for generating cardSign / 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 () } / get the signature of JS-SDK permission verification Signature / public string GetSignature (string ticket, string noncestr, string timestamp, string url) {/ / clear Parameters ClearParameter () SetParameter ("jsapi_ticket", ticket); SetParameter ("noncestr", noncestr); SetParameter ("timestamp", timestamp); SetParameter ("url", url); return CreateSha1 () } / get the location signature AddrSign / public string GetAddrSign (string appId, string appSecret, string noncestr, string timestamp, string url) {/ / clear 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 () } / get card coupon signature CardSign / public string GetCardSign (string appId, string appSecret, string locationId, string noncestr, string timestamp, string cardId String cardType) {/ / clear 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 () }} the above is all the contents of the article "sample Analysis of Wechat JSSDK developed by Wechat official account". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report