Index

1 Overview

1.1 JSSDK Steps

1.1.1 Step 1: Bind domain name

1.1.2 Step 2: Import JS file

1.1.3 Step 3: Verify the configuration via the config interface

1.1.4 Step 4: Successful verification via the ready interface

1.1.5 Step 5: Failure verification via the error interface

1.2 Interface call descriptions

2 Base interface

2.1 To determine whether the current client version supports the specified JS interface

3 Share interface

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

3.2 Get “Share to friends” button click status and customize the sharing content interface

3.3 Get “Share to QQ” button click status and customize the sharing content interface

3.4 Get “Share to Weibo”button click status and customize the sharing content interface

3.5 Get “Share to QZone” button click status and customize the sharing content interface

4 Image interface

4.1 Take a picture or choose a picture from phone album interface

4.2 Picture preview interface

4.3 Upload image interface

4.4 Download image interface

4.5 Get local image interface

5 Audio interface

5.1 Starts recording interface

5.2 Stops recording interface

5.3 Monitor recording automatically stop interface

5.4 Play voice message interface

5.5 Pause voice message interface

5.6 Stop voice message interface

5.7 Monitor voice message end interface

5.8 Upload voice message interface

5.9 Download voice message interface

6 Smart interface

6.1 Identify voice and return to identify result interface

7 Device Information

7.1 Get network status interface

​8 Location

8.1 Use Weixin built-in map to view location interface

8.2 Get location interface

9 Shake Nearby

9.1 Turn on search Nearby ibeacon device interface

9.2 Turn off search Nearby ibeacon device interface

9.3 Monitor Nearby ibeacon device interface

10 Interface operations

10.1 Hide upper right menu interface

10.2 Display upper right menu interface

10.3 Close current webpage interface

10.4 Hide function buttons in bulk interface

10.5 Display function buttons in bulk interface

10.6 Hide all non-base buttons interface

10.7 Display all non-base buttons interface

11 Weixin scan QR Code

11.1 Enable Weixin scan QR Code

12 Weixin Shop

12.1 Go to Weixin product page interface

13 Weixin card

13.1 Get api_ticket

13.2 Choose applicable cards and get user selection information

13.3 Add cards in bulk interface

13.4 View the cards in the Weixin card package interface

14 WeChat Pay

14.1 Set up a WeChat pay request

15 Quick input

15.1 Share Weixin shipping address

16 Appendix 1-JS-SDK signature usage permission algorithm

17 Appendix 2-All JS interface list

18 Appendix 3-All menu list

19 Appendix 4-Card extension fields and signature generation algorithms

20 Appendix 5-Common errors and solutions

21 Appendix 6-DEMO page and sample codes

22 Appendix 7-Feedback

# Overview

Weixin JS-SDK isWeixin public platformWeixin in-app based web development tool kits for web developers.

Through using Weixin JS-SDK, web developers can effectively use the capabilities of mobile phone systems to take pictures, select pictures, voices and locations. Also to use Weixin's unique capabilities such as Weixin sharing, scanning, card, payment to provide Weixin users better quality Web experience.

This document introduce Weixin JS-SDK to web developer, how to use and related matters.

# JSSDK Steps

# Step 1: Bind domain name

Log-in Weixin public platform, enter “Official account setting” under “Function setting” input “JS interface secured domain name”

Note: Once logged in, Check the corresponding interface permissions at developer center

# Step 2: Import JS file

In need to use JS interface page, import JS file as below (support https): http://res.wx.qq.com/open/js/jweixin-1.2.0.js

Note: Support AMD/CMD standard module loading method to load

# Step 3: Verify the configuration via the config interface

All pages need to use JS-SDK must first import configuration information, otherwise it cannot call (each url only need to be called once, variable url SPA of Web app, can be called when the url changes. Currently Android Weixin users is not supported by the new features of H5 of pushState. Therefore, using puchState to run web app page will cause signature failure, this issue will be fixed in Android 6.2).

wx.config({

	debug: true, // turn on debug mode, call all return value of api, which will be in alert in client's end. To view the incoming parameters, this cane be opened on a pc, the parameter information will be displayed through a log, only to be printed on a pc.
	appId: '', // Required, the only identification of Official account.
	timestamp: , // Required, generate a signed timestamp
	'nonceStr: '', // Required, generate a signed nonceStr
	signature: '',// Required, signature. See Appendix 1
	jsApiList: [] // Required, required JA interface list, all JS interface list, see Appendix 2
	
});

# Step 4: Successful verification via the ready interface

wx.ready(function(){

	// config information validation will execute by the ready method, all interface call must be done after config interface get the result. Config is an asynchronous operation of client's side. If call relevant interface is required when loading a page, the relevant interface must be called on the ready function to ensure correct execution. For those interface call when triggered by users, it can be called directly, not required to be in the ready function.
	
});

