Home Web Front-end JS Tutorial WeChat JS interface summary and detailed explanation of usage_javascript skills

WeChat JS interface summary and detailed explanation of usage_javascript skills

May 16, 2016 pm 04:21 PM
WeChat

Basic instructions

Instructions for use

1. Import JS files
Introduce the following JS file into the page that needs to call the JS interface (supports https): http://res.wx.qq.com/open/js/jweixin-1.0.0.js

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

2. Inject the configuration config interface
All pages that need to use JSSDK 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).

Copy code The code is as follows:

wx.config({
debug: true, // Turn on debugging mode. The return values ​​of all api calls will be alerted on the client side. If you want to view the incoming parameters, you can open it on the PC side. The parameter information will be printed out through the log, only on the PC side. will print.
appId: '', // Required, the unique identifier of the official account
timestamp: , // Required, timestamp to generate signature
nonceStr: '', // Required, generate a random string of signature
signature: '',//Required, signature, see Appendix 1
jsApiList: [] // Required, a list of JS interfaces that need to be used. For a list of all JS interfaces, see Appendix 2
});

3. Verify through the ready interface

Copy code The code is as follows:

wx.ready(function(){

// The ready method will be executed after the config information is verified. All interface calls must be made after the config interface obtains the result. config is an asynchronous operation on the client side, so if you need to call the relevant interface when the page is loaded, you must put the relevant The interface is called in the ready function to ensure correct execution. For interfaces that are called only when triggered by the user, they can be called directly and do not need to be placed in the ready function.
});

4. Verification failure error interface

Copy code The code is as follows:

wx.error(function(res){
// If the config information verification fails, the error function will be executed. If the signature expires and the verification fails, the specific error information can be viewed by opening the debug mode of the config or in the returned res parameter. For SPA, the signature can be updated here.
});

Interface calling instructions
All interfaces are called through wx objects (jWeixin objects can also be used). The parameter is an object. In addition to the parameters that need to be passed by each interface itself, there are also the following common 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 name of the called interface
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

Basic interface
Determine whether the current client version supports the specified JS interface

Copy code The code is as follows:

