WeChat JSSDK for WeChat public account development
Feb 22, 2017 pm 03:58 PMOverview
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.miracleart.cn/ Remarks: Supports loading using AMD/CMD standard module loading methodStep 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,?//?開啟調(diào)試模式,調(diào)用的所有api的返回值會(huì)在客戶端alert出來,若要查看傳入的參數(shù),可以在pc端打開,參數(shù)信息會(huì)通過log打出,僅在pc端時(shí)才會(huì)打印。 ????appId:?'',?//?必填,公眾號(hào)的唯一標(biāo)識(shí) ????timestamp:?,?//?必填,生成簽名的時(shí)間戳 ????nonceStr:?'',?//?必填,生成簽名的隨機(jī)串 ????signature:?'',//?必填,簽名,見附錄1 ????jsApiList:?[]?//?必填,需要使用的JS接口列表,所有JS接口列表見附錄2 });
Step 4: Process successful verification through the ready interfacewx.ready(function(){
????//?config信息驗(yàn)證后會(huì)執(zhí)行ready方法,所有接口調(diào)用都必須在config接口獲得結(jié)果之后,config是一個(gè)客戶端的異步操作,所以如果需要在頁面加載時(shí)就調(diào)用相關(guān)接口,則須把相關(guān)接口放在ready函數(shù)中調(diào)用來確保正確執(zhí)行。對于用戶觸發(fā)時(shí)才調(diào)用的接口,則可以直接調(diào)用,不需要放在ready函數(shù)中。
});
Step 5: Handle failed verification through error interfacewx.error(function(res){
????//?config信息驗(yàn)證失敗會(huì)執(zhí)行error函數(shù),如簽名過期導(dǎo)致驗(yàn)證失敗,具體錯(cuò)誤信息可以打開config的debug模式查看,也可以在返回的res參數(shù)中查看,對于SPA可以在這里更新簽名。
});
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:- success: The callback function executed when the interface call is successful.
- fail: The callback function executed when the interface call fails.
- complete: The callback function executed when the interface call is completed, regardless of success or failure.
- cancel: The callback function when the user clicks cancel. It is only used by some APIs where the user cancels the operation.
- trigger: A method that is triggered when a button in the Menu is clicked. This method only supports related interfaces in the Menu.
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:
- When the call is successful: "xxx:ok", where xxx is the interface name of the call
- When the user cancels: "xxx:cancel" , where xxx is the name of the called interface
- When the call fails: its value is the specific error message
/// <summary> /// 微信參數(shù)準(zhǔn)備 /// </summary> private void WxSdkPramas(bool isShare) { var jsSdk = new JSSDKHelper(); //獲取時(shí)間戳 var timestamp = JSSDKHelper.GetTimestamp(); //獲取隨機(jī)碼 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; }
- below It is js related code:
<head> <meta name="viewport" content="width=device-width" /> <title>公眾號(hào)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, // 開啟調(diào)試模式,調(diào)用的所有api的返回值會(huì)在客戶端alert出來,若要查看傳入的參數(shù),可以在pc端打開,參數(shù)信息會(huì)通過log打出,僅在pc端時(shí)才會(huì)打印。 appId: '@ViewData["AppId"]', // 必填,公眾號(hào)的唯一標(biāo)識(shí) timestamp: '@ViewData["Timestamp"]', // 必填,生成簽名的時(shí)間戳 nonceStr: '@ViewData["NonceStr"]', // 必填,生成簽名的隨機(jī)串 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('驗(yàn)證失敗'); }); wx.ready(function () { var url = 'http://weixin.senparc.com'; var link = url + '@(Request.Url.PathAndQuery)'; var imgUrl = url + '/images/v2/ewm_01.png'; //轉(zhuǎn)發(fā)到朋友圈 wx.onMenuShareTimeline({ title: 'JSSDK朋友圈轉(zhuǎn)發(fā)測試', link: link, imgUrl: imgUrl, success: function () { alert('轉(zhuǎn)發(fā)成功!'); }, cancel: function () { alert('轉(zhuǎn)發(fā)失敗!'); } }); //轉(zhuǎn)發(fā)給朋友 wx.onMenuShareAppMessage({ title: 'JSSDK朋友圈轉(zhuǎn)發(fā)測試', desc: '轉(zhuǎn)發(fā)給朋友', link: link, imgUrl: imgUrl, type: 'link', dataUrl: '', success: function () { alert('轉(zhuǎn)發(fā)成功!'); }, cancel: function () { alert('轉(zhuǎn)發(fā)失?。?amp;#39;); } }); }); </script> </head>
public class JSSDKHelper { public JSSDKHelper() { Parameters = new Hashtable(); } protected Hashtable Parameters; /// <summary> /// 設(shè)置參數(shù)值 /// </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> /// 獲取隨機(jī)字符串 /// </summary> /// <returns></returns> public static string GetNoncestr() { Random random = new Random(); return MD5Util.GetMD5(random.Next(1000).ToString(), "GBK"); } /// <summary> /// 獲取時(shí)間戳 /// </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權(quán)限驗(yàn)證的簽名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(); } }For more articles related to WeChat JSSDK for WeChat public account development, please pay attention to the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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

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.

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.

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 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

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.

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

According to news from this website on August 1, the WeChat Public Platform Operations Center issued an article today saying that the platform found that some articles published by operators contain feudal superstitions and use religion, feng shui, fortune and other gimmicks to make money or gain attention. Such content is very likely Causing misleading or property damage to users. WeChat will conduct continuous inspections, and once any illegal content is discovered, corresponding actions will be taken according to the specific degree of the violation. The violation cases attached to this site are as follows: publishing superstition-related titles, using intimidation, inducement and other tones to exaggerate the harm or negative impact of a certain behavior. ▲Picture source WeChat Public Platform Operation Center, the same article below provides services with feudal superstitions such as fortune telling, fortune telling, and divination, and includes paid items, such as the sale of transshipment and disaster relief products. Improperly collecting users’ personal privacy information in the name of providing relevant services