# Step 5: Failure verification via the error interface

wx.error(function(res){

	// config information failure will execute error function, such as expired signature to cause verification failure, the error message can be viewed via debug mode in config, also be viewed via returned res parameter. SPA can renew signature here.

});

# Interface call descriptions

All interfaces are called via wx objects (you can also use jWeixin objects). Parameter is an object, in addition to each interface itself needs to pass the parameters, there are the following general parameters:

1. success:Callback function executed when the interface call succeeds

2. fail:Callback function executed when the interface call fails

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

4. cancel: User click cancel callback function, only some users cancel the operation of the API will be used.

5. trigger: Monitor the method in the Menu button when clicked and triggered. This method only supports the relevant interface in Menu.

Note:Do not try to trigger the use of ajax asynchronous request to modify the content of this sharing, because the client sharing operation is a synchronous operation, at this time using the ajax package will not return.

Several functions above have a parameter,type is an object, in addition to the data returned by each interface itself, there is a common attribute errMsg, the value of the format is as follows:

When call succeeded "xxx:ok", the xxx is the interface name of call

When user cancelled:"xxx:cancel", the xxx is interface name of call.

When call failed: the value is a specific error message

# Base interfaces

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

wx.checkJsApi({

	jsApiList: ['chooseImage'], // Need to test JS interface list, all JS interface list, please see appendix 2.

	success: function(res) {

	// Returned as a key-value pair, the available api values are true and not available as false

	// If: {"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}

	}

});

Note: The checkJsApi interface is a reserved interface newly introduced by the client 6.0.2. The first open interface can be checked without using the checkJsApi.

# Share interface

Please note, do not induced sharing and other violations. Inductive sharing behavior will be result in permanent Official account interface permissions withdraw. For detailed rules, please see:FAQ of Moments management.

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

wx.onMenuShareTimeline({

	title: '', // Share title
	link: '', // Share link, this link domain name and path must be the same as the current page which corresponding to JS secured domain name as Official account
	imgUrl: “,// Share icons.
	success: function () {
		// The user confirms the callback function that was executed after sharing
	},
	cancel: function () {
		// The user cancels the callback function that was executed after sharing
	}
});

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

wx.onMenuShareAppMessage({
	title: '', // Share title
	desc: '', // Share description
	link: '', // Share Link,this link domain name and path must be the same as the current page which corresponding to JS secured domain name as Official account
	imgUrl: '', // Share Icon
	type: '', // Share type, music, video link, not filled default link
	dataUrl: '', // If type is music or video, provide data links, the default is empty
	success: function () {
		// The user confirms the callback function that was executed after sharing
	},
	cancel: function () {
		// The user cancels the callback function that was executed after sharing
	}
});

# Get “Share to QQ” button click status and customize the sharing content interface

wx.onMenuShareQQ({

	title: '', // Share title
	desc: '', // Share description
	link: '', // Share link
	imgUrl: “, // Share icons.
	success: function () {
		// The user confirms the callback function that was executed after sharing
	},
	cancel: function
		// The user cancels the callback function that was executed after sharing
	}
});

# Get “Share to Weibo ” button click status and customize the sharing content interface

wx.onMenuShareWeibo({

	title: '', // Share title
	desc: '', // Share description
	link: '', // Share link
	imgUrl: “, // Share icons.
	success: function () {
		// The user confirms the callback function that was executed after sharing
	},
	cancel: function () {
		// The user cancels the callback function that was executed after sharing
	}
});

# Get “Share to QZone” button click status and customize the sharing content interface

wx.onMenuShareQZone({
	title: '', // Share title
	desc: '', // Share description
	link: '', // Share link
	imgUrl: “, // Share icons
	success: function () {
		// The user confirm the callback function that was executed after sharing
	},
	cancel: function
		// The user cancels the callback function that was executed after sharing
	}
});

# Image interface

# Take a picture or choose a picture from phone album interface

wx.chooseImage({
	count: 1, // Default 9
	sizeType: ['original'], ['compressed'], // Can specify whether it is the original or compressed image, default includes both
	sourceType: ['album'], ['camera'], // Can specify whether the source is an album or camera, default includes both
	success: function (res) {
		var localIds = res.localIds; // Returns to local ID list for the selected photo, localId can be used as the src attribute of img tag to display the image
	}
});

# Preview image interface

wx.previewImage({
	current: '', // http link for currently displayed image
	urls: [] // List of http links for images that need to be previewed
});

# Upload images interface

wx.uploadImage({
	localId: '', // Local ID for images required to be uploaded, achieved via chooseImage interface
	isShowProgressTips: 1, // default is 1, Show progress prompt
	success: function (res) {
		var serverId = res.serverId; // Returns to image server ID
	}
});