wx.checkJsApi({
jsApiList: ['chooseImage'] // List of JS interfaces that need to be detected. See Appendix 2 for the list of all JS interfaces,
success: function(res) {
//Return in the form of key-value pairs, the available API value is true, and the unavailable API value is 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

Copy code The code is as follows:

wx.onMenuShareTimeline({
Title: '', // Share title
Link: '', // Share link
imgUrl: '', // Share icon
success: function () {
//Callback function executed after the user confirms sharing
},
cancel: function () {
//Callback function executed after the user cancels sharing
}
});

Get the "Share to Friends" button click status and customize the sharing content interface

Copy code The code is as follows:

wx.onMenuShareAppMessage({
Title: '', // Share title
desc: '', // Share description
Link: '', // Share link
imgUrl: '', // Share icon
Type: '', // Sharing type, music, video or link, if left blank, the default is link
dataUrl: '', // If type is music or video, a data link must be provided, which is empty by default
success: function () {
//Callback function executed after the user confirms sharing
},
cancel: function () {
//Callback function executed after the user cancels sharing
}
});

Get the "Share to QQ" button click status and customize the sharing content interface

Copy code The code is as follows:

wx.onMenuShareQQ({
Title: '', // Share title
desc: '', // Share description
Link: '', // Share link
imgUrl: '' // Share icon
success: function () {
//Callback function executed after the user confirms sharing
},
cancel: function () {
//Callback function executed after the user cancels sharing
}
});

Get the click status of the "Share to Tencent Weibo" button and customize the sharing content interface

Copy code The code is as follows:

wx.onMenuShareWeibo({
Title: '', // Share title
desc: '', // Share description
Link: '', // Share link
imgUrl: '' // Share icon
success: function () {
//Callback function executed after the user confirms sharing
},
cancel: function () {
//Callback function executed after the user cancels sharing
}
});

Image interface

Interface for taking pictures or selecting pictures from the mobile phone album

Copy code The code is as follows:

wx.chooseImage({
Success: function (res) {
            var localIds = res.localIds; // Return the local ID list of the selected photo, localId can be used as the src attribute of the img tag to display the image
}
});

Preview picture interface

Copy code The code is as follows:

wx.previewImage({
Current: '', // Currently displayed image link
urls: [] // List of image links that need to be previewed
});

Upload picture interface

Copy code The code is as follows:

wx.uploadImage({
localId: '', // The local ID of the image to be uploaded, obtained through the chooseImage interface
isShowProgressTips: 1// The default is 1, showing progress tips
Success: function (res) {
          var serverId = res.serverId; // Return the server ID of the image
}
});

Note: You can use the WeChat download multimedia file interface to download uploaded pictures. The serverId obtained here is media_id. Refer to the document../12/58bfcfabbd501c7cd77c19bd9cfa8354.html

Download picture interface

Copy code The code is as follows:

wx.downloadImage({
serverId: '', // The server ID of the image to be downloaded, obtained through the uploadImage interface
isShowProgressTips: 1// The default is 1, showing progress tips
Success: function (res) {
          var localId = res.localId; // Return the local ID after downloading the image
}
});

Audio Interface

Start recording interface

Copy code The code is as follows:

wx.startRecord();

Stop recording interface

Copy code The code is as follows:

wx.stopRecord({
Success: function (res) {
      var localId = res.localId;
}
});

Monitoring recording automatic stop interface

Copy code The code is as follows:

wx.onVoiceRecordEnd({
// The complete callback will be executed when the recording time exceeds one minute without stopping
complete: function (res) {
var localId = res.localId;
}
});

Play voice interface

Copy code The code is as follows:

wx.playVoice({
LocalId: '' // The local ID of the audio to be played, obtained through the stopRecord interface
});

Pause playback interface

Copy code The code is as follows:

wx.pauseVoice({
LocalId: '' // The local ID of the audio that needs to be paused, obtained through the stopRecord interface
});


Stop playback interface

Copy code The code is as follows:

wx.stopVoice({
LocalId: '' // The local ID of the audio that needs to be stopped, obtained through the stopRecord interface
});

Interface for monitoring voice playback completion

Copy code The code is as follows:

wx.onVoicePlayEnd({
ServerId: '', // The server ID of the audio to be downloaded is obtained through the uploadVoice interface
Success: function (res) {
          var localId = res.localId; // Return the local ID of the audio
}
});

Upload voice interface

Copy code The code is as follows:

wx.uploadVoice({
localId: '', // The local ID of the audio to be uploaded, obtained through the stopRecord interface
isShowProgressTips: 1// The default is 1, showing progress tips
Success: function (res) {
          var serverId = res.serverId; // Return the server ID of the audio
}
});

Note: The uploaded voice can be downloaded through the WeChat multimedia file download interface. The serverId obtained here is media_id, refer to the document../12/58bfcfabbd501c7cd77c19bd9cfa8354.html

Download voice interface

Copy code The code is as follows:

wx.downloadVoice({
serverId: '', // The server-side ID of the audio to be downloaded, obtained through the uploadVoice interface
isShowProgressTips: 1// The default is 1, showing progress tips
Success: function (res) {
          var localId = res.localId; // Return the local ID of the audio
}
});

Smart Interface

Recognize audio and return the recognition result interface

Copy code The code is as follows:

wx.translateVoice({
localId: '', // The local ID of the audio that needs to be recognized, obtained from the recording related interface
isShowProgressTips: 1, //The default is 1, showing progress tips
success: function (res) {
alert(res.translateResult); // Speech recognition results
}
});

Device Information

Get network status interface

Copy code The code is as follows:

wx.getNetworkType({
Success: function (res) {
           var networkType = res.networkType; // Return network type 2g, 3g, 4g, wifi
}
});

Geographical location

Use WeChat’s built-in map to view the location interface

Copy code The code is as follows:

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, ranging from 1 to 28. Default is max
infoUrl: '' // The hyperlink displayed at the bottom of the viewing location interface can be clicked to jump
});

Get geographical location interface

Copy code The code is as follows:

wx.getLocation({
Timestamp: 0, // Location signature timestamp, only provided when compatible with versions before 6.0.2
nonceStr: '', // Position signature random string, only provided when compatible with versions before 6.0.2
​​ addrSign: '', // Location signature, only provided when compatible with versions before 6.0.2, see Appendix 4
for details Success: function (res) {
           var longitude = res.longitude; // Latitude, floating point number, range is 90 ~ -90
        var latitude = res.latitude; // Longitude, floating point number, range is 180 ~ -180.
           var speed = res.speed; // Speed, in meters/second
        var accuracy = res.accuracy; // Position accuracy
}
});

Interface operation

Copy code The code is as follows:

Hide the menu interface in the upper right corner
wx.hideOptionMenu();
Display the menu interface in the upper right corner
wx.showOptionMenu();
Close the current web window interface
wx.closeWindow();
Batch hidden function button interface
wx.hideMenuItems({
menuList: [] // Menu items to be hidden, see Appendix 3 for all menu items
});
Batch display function button interface
wx.showMenuItems({
menuList: [] // Menu items to be displayed, see Appendix 3
for all menu items });
Hide all non-basic button interfaces
wx.hideAllNonBaseMenuItem();
Show all function button interfaces
wx.showAllNonBaseMenuItem();
Scan on WeChat
Open the WeChat scanning interface
wx.scanQRCode({
desc: 'scanQRCode desc',
needResult: 0, // The default is 0, the scan result is processed by WeChat, 1 returns the scan result directly,
scanType: ["qrCode","barCode"], // You can specify whether to scan a QR code or a 1D code, both are available by default
success: function () {
var result = res.resultStr; // When needResult is 1, the result returned by scanning the QR code
}
});

Harvest address

Edit shipping address interface

Copy code The code is as follows:

wx.editAddress(
Timestamp: 0, // Location signature timestamp, only provided when compatible with versions before 6.0.2
nonceStr: '', // Position signature random string, only provided when compatible with versions before 6.0.2
​​ addrSign: '', // Location signature, only provided when compatible with versions before 6.0.2, see Appendix 4
for details Success: function (res) {
          var userName = res.userName; // Consignee’s name
        var telNumber = res.telNumber; // Consignee’s phone number
        var postalCode = res.postalCode; // Postal code
           var provinceName = res.provinceName; // First-level address of national standard delivery 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 = res.address; // Detailed shipping address information
          var nationalCode = res.nationalCode; // Country code of shipping address
}
});

