Table of Contents
Overview" >Overview
JSSDK usage steps" >JSSDK usage steps
## Step 1: Bind domain name" >## Step 1: Bind domain name
Step 2: Introduce JS files" >Step 2: Introduce JS files
Interface call instructions" >Interface call instructions
Home WeChat Applet WeChat Development WeChat JSSDK for WeChat public account development

WeChat JSSDK for WeChat public account development

Feb 22, 2017 pm 03:58 PM
WeChat public account

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!


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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1657
14
PHP Tutorial
1257
29
C# Tutorial
1229
24
Scrapy implements crawling and analysis of WeChat public account articles Scrapy implements crawling and analysis of WeChat public account articles Jun 22, 2023 am 09:41 AM

Scrapy implements article crawling and analysis of WeChat public accounts. WeChat is a popular social media application in recent years, and the public accounts operated in it also play a very important role. As we all know, WeChat public accounts are an ocean of information and knowledge, because each public account can publish articles, graphic messages and other information. This information can be widely used in many fields, such as media reports, academic research, etc. So, this article will introduce how to use the Scrapy framework to crawl and analyze WeChat public account articles. Scr

What are the differences between WeChat official account certification and non-certification? What are the differences between WeChat official account certification and non-certification? Sep 19, 2023 pm 02:15 PM

The difference between WeChat public account authentication and non-authentication lies in the authentication logo, function permissions, push frequency, interface permissions and user trust. Detailed introduction: 1. Certification logo. Certified public accounts will obtain the official certification logo, which is the blue V logo. This logo can increase the credibility and authority of the public account and make it easier for users to identify the real official public account; 2. Function permissions. Certified public accounts have more functions and permissions than uncertified public accounts. For example, certified public accounts can apply to activate the WeChat payment function to achieve online payment and commercial operations, etc.

Practical crawler combat in Python: WeChat public account crawler Practical crawler combat in Python: WeChat public account crawler Jun 10, 2023 am 09:01 AM

Python is an elegant programming language with powerful data processing and web crawling capabilities. In this digital era, the Internet is filled with a large amount of data, and crawlers have become an important means of obtaining data. Therefore, Python crawlers are widely used in data analysis and mining. In this article, we will introduce how to use Python crawler to obtain WeChat public account article information. WeChat official account is a popular social media platform for publishing articles online and is an important tool for promotion and marketing of many companies and self-media.

Use PHP to build a WeChat public account API interface Use PHP to build a WeChat public account API interface May 13, 2023 pm 12:01 PM

In today's Internet era, WeChat official accounts have become an important marketing channel for more and more companies. If you want your WeChat official account to implement more functions, you often need to write corresponding interfaces. This article will use PHP language as an example to introduce how to build a WeChat public account API interface. 1. Preparation Before writing the WeChat public account API interface, the developer needs to have a WeChat public account and apply for developer interface permissions in the WeChat public platform. After the application is successful, you can obtain the relevant developer AppID and AppSe

How to use Laravel to develop an online ordering system based on WeChat public account How to use Laravel to develop an online ordering system based on WeChat public account Nov 02, 2023 am 09:42 AM

How to use Laravel to develop an online ordering system based on WeChat official accounts. With the widespread use of WeChat official accounts, more and more companies are beginning to use them as an important channel for online marketing. In the catering industry, developing an online ordering system based on WeChat public accounts can improve the efficiency and sales of enterprises. This article will introduce how to use the Laravel framework to develop such a system and provide specific code examples. Project preparation First, you need to ensure that the Laravel framework has been installed in the local environment. OK

Can the official account only post one article per day? Can the official account only post one article per day? Jun 16, 2023 pm 02:04 PM

The public account can not only post one article per day, but can publish up to eight articles at a time. How to publish multiple articles: 1. Click "Material Management" on the left, and then click "New Graphic and Text Material" to start editing. First article; 2. After editing the first article, click the + sign under the first article on the left and click "Graphic Message" to edit the second article; 3. After finishing multiple images and text, click " Save and send in bulk" to complete the publishing of multiple articles.

Build WeChat public account application using Go language framework Build WeChat public account application using Go language framework Jun 04, 2023 am 10:40 AM

With the popularity of the Internet and the widespread use of mobile devices, WeChat official accounts have become an indispensable part of corporate marketing. Through WeChat public accounts, companies can easily interact with users, promote products and services, and increase brand awareness. In order to better develop WeChat public account applications, more and more developers and companies choose to use Go language to build WeChat public account applications. Go language is a programming language developed by Google. Its syntax is concise and suitable for building high-performance, high-concurrency real-time applications. In terms of ease of use and

PHP and WeChat public account development guide PHP and WeChat public account development guide Jun 11, 2023 pm 03:31 PM

With the gradual popularity of WeChat public accounts in social networks, more and more developers have begun to get involved in the field of WeChat public account development. Among them, PHP, as a common back-end programming language, has also begun to be widely used in the development of WeChat public accounts. This article will introduce the basic knowledge and common techniques of PHP in WeChat public account development. 1. Basics of PHP and WeChat public account development WeChat public account development WeChat public account refers to an Internet application based on the WeChat platform, which can provide users with different types of services and content, such as information push

See all articles