Note: Uploaded images is valid for 3 days, use the Weixin multimedia interface to download images to user's own server, where serverId is media_id.

# Download image interface

wx.downloadImage({
	serverId: '', // Server ID of images required to be downloaded, achieved via uploadImage interface
	isShowProgressTips: 1, // default is 1, Show progress prompt
	success: function (res) {
		var localId = res.localId; // Returns to local ID after downloading images
	}
});

# Get local image interface

wx.getLocalImgData({
	localId: '', // localID of image
	success: function (res) {
		var localData = res.localData; // localData is the base64 data of images, can be display with img tags
	}
});

Note: thisinterface only provided in iOS WKWebview,compatible with iOS WKWebview not supporting localId with direct display images issues. Specific reference 《<a href="http://mp.weixin.qq.com/advanced/wiki?t=t=resource/res_main&id=mp1483682025_enmey "iOS web development and adaptation guide"" target="_blank">iOS web development and adaptation guide》

# Audio interface

# Starts recording interface

wx.startRecord();

# Stops recording interface

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

# Monitor recording automatically stop interface

wx.onVoiceRecordEnd({
	// Recording time is longer than one minute without stopping, complete callback will be executed.
	complete: function (res) {
		var localId = res.localId;
	}
});

# Play voice message interface

wx.playVoice({
	localId: '' // local ID for voice message required to be played, achieved via stopRecord interface
});

# Pause

wx.pauseVoice({
	localId: '' // local ID for voice message required to be paused, achieved via stopRecord interface
});

# Stop voice message interface

wx.stopVoice({
	localId: '' // local ID for voice message required to be stopped, achieved via stopRecord interface
});

# Monitor voice message end interface

wx.onVoicePlayEnd({
	success: function (res) {
		var localId = res.localId; // Returns to voice local ID
	}
});

# Upload voice message interface

wx.uploadVoice({
	localId: “,// local ID for voice message required to be uploaded, achieved via stopRecord interface
	isShowProgressTips: 1, // default is 1, Show progress prompt
		success: function (res) {
		var serverId = res.serverId; // Returns to voice server ID
	}
});

Note: Uploaded images is valid for 3 days, use the Weixin multimedia interface to download voice message to user's own server, where serverId is media_id. Refer to documentation, currently multimedia file download interface frequency limit is 10000 times a day. If frequency need to increased, please log in Weixin Official account, in the “Development - Interface permissions list”, apply for increasing temporary capping。

# Download voice message interface

wx.downloadVoice({
	serverId: '', // Server ID for voice message required to be downloaded, achieved via stopRecord interface
	isShowProgressTips: 1, // default is 1, Show progress prompt
	success: function (res) {
		var localId = res.localId; // Returns to voice local ID
	}
});

# Smart interface

# Identify voice and return to identify result interface

wx.translateVoice({
	localId: '', // Local Id for voice need to be identified, achieved via relevant recording interface
	isShowProgressTips: 1, // default is 1, Show progress prompt
	success: function (res) {
		alert(res.translateResult); // Voice identify result
	}
});

# Device information

# Get Network status interface

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

# Location

##​Use Weixin built-in map to view location interface