Get the nearest shipping address interface

Copy code The code is as follows:

wx.getLatestAddress({
Timestamp: 0, // Location signature timestamp, only provided when compatible with versions before 6.0.2
nonceStr: '', // Position signature random string, only provided when compatible with versions before 6.0.2
​​ addrSign: '', // Location signature, only provided when compatible with versions before 6.0.2, see Appendix 4
for details Success: function (res) {
          var userName = res.userName; // Consignee’s name
        var telNumber = res.telNumber; // Consignee’s phone number
        var postalCode = res.postalCode; // Postal code
           var provinceName = res.provinceName; // First-level address of national standard delivery 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 = res.address; // Detailed shipping address information
          var nationalCode = res.nationalCode; // Country code of shipping address
}
});

WeChat Store

Jump to WeChat product page interface

Copy code The code is as follows:

wx.openProductSpecificView({
productId: '', // product id
viewType: '' // 0. Default value, ordinary product details page 1. Scan product details page 2. Store product details page
});

WeChat Card Coupon

Calling up the list of cards and coupons applicable to the store and getting the user selection list

Copy code The code is as follows:

wx.chooseCard({
shopId: '', // StoreId
CardType: '', // Card type
CardId: '', // Card coupon Id
timeStamp: 0, // Card signature timestamp
nonceStr: '', // Card signature random string
cardSign: '', //Card and coupon signature, see Appendix 6
for details Success: function (res) {
        var cardList= res.cardList; // Card list information selected by the user
}
});

Batch adding interface for cards and coupons

