This article has shared a detailed version of the js WeChat interface for your reference. The specific content is as follows
Basic instructions
Instructions for use
1.Introduce JS files
Introduce the following JS file on the page that needs to call the JS interface (support https): http://res.wx.qq.com/open/js/jweixin-1.0.0.js
Note: Support loading using AMD/CMD standard module loading method
2. Inject and configure the config interface
All pages that need to use JSSDK must first inject configuration information, otherwise they will not be called (the same url needs to be called only once, and the web app of the SPA that changes the url can be called every time the url changes).
wx.config({ debug: true, // Turn on debug mode, the return values of all APIs called will be alerted on the client. To view the passed parameters, you can open them on the PC side, the parameter information will be printed through the log and will only be printed on the PC side. appId: '', // Required, the unique identifier of the official account timestamp: , // Required, the timestamp generated for the signature nonceStr: '', // Required, the random string generated for the signature signature: '', // Required, the signature is shown in Appendix 1 jsApiList: [] // Required, the list of JS interfaces to be used, and all JS interfaces are listed in Appendix 2});3. Verify through the ready interface
wx.ready(function(){ // After config information is verified, the ready method will be executed. All interface calls must be obtained after the config interface obtains the result. config is an asynchronous operation of a client. Therefore, if you need to call the relevant interface when the page is loaded, the relevant interface must be placed in the ready function to ensure correct execution. For interfaces that are called only when the user triggers, they can be called directly, and do not need to be placed in the ready function. });4. Verification failed error interface
wx.error(function(res){// If the config information fails to verify, the error function will be executed. If the signature expires, the verification will fail. For specific error messages, you can open the debug mode of config to view, or you can view it in the returned res parameter. For SPAs, you can update the signature here. });Interface call instructions
All interfaces are called through wx objects (can also be used with jWeixin objects). The parameters are an object. In addition to the parameters that each interface itself needs to pass, there are also the following general parameters:
1. success: The callback function executed when the interface is called successfully.
2. Fail: A callback function executed when the interface calls fail.
3. complete: The callback function executed when the interface call is completed, and will be executed regardless of success or failure.
4. cancel: The callback function when the user clicks to cancel, only some APIs that have users cancel operations will be used.
5. trigger: A method that listens to the trigger when a button is clicked in Menu. This method only supports related interfaces in Menu.
The above functions all have a parameter, type object, in addition to the data returned by each interface itself, there is also a common property 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 called interface name
3. When the call fails: its value is specific error message
Basic interface
Determine whether the current client version supports the specified JS interface
wx.checkJsApi({jsApiList: ['chooseImage'] // The list of JS interfaces that need to be detected, all JS interfaces are listed in Appendix 2, success: function(res) {// Return as key-value pairs, the available api value is true, and not available as false// For example: {"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}});Sharing interface
Get the click status of the "Share to Moments" button and customize the sharing content interface
wx.onMenuShareTimeline({ title: '', // Share title link: '', // Share link imgUrl: '', // Share icon success: function () { // Callback function executed after user confirms sharing}, cancel: function () { // Callback function executed after user cancels sharing}});Get the click status of the "Share to Friends" button and customize the sharing content interface
wx.onMenuShareAppMessage({ title: '', // Share title desc: '', // Share description link: '', // Share link imgUrl: '', // Share icon type: '', // Share type, music, video or link, do not fill in the default linkdataUrl: '', // If the type is music or video, you need to provide a data link, the default is empty success: function () { // Callback function executed after the user confirms the sharing}, cancel: function () { // Callback function executed after the user cancels the sharing}});Get the click status of the "Share to QQ" button and customize the sharing content interface
wx.onMenuShareQQ({ title: '', // Share title desc: '', // Share description link: '', // Share link imgUrl: '' // Share icon success: function () { // Callback function executed after the user confirms the sharing}, cancel: function () { // Callback function executed after the user cancels the sharing}});Get the click status of the "Share to Tencent Weibo" button and customize the sharing content interface
wx.onMenuShareWeibo({ title: '', // Share title desc: '', // Share description link: '', // Share link imgUrl: '' // Share icon success: function () { // Callback function executed after the user confirms the sharing}, cancel: function () { // Callback function executed after the user cancels the sharing}});Image interface
Take a picture or select a picture from the mobile phone album interface
wx.chooseImage({ success: function (res) { var localIds = res.localIds; // Returns the local ID list of the selected photo. localId can display pictures as the src attribute of the img tag}});Preview picture interface
wx.previewImage({ current: '', // The currently displayed image link urls: [] // The list of image links that need to be previewed});Upload image interface
wx.uploadImage({localId: '', // The local ID of the image to be uploaded, obtained from the choiceImage interface isShowProgressTips: 1// The default is 1, and the progress prompt is displayed success: function (res) { var serverId = res.serverId; // Return the server ID of the image }});Note: You can download the uploaded picture by WeChat using the multimedia file interface. The serverId obtained here is media_id. Reference document../12/58bfcfabbd501c7cd77c19bd9cfa8354.html
Download picture interface
wx.downloadImage({serverId: '', // The server-side ID of the image to be downloaded, obtained from the uploadImage interface isShowProgressTips: 1// The default is 1, and the progress prompt is displayed success: function (res) { var localId = res.localId; // Return to the local ID after the image is downloaded }});Audio interface
Start recording interface
wx.startRecord();
Stop recording interface
wx.stopRecord({ success: function (res) { var localId = res.localId; }});Automatic stop interface for monitoring recording
wx.onVoiceRecordEnd({ // Complete callback will be executed when the recording time exceeds one minute and does not stop. Complete: function (res) {var localId = res.localId; }});Play voice interface
wx.playVoice({ localId: '' // The local ID of the audio to be played, obtained by the stopRecord interface});Pause playback interface
wx.pauseVoice({ localId: '' // The local ID of the audio that needs to be paused, obtained by the stopRecord interface});Stop playback interface
wx.stopVoice({ localId: '' // The local ID of the audio that needs to be stopped, obtained by the stopRecord interface});Monitoring voice playback interface
wx.onVoicePlayEnd({ serverId: '', // The server-side ID of the audio that needs to be downloaded, obtain success: function (res) { var localId = res.localId; // Return the local ID of the audio }});Upload voice interface
wx.uploadVoice({localId: '', // The local ID of the audio that needs to be uploaded, obtained from the stopRecord interface isShowProgressTips: 1// The default is 1, displaying the progress prompt success: function (res) { var serverId = res.serverId; // Return the server-side ID of the audio }});Note: You can download the uploaded voice by WeChat's multimedia file interface. The serverId obtained here is media_id. Reference document../12/58bfcfabbd501c7cd77c19bd9cfa8354.html
Download voice interface
wx.downloadVoice({serverId: '', // The server-side ID of the audio that needs to be downloaded, obtained from the uploadVoice interface isShowProgressTips: 1// The default is 1, and the progress prompt is displayed success: function (res) { var localId = res.localId; // Return the local ID of the audio }});Intelligent interface
Identify audio and return to the recognition result interface
wx.translateVoice({localId: '', // The local Id of the audio that needs to be recognized, isShowProgressTips: 1, // The default is 1, displaying progress prompt success: function (res) {alert(res.translateResult); // The result of voice recognition}});Equipment Information
Obtain the network status interface
wx.getNetworkType({ success: function (res) { var networkType = res.networkType; // Return network types 2g, 3g, 4g, wifi }});Geographical location
Use the built-in map of WeChat to view location interface
wx.openLocation({ latitude: 0, // Latitude, floating point number, range is 90 ~ -90 longitude: 0, // Longitude, floating point number, range is 180 ~ -180. name: '', // Location name address: '', // Address details scale: 1, // Map zoom level, shaping value, range from 1 ~ 28. The default is the maximum infoUrl: '' // The hyperlink displayed at the bottom of the viewing position interface, you can click to jump});Get the geolocation interface
wx.getLocation({ timestamp: 0, // Position signature timestamp, provided nonceStr: '', // Position signature random string, provided only when compatible with version 6.0.2, addrSign: '', // Position signature, provided only when compatible with version 6.0.2, see Appendix 4 for details. success: function (res) { var longitude = res.longitude; // Latitude, floating point number, range 90 ~ -90 var latitude = res.latitude; // Longitude, floating point number, range 180 ~ -180. var speed = res.speed; // Speed, counted in meters/per second var accuracy = res.accuracy; // Position accuracy}});Interface operation
Hide the menu interface wx.hideOptionMenu() in the upper right corner;
Show the menu interface wx.showOptionMenu() in the upper right corner;
Close the current web window interface wx.closeWindow();
Batch Hide Function Button Interface
wx.hideMenuItems({ menuList: [] // To hide menu items, see Appendix 3});Batch display function button interface
wx.showMenuItems({ menuList: [] // All menu items to be displayed are shown in Appendix 3});Hide all non-base button interfaces wx.hideAllNonBaseMenuItem();
Show all function button interface wx.showAllNonBaseMenuItem();
Scan the WeChat
Click on the WeChat scan interface
wx.scanQRCode({desc: 'scanQRCode desc',needResult: 0, // The default is 0, the scan result is processed by WeChat, and 1 directly returns the scan result, scanType: ["qrCode","barCode"], // You can specify whether to scan the QR code or the 1R code. Both defaults to success: function () {var result = res.resultStr; // When needResult is 1, the result returned by scanning the code}});Harvest address
Edit delivery address interface
wx.editAddress( timestamp: 0, // Location signature timestamp, only if it needs to be compatible with version 6.0.2, nonceStr: '', // Location signature random string, only if it needs to be compatible with version 6.0.2, addrSign: '', // Location signature, only if it needs to be compatible with version 6.0.2, see Appendix 4 for details. success: function (res) { var userName = res.userName; // Consignee name var telNumber = res.telNumber; // Consignee phone number var postalCode = res.postalCode; // Postcode var provinceName = res.provinceName; // National standard delivery address first level address var cityName = res.cityName; // National standard delivery address second level address var countryName = res.countryName; // National standard delivery address third level address var address var address = res.address; // Detailed delivery address information var nationalCode = res.nationalCode; // National delivery address country code }});Get the nearest delivery address interface
wx.getLatestAddress({ timestamp: 0, // Location signature timestamp, only if it needs to be compatible with version 6.0.2, nonceStr: '', // Location signature random string, only if it needs to be compatible with version 6.0.2, addrSign: '', // Location signature, only if it needs to be compatible with version 6.0.2, see Appendix 4 for details. success: function (res) { var userName = res.userName; // Consignee name var telNumber = res.telNumber; // Consignee phone number var postalCode = res.postalCode; // Postcode var provinceName = res.provinceName; // National standard delivery address first level address var cityName = res.cityName; // National standard delivery address second level address var countryName = res.countryName; // National standard delivery address third level address var address var address = res.address; // Detailed delivery address information var nationalCode = res.nationalCode; // National delivery address country code }});WeChat store
Jump to WeChat product page interface
wx.openProductSpecificView({productId: '', // Product idviewType: '' // 0. Default value, ordinary product details page 1. Scan the product details page 2. Store product details page });WeChat card coupon
Release the list of card coupons for stores and get the user selection list
wx.chooseCard({ shopId: '', // Store Id cardType: '', // Card type cardId: '', // Card Id timeStamp: 0, // Card Id timestamp: nonceStr: '', // Card Voucher signature random string cardSign: '', // Card Voucher signature, see Appendix 6 for details. success: function (res) { var cardList= res.cardList; // Card Voucher list information selected by the user}});Add card coupon interface in batches
wx.addCard({cardList: [{cardId: '',cardExt: ''}], // The card coupon list that needs to be added success: function (res) { var cardList = res.cardList; // The card coupon list information }});Check the card coupon interface in the WeChat card package
wx.openCard({cardList: [{cardId: '',code: ''}]// List of card coupons to be opened});WeChat Payment
Initiate a WeChat payment request
wx.chooseWXPay({timestamp: 0, // Payment signature timestamp noncestr: '', // Payment signature random string package: '', // Order details are extended string, see Appendix 5, paySign: '', // Payment signatures are for details, see Appendix 5});Appendix 1 - JSSDK permission signature algorithm
jsapi_ticket
Before generating a signature, you must first understand jsapi_ticket. jsapi_ticket is a temporary ticket used by the official account to call the WeChat JS interface. Under normal circumstances, the validity period of jsapi_ticket is 7200 seconds, which is obtained through access_token. Since the number of API calls to obtain jsapi_ticket is very limited, frequent refresh of jsapi_ticket will cause API calls to be limited and affect their own business. Developers must cache jsapi_ticket globally in their services.
1. Refer to the following document to obtain access_token (valid for 7200 seconds, developers must cache access_token globally in their service): ../12/4b08382e91217687730a2dfc71e9218c.html
2. Use the access_token obtained in the first step to request the jsapi_ticket (valid for 7200 seconds, the developer must cache jsapi_ticket globally in his service): https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi
Successfully returns the following JSON:
{"errcode":0,"errmsg":"ok","ticket":"bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA","expires_in":7200}After obtaining jsapi_ticket, you can generate a signature for JSSDK permission verification.
Signature Algorithm
The signature generation rules are as follows: the fields participating in the signature include noncestr (random string), valid jsapi_ticket, timestamp (timestamp), url (the URL of the current web page, not including # and its subsequent parts). After sorting all parameters to be signed from small to large (dictionary order) according to the ASCII code of the field name, the format of the URL key-value pair (that is, key1=value1&key2=value2…) is used to splice into a string string1. It should be noted here that all parameter names are lowercase characters. String1 is encrypted, and the field name and field value are both original values and no URL escape is performed.
That is, signature=sha1(string1). Example:
• noncestr=Wm3WZYTPz0wzccnW
• jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg
• timestamp=1414587457
• url=http://mp.weixin.qq.com
Step 1. After sorting all the parameters to be signed from small to large (dictionary order) according to the ASCII code of the field name, splice them into string string1 using the format of the URL key-value pair (that is, key1=value1&key2=value2…):
jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg&noncestr=Wm3WZYTPz0wzccnW×tamp=1414587457&url=http://mp.weixin.qq.com
Step 2. Sign string1 with sha1 and get signature:
f4d90daf4b3bca3078ab155816175ba34c443a7b
Things to note
1. The noncestr and timestamp used for signature must be the same as the nonceStr and timestamp in wx.config.
2. The url used for signature must be the complete URL of the page calling the JS interface.
3. For security reasons, developers must implement signature logic on the server side.
Appendix 2 - List of all JS interfaces
• onMenuShareTimeline
• onMenuShareAppMessage
• onMenuShareQQ
• onMenuShareWeibo
• startRecord
• stopRecord
• onVoiceRecordEnd
• playVoice
• pauseVoice
• stopVoice
• onVoicePlayEnd
• uploadVoice
• downloadVoice
• chooseImage
• previewImage
• uploadImage
• downloadImage
• translateVoice
• getNetworkType
• openLocation
• getLocation
• hideOptionMenu
• showOptionMenu
• hideMenuItems
• showMenuItems
• hideAllNonBaseMenuItem
• showAllNonBaseMenuItem
• closeWindow
• scanQRCode
• chooseWXPay
• getLatestAddress
• editAddress
• openProductSpecificView
• addCard
• chooseCard
• openCard
Appendix 3 - List of all buttons
Basic categories
• Report: "menuItem:exposeArticle"
• Adjust the font: "menuItem:setFont"
• Daytime mode: "menuItem:dayMode"
• Night Mode: "menuItem:nightMode"
• Refresh: "menuItem:refresh"
• View official account (added): "menuItem:profile"
• View official account (not added): "menuItem:addContact"
Communication category
• Send to a friend: "menuItem:share:appMessage"
• Share to Moments: "menuItem:share:timeline"
• Share to QQ: "menuItem:share:qq"
• Share to Weibo: "menuItem:share:weiboApp"
• Collection: "menuItem:favorite"
• Share to FB: "menuItem:share:facebook"
Protection class
• Debug: "menuItem:jsDebug"
• Edit tag: "menuItem:editTag"
• Delete: "menuItem:delete"
• Copy link: "menuItem:copyUrl"
• Original web page: "menuItem:originPage"
• Reading mode: "menuItem:readMode"
• Open in QQ browser: "menuItem:openWithQQBrowser"
• Open in Safari: "menuItem:openWithSafari"
• Email: "menuItem:share:email"
• Some special public accounts: "menuItem:share:brand"
Appendix 4 - Location and Address Signature Generation Algorithm
The generation rules of addrSign are the same as those of JSSDK permission verification (see Appendix 1), but the participating signature parameters are different. The signature parameters participating in addrSign are: appId, url (current web url), timestamp, noncestr, accessoken (user authorization credentials, please refer to the oauth2.0 protocol to obtain).
Appendix 5 - Payment extension field and signature generation algorithm
Order details (package) extension string definition
When the merchant redirects the JS API, the merchant needs to determine the order details at this time and combine the order details into the package in a certain way. After the JS API is called, WeChat will generate a prepayment order through the content of the package. The following will define the required field list and signature method for the package. Interface needs to be noted: All incoming parameters are string types!
This article has been compiled into "Summary of JavaScript WeChat Development Skills", and everyone is welcome to learn and read.
I would like to recommend a tutorial on WeChat mini program that is highly concerned: "WeChat Mini Program Development Tutorial" has been carefully compiled by the editor of everyone, I hope you like it.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.