wx.openLocation({
	latitude: 0, // Latitude, floating point, range is 90 ~ -90
	longitude: 0, // longitude, floating point, range is 180 ~ -180.
	name: '', // Location name
	address: '', // Address detail description
	scale: 1, // Map scale, alter value, range is 1~28. Default is maximum
	infoUrl: '' // Click on the hyperlink that appears at the bottom of the View Location screen
});
```
<span id = "38"></span>

## Get location interface

```
wx.getLocation({
	type: 'wgs84', // wgs84 is the default gps coordinates. If wish to return, import 'gcj02' directly as the Mars coordinates used for openLocation.
	success: function (res) {
		var latitude = res.latitude; // latitude, floating point, range is 90 ~ -90
		var longitude = res.longitude; // longitude, floating point, range is 180 ~ -180.
		var speed = res.speed; // speed, calculated in meter per second
		var accuracy = res.accuracy; // location accuracy
	}
});
```
<span id = "39"></span>

# Shake Nearby


<span id = "40"></span>

## Turn on search nearby ibeacon device interface

```
wx.startSearchBeacons({
	ticket:"",   //shake to search nearby business ticket, system automatically adds the page link.
	complete:function(argv){
		//Turn on search complete callback function
	}
});
```

Note: If require to add Shake nearby feature, please refer to: Apply for Shake nearby


<span id = "41"></span>

## Turn off search nearby ibeacon device interface

```
wx.stopSearchBeacons({
	complete:function(res){
		//Turn off search complete callback function
	}
});
```
<span id = "42"></span>

## Monitor nearby ibeacon device interface

```
wx.onSearchBeacons({
	complete:function(argv){
		//Callback function can be used in several groups, to obtain a list of related device within the business registered perimeter
	}
});
```

Note: above mentioned precautions for use and more return to result instruction. Please refer to: Shake nearby for device information.


<span id = "43"></span>

# Interface operation


<span id = "44"></span>

## Close current web window interface

```
wx.closeWindow();
```
<span id = "45"></span>

## Bulk hide function button interface

```
wx.hideMenuItems({
	menuList: [] // To hide menu items, only hide "Communication" and "protection" buttons. See appendix 3 for all the menu items
});
```
<span id = "46"></span>

## Bulk show function button interface

```
wx.showMenuItems({
	menuList: [] // To show menu items, See appendix 3 for all the menu items.
});
```
<span id = "47"></span>

## Hide all Non-base button interface

```
wx.hideAllNonBaseMenuItem();
// See appendix 3 for “Base” button details
```
<span id = "48"></span>

## Show all function button interface

```
wx.showAllNonBaseMenuItem();
```
<span id = "49"></span>

# Weixin Scan QR code


<span id = "50"></span>

## Turn on Weixin Scan QR code

```
wx.scanQRCode({
	needResult: 0, // Default is 0, scan result is processed by Weixin, 1 is to directly return to scan result,
	scanType: ["qrCode","barCode"], // Can specify to scan QR code or Bar code, default includes both
	success: function (res) {
		var result = res.resultStr; // when needResult is 1,Return result of the scan
	}
});
```
<span id = "51"></span>

# Weixin Shop


<span id = "52"></span>

## Go to Weixin product page interface

```
wx.openProductSpecificView({
	productId: '', // Product id
	viewType: '' // 0. default, general product listing page 1. Scan product listing page 2. Shop Item listing page
});
```
<span id = "53"></span>

# Weixin card



The signature certificate, api_ticket, used in Weixin Card interface is not the same as the signature certificate, jsapi_ticket, that was used by the config in step 3. During the process of calling Weixin card JS-SDK, developers are require to complete two different signatures and to ensure the certificate cache.


<span id = "54"></span>

##  Get api_ticket



api_ticket is used to call Weixin card temporary ticket of JS API, valid for 7200 seconds, obtained through access_token.



Developers need to know:



1.This is used for singature api_ticket of card interface with step three Import authentication configuration via config interface  different jsapi_ticket used.



2.Due to the very limited number of api calls of api_ticket, frequently refreshing api_ticket can result in api calls being limited and affecting the business. Developers need to store and update api_tickets in their own services.



**Interface call request descriptions**

```
http request methods: GET