Copy code The code is as follows:

wx.addCard({
cardList: [{
cardId: '',
cardExt: ''
}], // List of cards and coupons to be added
Success: function (res) {
          var cardList = res.cardList; // Added card and coupon list information
}
});

View the card and coupon interface in the WeChat card package

Copy code The code is as follows:

wx.openCard({
cardList: [{
cardId: '',
code: ''
}]// List of cards and coupons that need to be opened
});

WeChat Pay

Initiate a WeChat payment request

Copy code The code is as follows:

wx.chooseWXPay({
timestamp: 0, // Payment signature timestamp
noncestr: '', // Payment signature random string
package: '', // Order details extension string, see Appendix 5
for details paySign: '', // Payment signature, see Appendix 5 for details
});
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)

The difference between H5 and mini-programs and APPs The difference between H5 and mini-programs and APPs Apr 06, 2025 am 10:42 AM

H5. The main difference between mini programs and APP is: technical architecture: H5 is based on web technology, and mini programs and APP are independent applications. Experience and functions: H5 is light and easy to use, with limited functions; mini programs are lightweight and have good interactiveness; APPs are powerful and have smooth experience. Compatibility: H5 is cross-platform compatible, applets and APPs are restricted by the platform. Development cost: H5 has low development cost, medium mini programs, and highest APP. Applicable scenarios: H5 is suitable for information display, applets are suitable for lightweight applications, and APPs are suitable for complex functions.

Ouyi Exchange app domestic download tutorial Ouyi Exchange app domestic download tutorial Mar 21, 2025 pm 05:42 PM

This article provides a detailed guide to safe download of Ouyi OKX App in China. Due to restrictions on domestic app stores, users are advised to download the App through the official website of Ouyi OKX, or use the QR code provided by the official website to scan and download. During the download process, be sure to verify the official website address, check the application permissions, perform a security scan after installation, and enable two-factor verification. During use, please abide by local laws and regulations, use a safe network environment, protect account security, be vigilant against fraud, and invest rationally. This article is for reference only and does not constitute investment advice. Digital asset transactions are at your own risk.

What is the difference between H5 page production and WeChat applets What is the difference between H5 page production and WeChat applets Apr 05, 2025 pm 11:51 PM

H5 is more flexible and customizable, but requires skilled technology; mini programs are quick to get started and easy to maintain, but are limited by the WeChat framework.

What should I do if the company's security software conflicts with applications? How to troubleshoot HUES security software causes common software to fail to open? What should I do if the company's security software conflicts with applications? How to troubleshoot HUES security software causes common software to fail to open? Apr 01, 2025 pm 10:48 PM

Compatibility issues and troubleshooting methods for company security software and application. Many companies will install security software in order to ensure intranet security. However, security software sometimes...

How to solve the problem of JS resource caching in enterprise WeChat? How to solve the problem of JS resource caching in enterprise WeChat? Apr 04, 2025 pm 05:06 PM

Discussion on the JS resource caching issue of Enterprise WeChat. When upgrading project functions, some users often encounter situations where they fail to successfully upgrade, especially in the enterprise...

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to choose H5 and applets How to choose H5 and applets Apr 06, 2025 am 10:51 AM

The choice of H5 and applet depends on the requirements. For applications with cross-platform, rapid development and high scalability, choose H5; for applications with native experience, rich functions and platform dependencies, choose applets.

Detailed tutorial on how to buy and sell Binance virtual currency Detailed tutorial on how to buy and sell Binance virtual currency Mar 18, 2025 pm 01:36 PM

This article provides a brief guide to buying and selling of Binance virtual currency updated in 2025, and explains in detail the operation steps of virtual currency transactions on the Binance platform. The guide covers fiat currency purchase USDT, currency transaction purchase of other currencies (such as BTC), and selling operations, including market trading and limit trading. In addition, the guide also specifically reminds key risks such as payment security and network selection for fiat currency transactions, helping users to conduct Binance transactions safely and efficiently. Through this article, you can quickly master the skills of buying and selling virtual currencies on the Binance platform and reduce transaction risks.

See all articles