WeChat JSSDK for WeChat public account development

高洛峰
Release: 2017-02-22 15:58:46
Original
2325 people have browsed it

Overview

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.

JSSDK usage steps

## Step 1: Bind domain name

First log in to the WeChat public platform and enter the "Function Settings" of "Public Account Settings" to fill in the "JS Interface Security Domain Name".

Note: After logging in, you can view the corresponding interface permissions in the "Developer Center".

Step 2: Introduce JS files

Introduction to the page where the JS interface needs to be called, introduce the following JS files (https is supported): http:/ /www.php.cn/

Remarks: Supports loading using AMD/CMD standard module loading method

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
});
Copy after login

Step 4: Process successful verification through the ready interface
wx.ready(function(){

    // config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。
});
Copy after login

Step 5: Handle failed verification through error interface
wx.error(function(res){

    // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。

});
Copy after login

Interface call instructions

All interfaces pass wx objects (also It can be called using jWeixin object). The parameter is an object. In addition to the parameters that need to be passed by each interface itself, there are also the following general parameters:


    1. success: The callback function executed when the interface call is successful.

    2. fail: The callback function executed when the interface call fails.

    3. complete: The callback function executed when the interface call is completed, regardless of success or failure.

    4. cancel: The callback function when the user clicks cancel. It is only used by some APIs where the user cancels the operation.

    5. trigger: A method that is triggered when a button in the Menu is clicked. This method only supports related interfaces in the Menu.

Note: Do not try to use ajax asynchronous request in trigger to modify the content of this share, because the client sharing operation is a synchronous operation, use ajax return packet at this time Will have not returned yet.

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:

    1. When the call is successful: "xxx:ok", where xxx is the interface name of the call

    2. When the user cancels: "xxx:cancel" , where xxx is the name of the called interface

    3. When the call fails: its value is the specific error message

    /// <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;
            }
    Copy after login
    below It is js related code:
  1. <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: &#39;@ViewData["AppId"]&#39;, // 必填,公众号的唯一标识
                timestamp: &#39;@ViewData["Timestamp"]&#39;, // 必填,生成签名的时间戳
                nonceStr: &#39;@ViewData["NonceStr"]&#39;, // 必填,生成签名的随机串
                signature: &#39;@ViewData["Signature"]&#39;,// 必填,签名
                jsApiList: [
                      "checkJsApi",
                        &#39;onMenuShareTimeline&#39;,
                        &#39;onMenuShareAppMessage&#39;,
                        &#39;onMenuShareQQ&#39;,
                        &#39;onMenuShareWeibo&#39;,
                        &#39;hideMenuItems&#39;,
                        &#39;showMenuItems&#39;,
                        &#39;hideAllNonBaseMenuItem&#39;,
                        &#39;showAllNonBaseMenuItem&#39;,
                        &#39;translateVoice&#39;,
                        &#39;startRecord&#39;,
                        &#39;stopRecord&#39;,
                        &#39;onRecordEnd&#39;,
                        &#39;playVoice&#39;,
                        &#39;pauseVoice&#39;,
                        &#39;stopVoice&#39;,
                        &#39;uploadVoice&#39;,
                        &#39;downloadVoice&#39;,
                        &#39;chooseImage&#39;,
                        &#39;previewImage&#39;,
                        &#39;uploadImage&#39;,
                        &#39;downloadImage&#39;,
                        &#39;getNetworkType&#39;,
                        &#39;openLocation&#39;,
                        &#39;getLocation&#39;,
                        &#39;hideOptionMenu&#39;,
                        &#39;showOptionMenu&#39;,
                        &#39;closeWindow&#39;,
                        &#39;scanQRCode&#39;,
                        &#39;chooseWXPay&#39;,
                        &#39;openProductSpecificView&#39;,
                        &#39;addCard&#39;,
                        &#39;chooseCard&#39;,
                        &#39;openCard&#39;
                ] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2。详见:http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html
            });
            wx.error(function (res) {
                console.log(res);
                alert(&#39;验证失败&#39;);
            });
            wx.ready(function () {
                var url = &#39;http://weixin.senparc.com&#39;;
                var link = url + &#39;@(Request.Url.PathAndQuery)&#39;;
                var imgUrl = url + &#39;/images/v2/ewm_01.png&#39;;
                //转发到朋友圈
                wx.onMenuShareTimeline({
                    title: &#39;JSSDK朋友圈转发测试&#39;,
                    link: link,
                    imgUrl: imgUrl,
                    success: function () {
                        alert(&#39;转发成功!&#39;);
                    },
                    cancel: function () {
                        alert(&#39;转发失败!&#39;);
                    }
                });
                //转发给朋友
                wx.onMenuShareAppMessage({
                    title: &#39;JSSDK朋友圈转发测试&#39;,
                    desc: &#39;转发给朋友&#39;,
                    link: link,
                    imgUrl: imgUrl,
                    type: &#39;link&#39;,
                    dataUrl: &#39;&#39;,
                    success: function () {
                        alert(&#39;转发成功!&#39;);
                    },
                    cancel: function () {
                        alert(&#39;转发失败!&#39;);
                    }
                });
            });
        </script>
    </head>
    Copy after login
The Helper used above:

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();
        }
    }
Copy after login
For more articles related to WeChat JSSDK for WeChat public account development, please pay attention to the PHP Chinese website!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template