https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=wx_card
```

**Parameter descriptions**



| **Parameters** | **Is it necessary** | **Description:** |
|---|---|---|
| Get access_token | Yes | Interface calls certificate |



**Return data**



**Data sample**

```
{
"errcode":0,
"errmsg":"ok",
"ticket":"bxLdikRXVbTPdHSM05e5u5sUoXNKdvsdshFKA",
"expires_in":7200
}
```





| **Parameters name** | **Describe** |
|---|---|
| errcode | Error code |
| errmsg | Error message |
| ticket | api_ticket, Certificate required for signature in Card interface |
| expires_in | Expiry time |


<span id = "55"></span>

## Choose applicable card and get user selection information

```
wx.chooseCard({
	shopId: '', // Shop Id
	cardType: '', // Card type
	cardId: '', // Card Id
	timestamp: 0, // Card signature time stamp
	'nonceStr': '', '', // Card singature nonceStr
	signType: '', // signature type, default as 'SHA1'
	cardSign: '', // Card signature
		success: function (res) {
		var cardList= res.cardList; // Card list information selected by the user
	}
});
```





| **Parameters** | **Required** | **Types** | **Example:** | **Describe** |
|---|---|---|---|---|
| shopId | No | string(24) | 1234 | Shop ID shopID is used to filter out a list of cards with the specified location_list (shopID), not required. |
| cardType | No | string(24) | GROUPON | Card type, used to pull up the list of card types for the specified card type. When cardType is empty, by default to pull up all card list, not required. |
| cardId: | No | string(32) | p1Pj9jr90_SQRaVqYI239Ka1erk | Card ID, used to pull up specified card list of cardId, when cardId is empty, by default to pull up all card list, not required. |
| timestamp | Yes | string(32) | 14300000000 | Time stamp. |
| 'nonceStr': '', | Yes | string(32) | sduhi123 | Random string. |
| signType | Yes | string(32) | SHA1 | Signature type, currently support SHA1 |
| cardSign | YEs | string(64) | abcsdijcous123 | Signature |



CardSign detail, see [appendix 4](#65).



Special Note for Developers: If the signature is incorrect, the card list will be empty. Please check the validity of parameters of involved signature carefully.



**Special attention**



List is only relevant to user's local coupons. There are three situations causing empty list: signature error, invalid time stamp, wrong random selection Developers to organize reasons for positioning.


<span id = "56"></span>

## Bulk adds cards interface

```
wx.addCard({
	cardList: [{
		cardId: '',
		cardExt: ''
}], // Card list required to be added
	success: function (res) {
		var cardList = res.cardList; // Adds card list information
	}
});
```

CardExt see [appendix 4](#65), If developers call the interface that reported with wrong signature, has been finished or other unusual issues, refer to:<a href="http://mp.weixin.qq.com/s/WhYpWmfuhUBw2wseTXdt2A" target="_blank">card signature error troubleshooting</a>






<span id = "57"></span>

## View the cards interface in the Weixin card package

```
wx.openCard({
	cardList: [{
		cardId: '',
		code: ''
	}]// Card list required to be opened
});
```
<span id = "58"></span>

# WeChat Pay


<span id = "59"></span>

## Initiate a WeChat Pay request

```
wx.chooseWXPay({
	timestamp: 0, // pay signature time stamp, please note, timestamp used in Weixin jssdk are all written in lower case. But the latest version of pay platform, timeStamp used in generating signature, capital S is required.
	'nonceStr': '', // Random string of pay signature is no longer than 32 bits
	'package: “, // prepay_id parameter values returned by unified pay interface, submitted format such as: prepay_id=\*\*\*)
	signType: '', // signature type, default as 'SHA1', need to import 'MD5' to use new version of pay
	paySign: '', // pay signature
	success: function (res) {
		// Callback Function After Successful Payment
	}
});
```

Note: prepay_id is obtained by unified WeChat pay order interface. paySign use unified WeChat pay Sign signature generating method. Note, appId also involved in the signature here, appId and config imported the same appId, the final parameters involved in the signature are appId, timeStamp, nonceStr, package, signType.



Weixin pat development documentation: <a href="https://pay.weixin.qq.com/wiki/doc/api/index.html" target="_blank">https://pay.weixin.qq.com/wiki/doc/api/index.html</a>



<span id = "60"></span>

# Quick input


<span id = "61"></span>

## Share shipping address interface

```
wx.openAddress({
	success: function (res) {
	var userName = res.userName; // Receiver name
	var postalCode = res.postalCode; // Post code
	var provinceName = res.provinceName; // National standard shipping address, first level of adress (County)
	var cityName = res.cityName; // National standard shipping address, second level of address (City)
	var countryName = res.countryName; // National standard shipping address, third level of address (Country)
	var detailInfo = res.detailInfo; // Shipping address detailed information
	var nationalCode = res.nationalCode; // Shipping address Country code
	var telNumber = res.telNumber;  // Receiver telephone number
	}
});
```

Note:



Weixin address shared data field are: 
- Receiver name 
- Region, county, city and area 
- Detailed address
- Post code
- contact telephone number 

Region are corresponded to the national standard three level area code, example “Guangdong province-Guangzhou City-Tianhe area”, correspond post code is 510630. Refer to link for details: http://www.stats.gov.cn/tjsj/tjbz/xzqhdm/201401/t20140116_501070.html






<span id = "62"></span>

# Appendix 1 - JS-SDK Usage Rights signature Algorithm



**jsapi_ticket**



Before generating signature, must understand jsapi_ticket. jsapi_ticket is a temporary ticket for Official account to call Weixin. Under normal circumstances, jsapi_ticket is vaild for 7200 seconds,obtained via access_token. Due to the very limited number of api calls of jsapi_ticket, frequently refreshing jsapi_ticket can result in api calls being limited and affecting the business.  Developers must cache jsapi_ticket globally within their service.



1\. Refer to the following documents to obtain access_token( vaild for 7200 seconds,developers must cache access_token within their service): ../15/54ce45d8d30b6bf6758f68d2e95bc627.html



2\. Use the access_token obtained in Steps 1, use http GET method to obtain jsapi_ticket(valid for 7200 seconds, developers must cache jsapi_ticket globally within their service ): https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi



Success return as below JSON:

```
{
"errcode":0,
"errmsg":"ok",
"ticket":"bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA",
"expires_in":7200
}
```

After obtaining jsapi_ticket, then generate JS-SDK signature verification.



**Signature algorithm**



The rules of generate signature is as follow: the fields of involved signature included noncestr(random string), valid jsapi_ticket, timestamp(time stamp), url (current web page URL,  not including # and the remaining ). After all the parameters are signed, sort ASCII code according to the field name from small to large (dictionary order). Use the format of URL key-value pairs (key1 = value1&key2=value2 ...) connect into string1. It should be noted here that all parameter names are lowercase characters. String1 as sha1 encryption, field names and field values are the original value, without URL transfer.



Therefore, signature=sha1(string1). Example:

```
noncestr=Wm3WZYTPz0wzccnW
jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg
timestamp=1414587457
url=http://mp.weixin.qq.com?params=value
```

Step 1. After all the parameters are signed, sort ASCII code according to the field name from small to large (dictionary order). Use the format of URL key-value pairs (key1=value1&key2=value2 ...) connect into string1.

```
jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg&noncestr=Wm3WZYTPz0wzccnW&timestamp=1414587457&url=http://mp.weixin.qq.com?params=value
```

Step 2. Use string1 to sign sha1, to obtain signature:

```
0f9de62fce790f9a083d5c99e95740ceb90c27ed
```

Note the following points:



1. The noncestr and timestamp used for signature must be the same as nonceStr and timestamp in wx.config.



2. The urlused for signature must be the complete page URL to call JS interface



3. For security reasons, developers must implement the logic of signature on the server.



If invalid signature or other errors occurred, see appendix 5 for Common errors and solutions


<span id = "63"></span>

# Appendix 2-all JS interface list



**Version 1.0.0 interface**



onMenuShareTimeline



onMenuShareAppMessage



onMenuShareQQ



onMenuShareWeibo



onMenuShareQZone



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



openProductSpecificView



addCard



chooseCard



openCard


<span id = "64"></span>

# Appendix 3-all menu item list



**Base type**



Expose: "menuItem:exposeArticle"



Set font: "menuItem:setFont"



Day Mode: "menuItem:dayMode"



Night Mode: "menuItem:nightMode"



Refresh: "menuItem:refresh"



View Official account (added): "menuItem:profile"



View Official account (not added): "menuItem:addContact"



**Communication**



Send to friends: "menuItem:share:appMessage"



Share to moments: "menuItem:share:timeline"



Share to QQ "menuItem:share:qq"



Share to Weibo: "menuItem:share:weiboApp"



Favorite: "menuItem:favorite"



Share to FB: "menuItem:share:facebook"



Share to QZone/menuItem:share:QZone



**Protected:**



Edit tags: "menuItem:editTag"



Delete: "menuItem:delete"



Copy URL: "menuItem:copyUrl"



Original Page "menuItem:originPage"



Reading Mode: "menuItem:readMode"



Open with QQ Browser: "menuItem:openWithQQBrowser"



Open with Safari: "menuItem:openWithSafari"



Email: "menuItem:share:email"



Some special official account: "menuItem:share:brand"


<span id = "65"></span>

# Appendix 4-Card extension fields and signature generation algorithms



**JSSDK users please read here, JSAPI users can skip**



Card signature and JSSDK signature are completely independent. The algorithm and meaning of the two completely different, please do not be confused. The JSSDK signature is using a layer of authentication that all JS interfaces need to go through, to identify the caller's identity and has nothing to do with the card itself. Secondly, the signature of the card is designed with a set of independent signature protocols, taking into account the expansibility of the protocol and simple anti-data tampering. Furthermore, due to historical reasons, JS interface of cards first appeared in JSSDK. At that time, there was no authentication system in JSAPI, so appsecret/api_ticket was also added to the card signature. Hopefully the developer would understood that.



**Card api_ticket**



Card api_ticket is used to call temporary ticket of relevant card interface, valid for 7200 seconds. Obtained via access_token. Please note, to separate from jsapi_ticket here. Due to the very limited number of api calls of api_ticket to obtain card, frequently refreshing api_ticket of new cards can result in api calls being limited and affecting the business.  Developers must cache card api_ticket globally within their service.



1. Refer to below document to obtain access_token ( valid for 7200 seconds, developers must cache access_token globally within their service ): ../15/54ce45d8d30b6bf6758f68d2e95bc627.html



2. Use Step 1 to obtain access_token, using http GET method to obtain api_ticket of card( valid for 7200 seconds, developers must cache card api_ticket globally within their service ):<a href="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&amp;type=wx_card" target="_blank">https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=wx_card</a>







**cardExt description of Card extension field**



CardExt is a JSON string that merchant assigned unique information to the card. It contains the following fields:



| **Field** | **Is it required** | Is it involve signature | **Description** |
|---|---|---|---|
| code | No | Yes | Specific card code, only to be used once. Custom code mode card must be filled in. Non-custom code and pre-stored code mode do not need to be filled in. For further detail, see:[创建卡券](/doc/offiaccount/en/Cards_and_Offer/Create_a_Coupon_Voucher_or_Card)|
| openid | No | Yes | Designated recipient's openid, only the user can collect. bind_openid field is true, card need to be filled in. bind_openid field is false, does not need to be filled |
| timestamp | Yes | Yes | Time stamp, the number of seconds the merchant has generated since 00:00:00 January 1, 1970 to now, therefore the current time, eventually need to be converted to a string form. Imported by the merchant after generated, different time stamp requests to be dynamically generated, any repeat will result in fail collection! |
| nonce_str | No | Yes | Random string imported by the developer's setting, **Enhanced security (if not filled in, may be asked to re-request)**. Random string, not longer than 32 bits. To use recommended uppercase, lowercase letters and numbers. different nonce requests added must be dynamically generated. Any repeated will result in fail collection |
| fixed_begintimestamp | No | No | The actual collection time of card in the third-party system, is East time zone 8 (UTC +8, accurate to seconds). When the card valid time type is DATE_TYPE_FIX_TERM, The actual effective time of the identified card is used to solve the problem of starting time and receiving time are out of synchronization in the merchant system.  |
| outer_str | No | No | Received channel parameters is used to identify the channel value received this time. |
| signature | Yes | - | Signature, the merchant will sign the parameters in the interface list according to the specified mode. The signature mode uses SHA1. For details of the signature plan, see below. The merchant imports the standard signature |



**Signature description**



1\. Sort the value of api_ticket、timestamp、card_id、code、openid、nonce_str in dictionary order.



2\. Join all the parameter strings into one string for sha1 encryption, to obtain signature.



3\. the timestamp of signature,nonce field and timestamp of card_ext, the nonce_str field must remain the same.



4\. code=1434008071,timestamp=1404896688,card_id=pjZ8Yt1XGILfi-FUsewpnnolGgZk, api_ticket=ojZ8YtyVyr30HheH3CM73y7h4jJE ,nonce_str=123 则signature=sha1(12314048966881434008071ojZ8YtyVyr30HheH3CM73y7h4jJEpjZ8Yt1XGILfi-FUsewpnnolGgZk)=f137ab68b7f8112d20ee528ab6074564e2796250。



**It is highly recommended that developers use the signature tool SDK in the card information package, to sign or use the debug tool to verify:**<a href="http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=cardsign" target="_blank">http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=cardsign</a>






**Card signature cardSign description**



1. Sort the value of  api_ticket、appid、location_id、timestamp、nonce_str、card_id、card_type in dictionary order



2. Join all the parameter strings into one string for sha1 encryption, to obtain cardSign.






<span id = "66"></span>

# Appendix 5-Common errors and solutions



Import parameter degug when calling config interface: True is to open debug mode,page will alert error messages Below are common errors and solutions:



1.invalid url domain, when the domain of the current page is not bind with the used appid. Confirm that the bind domain name is correctly entered, only support two ports, 80 (http) and 443 (https), therefore, port number do not need to filled in (one appid can be bind to three Valid domain name, see  [index 1.1.1](#2) ).



2.invalid signature It is recommended to check in the following order:



1. Confirm the signature algorithm is correct and available<a href="http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=jsapisign" target="_blank">http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=jsapisign</a>Use page tool to verify



2. Confirm the nonceStre in config (In js, use standard uppercase S). Timestamp and the correspond noncestr of signature timestamp to be the same.



3. Confirm url is the complete page url (Please within current page alert(location.href.split('#')[0])confirm),including 'http(s)://'part,and'?' The latter part of the GET parameters, but does not include the part beyond '#' hash.



4. Confirm appid in config, is the same as appid used to obtain jsapi_ticket.



5. make sure to cache access_token and jsapi_ticket



6. make sure url obtained for signature was dynamically obtained. Dynamic page can be found in php of the example code. If it is html static page in the front went through, ajax url passed to the background for signature, The front end needs to used js to obtain current page, to remove '#' hash section of the link (can use location.href.split ('#') \ , and encodeURIComponent). Once the page is shared, Weixin client will add other parameters at the end of your link. If it is not dynamically obtained the current link, it will result in page signature failure after shared.



3.the permission value is offline verifying, this is an error because config did not execute correctly, or JSAPI did not import config jsApiList parameters. It is recommended to check in the following order:



1. Confirm the config passed through correctly.



2. If the JSAPI is called when the page is loaded, it must be written in the wx.ready callback.



3. Confirm config jsApiList parameter contains this JSAPI



4.permission denied, this official account does not have permission to use this JSAPI, or calling JSAPI is not passed to the config's jsApiList parameter (some interfaces need to be authenticated before they can be used).



5.function not exist, current user version does not support this interface, please upgrade to the latest version.



6.Why 6.0.1 version config:ok, but 6.0.2 version or later is not ok. (because prior to 6.0.2 version, there was no permission verification. Therefore, config were ok, but this does not mean that the signature of your config would be ok. Please check if 6.0.2 version generate the correct signature to ensure that config is also ok in later versions. )



7.When iOS and Android cannot share (please confirm official account had been verified, only verified official account can have permission to share relevant interface. If verification has been confirmed, then check if monitor interface is triggered in wx.ready callback function)



8.Service can not get jsapi_ticket after getting online. No problem when self assessed (Because access_token and jsapi_ticket must be cached in their own server, otherwise trigger the frequency limit after going online. Make sure to cache token and ticket, to reduce server requests twice, not only to avoid triggering frequency limits but also to speed up your own service speed. Currently, to facilitate testing, 1w acquisition is provided. The service will no longer be available, once beyond the threshold,  Make sure that the service is online before the global cache access_token and jsapi_ticket, both valid for 7200 seconds. Or once online, it triggers frequency limit and service will no longer be available ).



9.uploadImage, how to upload many images (currently only support uploading one image at a time. Uploading multiple images must wait for the previous image uploaded before calling this interface again)



10.Can not preview locally selected images (chooseImage interface supports preview, no additional support required)



11.Through link a (for example, though Weixin authorized login) to go to link b, invalid signature (platform generated signature link to use the current jssdk link, which is also to go to link b. Please do not use Weixin login authorization link for signature calculation. Platform signature url must be the complete url of current page of jssdk, removing '#' section)



12.When config:fail error appears (due to incomplete config parameters imported. Please make sure to import the correct appId, timestamp, nonceStr, signature, and required jsApiList)



13.How to download jsapi of Weixin multimedia resources to your own server (see documentation of uploadVoice and uploadImage interface notes)



14.Android uploaded to the Weixin server through jssdk. Third party then downloaded from Weixin to their own server, and noise appeared (Weixin team has fixed this problem, which had been optimized)



15.Bind to prime domain name, is it possible to use sub-prime domain name (yes, the sub-prime domain name is fully supported after the prime domain name is bind)



16.In iOS Weixin 6.1 version, shared image external link did not show, only to display the image internal link of official account of Weixin server images. This has been fixed in 6.2



17.Does it need to be compatible with the lower version (jssdk are compatible with the low version, do not need to additional work from third parties, but some interfaces are introduced in 6.0.2, only the new version can be called)



18.This official account payment signature is invalid, cannot initiate the transaction (please make sure that you use jweixin.js is the official online version. This will not only reduce user traffic, but also repair bug. When copied to a third-party server, the official will not provide any protection for any problems that arise. For details of the signature algorithm, refer to  [JSSDK WeChat Payments Column (page 2)](#58)



19.Currently Android Weixin users do not support pushState H5 new features. Therefore to use pushState to achieve web app page may cause invalid signature. This problem had be fixed in Android 6.2.



20.Sometimes Android will not execute uploadImage In the chooseImage callback. Android 6.2 will solve this problem, if need to support low version, call uploadImage in setTimeout delayed 100ms.



21.require subscribe, the error indicates that you did not subscribe to this test account. The error only shows test account



22.getLocation returns coordinates in openLocation deviation, because getLocation returns gps coordinates, openLocation open Tencent map that are Mars coordinates. Need third-party to do the conversion themselves. The 6.2 version has begun to support and direct access to Mars coordinates



23.View official account (not added): "menuItem:addContact" not displayed. Currently, only the links that are publicized from official account can be displayed, and the source must be a official account



24.ICP record data synchronization delay by one day, please bind on the second day


<span id = "67"></span>

# Appendix 6-DEMO page and sample code



**DEMO page:**




<a href="http://203.195.235.76/jssdk/" target="_blank">http://demo.open.weixin.qq.com/jssdk</a>



<img src="https://mmbiz.qpic.cn/mmbiz/PiajxSqBRaEIQxibpLbyuSK39dMUJfWKTT3w5O5mich0nbKnpPnpl0QzuWuncBtibiaZQlmH1MGf3HoicWNIeaV4dXUg/0?wx_fmt=png" alt="" data-width="250" data-ratio="0.992">



**Sample code:**



<a href="http://demo.open.weixin.qq.com/jssdk/sample.zip" target="_blank">http://demo.open.weixin.qq.com/jssdk/sample.zip</a>



Note: link includedphp、java、nodejs and python sample code to provide for third party reference. Third partymust remember to obtain accesstoken and jsapi_ticket cache  to ensure that the frequency limit will not be triggered.


<span id = "68"></span>

# Appendix 7-Feedback

[Weixin  JS-SDK Feedback](https://developers.weixin.qq.com/community/minihome/question/1277775808983138305)

Describe the problem in a concise language and explain clearly the situation when problems are encountered and attach a screenshot. Weixin team will handle your feedback as soon as possible.