# JS-SDK Instructions for Use

# Summary

WeChat JS-SDK is WeChat Official Platform for web developers based on WeChat web development kit.

By using WeChat JS-SDK, web developers can use WeChat to efficiently use photos,The ability to select maps, voice, location and other mobile phone systems can also be directly used by WeChat to share, scan, coupons, payment and other WeChat-specific capabilities to provide WeChat users with a better quality web experience.

This document for web developers describes how to use WeChat JS-SDK and related notes.

# JSSDK Steps to Use

# Step 1: Binding the domain name

You can log in to the public platform to enter the "Service Account" "Function Settings" and fill in the "JS interface security domain name."Or go to WeChat developer platform - service number or service number - basic information - development information to modify

  • Binding a parent domain name so that its legitimate subdomains are available
  • Up to 5 legitimate domains can be filled in,
  • However, it does not support IP address, slogan and short chain domain name, in addition, the domain name needs to be verified by ICP registration, and the new domain name needs to be configured 24 hours later.

Note: The corresponding interface permissions can be viewed in the Developer Center after logging in.

# Step 2: Introduce JS files

Introduce the following JS file on the page that needs to call the JS interface (https supported): http://res.wx.qq.com/open/js/jweixin-1.6.0.js

To further improve service stability, when the above resources are not accessible, you can change access: http://res2.wx.qq.com/open/js/jweixin-1.6.0.js (https is supported).

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

# Step 3: Inject the permission validation configuration through the config interface

All pages that need to use the JS-SDK must be injected with configuration information before they cannot be called (the same URL needs to be called only once, and the web app of a SPA that changes the URL can call it each time the URL changes,Currently the Android WeChat client does not support the new H5 feature of pushState, so using pushState to implement a web app's page causes the signature to fail, a problem that will be fixed in Android 6.2.

wx.config({
  debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
  appId: '', // 必填,服务号的唯一标识
  timestamp: , // 必填,生成签名的时间戳
  nonceStr: '', // 必填,生成签名的随机串
  signature: '',// 必填,签名
  jsApiList: [] // 必填,需要使用的JS接口列表
});

The signature algorithm is in Appendix 1 at the end of this article, and the list of all JS interfaces is in Appendix 2 at the end of this article

Note: If you are using Weixin Mini Program cloud development static web hosting The web page of the domain name can skip any legal compliance Mini Program without rights, and when calling wx.config, appId needs to be filled in a certified Mini Program that is not a personal subject, and no signature needs to calculate, timestamp, nonceStr, and signature can be filled with any non-empty value.

# Step 4: Process successful validation through the ready interface

wx.ready(function(){
  // config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。
});

# Step 5: Handle failed validation through the error interface

wx.error(function(res){
  // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。
});

# Instructions for Interface Calls

All interfaces are called via a wx object (or jWeixin object). The parameters are an object. In addition to the parameters that each interface itself needs to pass, there are the following general parameters:

  1. Success: The callback function that is executed when the interface calls successfully.
  2. Fail: The interface invokes a callback function that executes when it fails.
  3. Complete: The interface invokes a callback function that executes at completion, whether it succeeds or fails.
  4. Cancel: The callback function when the user clicks cancel, only used in some APIs that have the user cancel action.
  5. Trigger: A method that listens to trigger when a button is clicked in a Menu and supports only the relevant interface in a Menu.

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

Each of the above functions takes a parameter, of type object, where in addition to the data returned by each interface itself, there is a generic attribute errMsg, whose value is formatted as follows:

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

When the user cancels: "xxx: cancel," where xxx is the interface name of the call

When the call fails: its value is specific error message

# Basic Interfaces

# Determine whether the current version of the home supports the specified JS

wx.checkJsApi({
  jsApiList: ['chooseImage'], // 需要检测的JS接口列表,所有JS接口列表见附录2,
  success: function(res) {
  // 以键值对的形式返回,可用的api值true,不可用为false
  // 如:{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
  }
});

Note: checkJsApi interface is a new guest terminal 6.0.2 introduced a reserved interface, the first phase of the open interface can not use checkJsApi to detect.

# Share Interface

Please note that there should be no violations such as inducing sharing, as the Service Account interface permissions will be permanently revoked in such cases. For detailed rules, please refer to: Frequently Asked Questions about WeChat Moments Management

Please note that the originalwx.onMenuShareTimelinewx.onMenuShareAppMessagewx.onMenuShareQQwx.onMenuShareQZoneThe interface is about to be abandoned.Please migrate as soon as possible to use the Guest 6.7.2 and JSSDK 1.4.0 above supportedwx.updateAppMessageShareDatawx.updateTimelineShareDatainterface interface.

# Customize the sharing content of the "Share to Friends" and "Share to QQ" buttons (1.4.0)

wx.ready(function () {   //需在用户可能点击分享按钮前就先调用
  wx.updateAppMessageShareData({ 
    title: '', // 分享标题
    desc: '', // 分享描述
    link: '', // 分享链接,该链接域名或路径必须与当前页面对应的服务号JS安全域名一致
    imgUrl: '', // 分享图标
    success: function () {
      // 设置成功
    }
  })
}); 

# Customize the sharing content for the "Share to WeChat Moments" and "Share to QQ Space" buttons (1.4.0)

wx.ready(function () {      //需在用户可能点击分享按钮前就先调用
  wx.updateTimelineShareData({ 
    title: '', // 分享标题
    link: '', // 分享链接,该链接域名或路径必须与当前页面对应的服务号JS安全域名一致
    imgUrl: '', // 分享图标
    success: function () {
      // 设置成功
    }
  })
}); 

# The API for obtaining the click status of the "Share to WeChat Moments" button and customizable sharing content will be discontinued soon.

wx.onMenuShareTimeline({
  title: '', // 分享标题
  link: '', // 分享链接,该链接域名或路径必须与当前页面对应的服务号JS安全域名一致
  imgUrl: '', // 分享图标
  success: function () {
  // 用户点击了分享后执行的回调函数
  }
},

# Get the click status of the "Share to a Friend" button and customize the sharing content interface (about to be scrapped)

wx.onMenuShareAppMessage({
  title: '', // 分享标题
  desc: '', // 分享描述
  link: '', // 分享链接,该链接域名或路径必须与当前页面对应的服务号JS安全域名一致
  imgUrl: '', // 分享图标
  type: '', // 分享类型,music、video或link,不填默认为link
  dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空
  success: function () {
    // 用户点击了分享后执行的回调函数
  }
});

# Get "Share to QQ" button click status and custom sharing content interface (will be abandoned)

wx.onMenuShareQQ({
  title: '', // 分享标题
  desc: '', // 分享描述
  link: '', // 分享链接
  imgUrl: '', // 分享图标
  success: function () {
  // 用户确认分享后执行的回调函数
  },
  cancel: function () {
  // 用户取消分享后执行的回调函数
  }
});

# Get "Share to QQ Space" button click status and custom sharing content interface (will be abandoned)

wx.onMenuShareQZone({
  title: '', // 分享标题
  desc: '', // 分享描述
  link: '', // 分享链接
  imgUrl: '', // 分享图标
  success: function () {
  // 用户确认分享后执行的回调函数
  },
  cancel: function () {
  // 用户取消分享后执行的回调函数
  }
});

# Image Interface

# Take a photo or select a picture from your phone album

wx.chooseImage({
  count: 1, // 默认9
  sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
  sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
  success: function (res) {
  var localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
  }
});

# Preview Picture Interface

wx.previewImage({
  current: '', // 当前显示图片的http链接
  urls: [] // 需要预览的图片http链接列表
});

# Upload Image Interface

wx.uploadImage({
  localId: '', // 需要上传的图片的本地ID,由chooseImage接口获得
  isShowProgressTips: 1, // 默认为1,显示进度提示
  success: function (res) {
    var serverId = res.serverId; // 返回图片的服务器端ID
  }
});

Note: upload pictures valid for 3 days, available WeChat multimedia interface to download pictures to their own server, where the serverId media_id.

# Download Picture Interface

wx.downloadImage({
  serverId: '', // 需要下载的图片的服务器端ID,由uploadImage接口获得
  isShowProgressTips: 1, // 默认为1,显示进度提示
  success: function (res) {
    var localId = res.localId; // 返回图片下载后的本地ID
  }
});

# Get a local image interface

wx.getLocalImgData({
  localId: '', // 图片的localID
  compressionRatio: 0.3, // 压缩比例,iOS 默认值 0.3
  success: function (res) {
    var localData = res.localData; // localData是图片的base64数据,可以用img标签显示
  }
});

Note: This interface is only available under iOS WKWebview for compatibility with iOS WKWebview does not support localId direct display of images.Refer to the iOS WKWebview Web Development Adaptation Guide

# Audio interface

# Start the recording interface

wx.startRecord();

# Stop the recording interface

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

# Listening recording automatically stops the interface

wx.onVoiceRecordEnd({
// A complete callback will be performed when the recording is longer than one minute without stopping
  complete: function (res) {
  var localId = res.localId;
}
});

# Play a voice interface

wx.playVoice({
  localId: '' // 需要播放的音频的本地ID,由stopRecord接口获得
});

# Pause the playback interface

wx.pauseVoice({
  localId: '' // 需要暂停的音频的本地ID,由stopRecord接口获得
});

# Stop playing the interface

wx.stopVoice({
  localId: '' // 需要停止的音频的本地ID,由stopRecord接口获得
});

# Listen to the Voice After Playing Interface

wx.onVoicePlayEnd({
  success: function (res) {
    var localId = res.localId; // 返回音频的本地ID
  }
});

# Upload voice interface

wx.uploadVoice({
  localId: '', // 需要上传的音频的本地ID,由stopRecord接口获得
  isShowProgressTips: 1, // 默认为1,显示进度提示
  success: function (res) {
    var serverId = res.serverId; // 返回音频的服务器端ID
  }
});

Note: Upload voice valid for 3 days, you can download voice to your own server with WeChat multimedia interface, The serverId obtained here is media_id, and refers to the documentation. The current frequency limit for the multimedia file download interface is 10000 times / day. If you need to increase the frequency, please log in to the WeChat Official Platform and in the Development - Interface Permissions list, request to increase a temporary maximum.

# Download the Voice Interface

wx.downloadVoice({
  serverId: '', // 需要下载的音频的服务器端ID,由uploadVoice接口获得
  isShowProgressTips: 1, // 默认为1,显示进度提示
  success: function (res) {
    var localId = res.localId; // 返回音频的本地ID
  }
});

# Smart Interface

# Recognize audio and return recognition result interface

wx.translateVoice({
  localId: '', // 需要识别的音频的本地Id,由录音相关接口获得
  isShowProgressTips: 1, // 默认为1,显示进度提示
  success: function (res) {
    alert(res.translateResult); // 语音识别的结果
  }
});

# Equipment Information

# Get a network state interface

wx.getNetworkType({
  success: function (res) {
    var networkType = res.networkType; // 返回网络类型2g,3g,4g,wifi
  }
});

# geographical location

# Use the WeChat built-in map view location interface

wx.openLocation({
  latitude: 0, // 纬度,浮点数,范围为90 ~ -90
  longitude: 0, // 经度,浮点数,范围为180 ~ -180。
  name: '', // 位置名
  address: '', // 地址详情说明
  scale: 1, // 地图缩放级别,整型值,范围从1~28。默认为最大
  infoUrl: '' // 在查看位置界面底部显示的超链接,可点击跳转
});

# Get a geolocation interface

wx.getLocation({
  type: 'wgs84', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
  success: function (res) {
    var latitude = res.latitude; // 纬度,浮点数,范围为90 ~ -90
    var longitude = res.longitude; // 经度,浮点数,范围为180 ~ -180。
    var speed = res.speed; // 速度,以米/每秒计
    var accuracy = res.accuracy; // 位置精度
  }
});

# Shake the neighborhood

# Turn on the Find Around ibeacon device interface

wx.startSearchBeacons({
  ticket:"",  //摇周边的业务ticket, 系统自动添加在摇出来的页面链接后面
  complete:function(argv){
    //开启查找完成后的回调函数
  }
});

Note: To access the Rocky Rock Neighborhood feature, please refer to: Request to open Rocky Rock

# Turn off Find Around ibeacon device interface

wx.stopSearchBeacons({
  complete:function(res){
    //关闭查找完成后的回调函数
  }
});

# Listening peripheral ibeacon device interface

wx.onSearchBeacons({
  complete:function(argv){
    //回调函数,可以数组形式取得该商家注册的在周边的相关设备列表
  }
});

Note: For the above mentioned usage precautions for the rocker peripheral interface and more instructions for returning results, please refer to: rocker periperipherals for equipment information

# Interface operations

# Close the current web window interface

wx.closeWindow();

# Bulk Hidden Function Button Interface

wx.hideMenuItems({
  menuList: [] // 要隐藏的菜单项,只能隐藏“传播类”和“保护类”按钮,所有menu项见附录3
});

# Bulk display feature button interface

wx.showMenuItems({
  menuList: [] // 要显示的菜单项,所有menu项见附录3
});

# Hide all non-basic button interfaces

wx.hideAllNonBaseMenuItem();
// The "Basic Class" button is detailed in Appendix 3

# Show all functional button interfaces

wx.showAllNonBaseMenuItem();

# WeChat Sweep

# Turn up WeChat Scan the interface

wx.scanQRCode({
  needResult: 0, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,
  scanType: ["qrCode","barCode"], // 可以指定扫二维码还是一维码,默认二者都有
  success: function (res) {
    var result = res.resultStr; // 当needResult 为 1 时,扫码返回的结果
  }
});

# WeChat Card voucher

WeChat Unlike the signature credential API_ticket used in the voucher interface, which is jsapi_ticket, the developer needs to complete two different signatures in succession during the call to the WeChat voucher JS-SDK and ensure the cache of the credentials.

# Get api_ticket

The api_ticket is a temporary ticket used to call the WeChat ticket JSAPI, valid for 7200 seconds, obtained by access_token.

Developers' Note:

  1. This API_Ticket for signing the Card Ticket interface is different from the JSAPI_Ticket configuration used in step 3 to inject permission validation through the Config interface.

  2. Because the number of API calls to get API_ticket is very limited, frequent refreshing API_ticket will lead to limited API calls, affecting their own business, developers need to store and update API_ticket in their own services.

Dxplaination of Interface Call Request

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

Parameter explaination

parameter Do I have to? Introductions
access_token yes Interface call credentials

Return data

Data examples:

{
  "errcode":0,
  "errmsg":"ok",
  "ticket":"bxLdikRXVbTPdHSM05e5u5sUoXNKdvsdshFKA",
  "expires_in":7200
}
Parameter Name describe
errcode Error code
errmsg Error message
ticket Api_ticket, the certificate required for signing in the card ticket interface
expires_in Validity time

Error code

Error code Error message
40097 Type parameter error

# Drag a list of applicable coupons and get user selection information

wx.chooseCard({
  shopId: '', // 门店Id
  cardType: '', // 卡券类型
  cardId: '', // 卡券Id
  timestamp: 0, // 卡券签名时间戳
  nonceStr: '', // 卡券签名随机串
  signType: '', // 签名方式,默认'SHA1'
  cardSign: '', // 卡券签名
  success: function (res) {
    var cardList= res.cardList; // 用户选中的卡券列表信息
  }
});
Parameter Name Required to fill in type Example values describe
shopId no string(24) 1234 Store ID. The shopID is used to filter out the list of coupons with the specified location_list (shopID).
cardType no string(24) GROUPON Coupon type, used to pull up a list of coupons for a specified voucher type. When cardType is empty, the default pull up the list of all card coupons, not required.
cardId no string(32) p1Pj9jr90_SQRaVqYI239Ka1erk Card voucher ID, used to pull up the card voucher list specified cardId, when cardId is empty, the default pull up the list of all card vouchers, not required.
timestamp yes string(32) 14300000000 Time stamp.
nonceStr yes string(32) sduhi123 Random character string.
signType yes string(32) SHA1 Currently only SHA1 is supported.
cardSign yes string(64) abcsdijcous123 Signature.

CardSignSee Appendix 4 for details.

Developers should be especially careful: a signature error can cause the pull-up voucher list to be abnormally empty. Please double check the validity of the parameters involved in the signature.

Special reminders

The pull-up list only relates to the user's local coupons. There are three common situations when the pull-up listing is abnormally empty: a signature error, an invalid timestamp, or an incorrect filtering mechanism. Ask the developer to check the location cause in turn.

# Add a voucher interface in bulk

wx.addCard({
  cardList: [{
    cardId: '',
    cardExt: ''
  }], // 需要添加的卡券列表
  success: function (res) {
    var cardList = res.cardList; // 添加的卡券列表信息
  }
});

CardExtSee appendix 4 for more details. Developers who call the interface to report exceptions such as a signature error, a receipt, etc. can refer to: Method for detecting signature error in coupons

# Check the coupon interface in the WeChat card package

wx.openCard({
  cardList: [{
    cardId: '',
    code: ''
  }]// 需要打开的卡券列表
});

# WeChat Payment

# Initiate a WeChat payment request

Please refer to WeChat Payment documentation, JSAPI Up Payment API: https://pay.weixin.qq.com/doc/v3/merchant/4012791857

Note:

WeChat Payment V2 development documentation: https://pay.weixin.qq.com/doc/v2/merchant/4011987975

WeChat Payment V3 development documentation: https://pay.weixin.qq.com/doc/v3/merchant/4012062524

# Quick input

# Shared shipping address interface

wx.openAddress({
  success: function (res) {
    var userName = res.userName; // 收货人姓名
    var postalCode = res.postalCode; // 邮编
    var provinceName = res.provinceName; // 国标收货地址第一级地址(省)
    var cityName = res.cityName; // 国标收货地址第二级地址(市)
    var countryName = res.countryName; // 国标收货地址第三级地址(国家)
    var detailInfo = res.detailInfo; // 详细收货地址信息
    var nationalCode = res.nationalCode; // 收货地址国家码
    var telNumber = res.telNumber; // 收货人手机号码
  }
});

Note:

WeChat Data fields used for address sharing include:

  • Name of the consignee
  • Regions, provinces and urban areas
  • Detailed address
  • postal code
  • Contact telephone

Among them, the region corresponds to a national standard Tier 3 regional code, such as "Guangdong - Guangzhou - Tianhe District," and the corresponding postcode is 510630.For details, please refer to: http://xzqh.mca.gov.cn/defaultQuery

# Appendix | JS-SDK Permission Signature Algorithm

jsapi_ticket

Before generating a signature, you must first understand jsapi_ticket, a temporary ticket that Service Account uses to invoke the WeChat JS interface.Normally, jsapi_ticket has a validity of 7200 seconds and is obtained by access_token.Because the number of API calls to get jsapi_ticket is very limited, frequent refreshing jsapi_ticket will lead to limited API calls, affecting their own business, developers must cache jsapi_ticket globally in their own services.

  1. Refer to the following documentation for access_token (valid for 7200 seconds, developers must globally cache access_token in their own service): https://developers.weixin.qq.com/doc/service/api/base/api_getaccesstoken.html

  2. Using the first step, access_token makes an HTTP GET request for jsapi_ticket (valid for 7,200 seconds, and developers must cache jsapi-ticket globally on their services): https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi

Returns the following JSON:

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

Once you get the jsapi_ticket, you can generate a signature for JS-SDK permission validation.

Signature Algorithm

The signature generation rule is as follows: The fields participating in the signature include nonce str (random character string), valid jsapi_ticket, timestamp, url (URL of the current page, excluding # and following).After sorting all the parameters to be signed by the ASCII code of the field name from small to large (lexicographic order), use the format of the URL key value pair (i.e. key1 = value1 & key2 = value2...As the character string 1. Note here that all parameter names are lowercase characters. String1 is sha1 encrypted with the original field name and field value, without URL escape.

Signature = sha1 (string1).Examples:

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

Step 1. After sorting all the parameters to be signed according to the ASCII code of the field name from small to large (lexicographic order), use the URL key-value pair format (i.e. key1 = value1 & key2 = value2...Into the character string 1

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

Step 2. Sign string1 sha1 to get the signature:

0f9de62fce790f9a083d5c99e95740ceb90c27ed

Note

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

  2. The url used for the signature must be the full URL of the page calling the JS interface.

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

If there is an invalid signature and other errors, see Appendix 5 Common Errors and Solutions.

# Appendix | List of all JS interfaces

Version 1.6.0 Interface

updateAppMessageShareData
updateTimelineShareData
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
addCard
chooseCard
openCard

# Appendix | List of All Menu Items

Basic categories

举报: "menuItem:exposeArticle"
调整字体: "menuItem:setFont"
日间模式: "menuItem:dayMode"
夜间模式: "menuItem:nightMode"
刷新: "menuItem:refresh"
查看服务号(已添加): "menuItem:profile"
查看服务号(未添加): "menuItem:addContact"

Category of Communication

发送给朋友: "menuItem:share:appMessage"
分享到朋友圈: "menuItem:share:timeline"
分享到QQ: "menuItem:share:qq"
分享到Weibo: "menuItem:share:weiboApp"
收藏: "menuItem:favorite"
分享到FB: "menuItem:share:facebook"
分享到 QQ 空间 "menuItem:share:QZone"

Category of Protection

编辑标签: "menuItem:editTag"
删除: "menuItem:delete"
复制链接: "menuItem:copyUrl"
原网页: "menuItem:originPage"
阅读模式: "menuItem:readMode"
在QQ浏览器中打开: "menuItem:openWithQQBrowser"
在Safari中打开: "menuItem:openWithSafari"
邮件: "menuItem:share:email"
一些特殊服务号: "menuItem:share:brand"

# Appendix | Permission comparison table

Different Service Account types have different interface permissions, as shown in the following table:

1, microblogging authentication as unauthenticated, so microblogging authentication Service Account will not have WeChat authentication service number unique interface.

2, WeChat certification is divided into two parts of quality certification and name certification, only need quality certification through, you can get the interface.

Interface Name Unauthenticated subscription number WeChat Certified subscription number Uncertified Service Account WeChat Certification Service Account
User Management - Get a list of users Yes Yes
User Management - Get a user's geographic location Yes
WeChat Payment Interface Application required
Weixin Store Interface Application required
WeChat Card Coupon Interface Application required Application required
WeChat Device function interface Application required
WeChat Invoice interface Yes Yes
WeChat JS-SDK- Basic interface Yes Yes Yes Yes
WeChat JS-SDK- Sharing interface Yes Yes
WeChat JS-SDK- Image interface Yes Yes Yes Yes
WeChat JS-SDK- Audio interface Yes Yes Yes Yes
WeChat JS-SDK - Smart Interfacing (web speech recognition) Yes Yes Yes Yes
WeChat JS-SDK- Device information Yes Yes Yes Yes
WeChat JS-SDK- Geographical location Yes Yes Yes Yes
WeChat JS-SDK-Interface operation Yes Yes Yes Yes
WeChat JS-SDK-WeChat Sweep Yes Yes Yes Yes
WeChat JS-SDK- Weixin Store Yes
WeChat JS-SDK- WeChat Card Voucher Yes Yes
WeChat JS-SDK-WeChat Pay Yes

# Appendix | Card Extension Field and Signature Generation Algorithm

# 1. JSSDK For users, please read here. JSAPI users can skip

The signature of the card coupon and the signature of JSSDK are completely independent, and the algorithm and meaning of the two are completely different, so please do not confuse them.The signature of the JSSDK is a layer of authentication that all JS interfaces need to go through to identify the identity of the caller, and has nothing to do with the card itself. Secondly, the signature of the voucher took into account the extensibility of the protocol and the simple prevention of data tampering, and a separate set of signature protocols was designed. In addition, due to historical reasons, the JS interface for coupons preceded the JSSDK, and the JS API did not have a authentication system at that time, so the appsecret / api_ticket identity information was added to the signature of the coupons, so the developer would understand.

# 2. Ticket api_ticket

The ticket api_ticket is a temporary ticket used to invoke the ticket related interface, valid for 7200 seconds, obtained by access_token.It is important to distinguish this from jsapi_ticket. Because the number of API calls to obtain voucher api_ticket is very limited, frequently refreshing voucher app_ticket causes limited API calls and affects the business, and developers must cache voucher ip_ticket globally on their services.

1.Refer to the following documentation for access_token (valid for 7200 seconds, developers must cache globally on their own servicesaccess_token):../15/54ce45d8d30b6bf6758f68d2e95bc627.html

2.Using the first step, access_token makes an HTTP GET request for a card api_ticket (valid for 7,200 seconds, and developers must cache the card api-ticket globally on their services): https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=wx_card

# 3. Card Voucher Extended Field cardExt Dxplaination

CardExt itself is a JSON character string that is the unique information that the merchant assigns to the card.

field Is it compulsory? Are you involved in the signature? Introductions
code no yes The specified card coupon code can only be received once. Custom code mode vouchers must be filled in, non-custom code and stored code mode vouchers do not need to fill in. See: Whether to Customize Code
openid no yes Specifies the recipient's openid, which only the user can collect. Vouchers whose bind_openid field is true must be filled in, and whose bind_openid field is false need not be filled in.
timestamp yes yes Timestamp, the number of seconds from 00: 00: 00 on January 1, 1970 until now, that is, the current time, and eventually need to be converted to a character string; Once generated by the merchant, the timestamps for different additional requests must be dynamically generated, and repeating them will result in a collection failure!
nonce_str no yes Random character string, passed in by the developer to enhance security (if not filled in may be replayed request). Random character string, no longer than 32 bits. It is recommended to use upper and lower case letters and numbers, and the nonce of different add requests must be generated dynamically, if repeated, it will result in failure to receive.
fixed_begintimestamp no no The actual time of receipt of the voucher in the third-party system is the time stamp of the East Eight Districts (UTC + 8, accurate to seconds). When the validity type of the card voucher is DATE_TYPE_FIX_TERM, it is used to identify the actual effective time of the card voucher, which is used to solve the problem that the starting time and the receiving time are not synchronized in the merchant system.
outer_str no no Receipt channel parameter, used to identify the channel value of this receipt.
signature yes - Signature: The merchant will sign the parameters in the interface list in accordance with the specified way, and the signature method uses SHA1, the specific signature scheme is referred to below; Entered by the merchant after signing in accordance with the specifications.

Signature Notes

  1. Lexicographically sort the character string with the values api_ticket, timestamp, card_id, code, openid, nonce_str.

  2. Concatenate all the argument character strings into a string and sha1 encrypt to get the signature.

  3. The timestamp, nonce field in signature and the timestamp, nonce_str field in card_ext must be consistent.

  4. code=1434008071,timestamp=1404896688,card_id=pjZ8Yt1XGILfi-FUsewpnnolGgZk,Api_ticket = ojZ8YtyVyr30HheH3CM73y7h4jJE, nonce_str = 123 thensignature=sha1(12314048966881434008071ojZ8YtyVyr30HheH3CM73y7h4jJEpjZ8Yt1XGILfi-FUsewpnnolGgZk)=f137ab68b7f8112d20ee528ab6074564e2796250。

Developers are strongly encouraged to use the Signature Tool SDK in the Voucher Pack for signature or to use the debug tool for verification: http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=cardsign

# 4. Certificate Signature cardSign Instructions

1.Convert api_ticket, AppID、location_id、timestamp、nonce_str、card_id、card_typeTo lexicographically sort character strings using the value of.

  1. All the parameters of the string will be stitched together into a character string sha1 encryption, get cardSign.

# Appendix | Common Errors and Resolutions

When calling the config interface, pass in the parameterdebug: trueto enable debug mode, and the page alerts with an error message.The following are common errors and solutions:

1.invalid url domainThe domain name for the current page is not tied to the AppID used,Make sure to fill in the bound domain name correctly. Only port 80 (http) and 443 (https) are supported, so you don't need to fill in a port number (one appid can bind three valid domain names, see ] directory 1.1.1 ).

  1. Invalid signature Signature error. It is recommended to check in the following order:
  • Verify that the signature algorithm is correct, using http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=jsapisign page tool to verify.
  • Verify that the nonceStr, timestamp in the config is the same as the noncestr, timestamp in the signature.
  • Confirm that the URL is the full URL of the page (please alert (location.href.split ('#')) on the current page[0]) confirmation), including the'http (s): / /'section, and the '?The 'after the GET parameter part, but not the part after the' # 'hash.
  • Verify that the AppID in the config matches the appid used to get the jsapi_ticket.
  • Make sure to cache access_token and jsapi_ticket.
  • Make sure you get the URL you use to sign it dynamically. Dynamic pages can be seen in the example code for how PHP is implemented. If it is a static html page in the front end through ajax url to the background signature, the front end needs to use js to get the current page to remove the '#' hash part of the link (available location.href.split ('#'))[0]Retrieve, and you need to encodeURIComponent, because once the page is shared, the WeChat client adds additional parameters at the end of your link, which, if not dynamically fetching the current link, will cause the shared page to fail to sign.

3.the permission value is offline verifyingThe error occurred because the config did not execute correctly, or because theJSAPIwas not called into theconfigjsApiList`parameter.It is recommended to check in the following order:

  • Verify that the config is passed correctly.
  • If the JSAPI is called when the page is loaded, it must be written in the callback of wx.ready.
  • Verify that the config's jsApiList parameter contains the JSAPI.

4.Permission denied The Service Account does not have permission to use this JSAPI, or the JSAPI called is not in the jsApiList parameter passed in the config (some interfaces require authentication before they can be used).

  1. Function not exist This interface is not supported in the current version of the Guest Account. Please upgrade to the new experience.

  2. Why is the 6.0.1 version config: ok, but not ok after the 6.0.2 version (because there was no permission verification before the 6.0.2 version, So the config is all ok, but this does not mean that the signature in your config is ok, please verify in 6.0.2 that the correct signature is generated to ensure that the config is ok in the later version. )

7.It is not possible to share on iOS or Android (make sure Service Account is authenticated. Only authenticated service numbers have permission to share the interface. If you do authenticate, check whether the listening interface is triggered in the wx.ready callback function)

  1. The service can not get jsapi_ticket after the line, no problem when testing.(Because access_token and jsapi_ticket must be cached in their own server, otherwise the frequency limit will be triggered when they go live.)Make sure to cache tokens and tickets to reduce the number of server requests by 2, not only to avoid the trigger frequency limit, but also to speed up your own service. At present, 1w is provided for convenience of testing. After the valve value is exceeded, the service will no longer be available. Make sure to cache access_token and jsapi_ticket globally before the service goes live. Both are valid for 7200 seconds, otherwise the service will not be available once the frequency limit is triggered.

  2. How to upload multiple images (currently only supports uploading one image at a time, multiple images need to wait for the previous image to upload and then call the interface)

  3. No preview of locally selected images (the chooseImage interface itself supports previewing, no additional support required)

11.Jump through a link (e.g. login with WeChat first) to a link b,invalid signature failed (The backend generated a signed link using the current link from the jssdk, which is the b link after the jump. Please don't use the authorized link for WeChat login to calculate the signature. The backend signed URL must be the full URL of the current page using the jsSDK, with the '#' part removed)

  1. Config: fail error (this is due to incomplete config parameters passed in, make sure you pass in the correct appId, timestamp, nonceStr, signature, and jsApiList you need to use)

13.How to download a multimedia resource uploaded by jsapi to WeChat to your server (see the notes on uploadVoice and uploadImage interfaces in the documentation)

14.Android is uploaded to the WeChat server via jssdk, and third parties download it from WeChat to their own server, and there is noise. (The WeChat team has fixed this problem, and the backend is now optimized for online)

  1. Binding a parent domain and whether its sub-domains are also available (yes, legitimate sub-domain is fully supported after binding the parent domain)

16.In iOS WeChat 6.1, the shared image outer link does not appear, only the image within the Service Account page or the image from the WeChat server. This was fixed in 6.2

  1. Is it necessary to make your own compatibility with the lower versions (JS SDKs are all compatible with the lowest versions and do not require third parties to do more on their own, but some interfaces were introduced in 6..0.2 and can only be invoked in the new version)

18.The Service Account payment signature is invalid and cannot initiate the transaction (please make sure you are using the official online version of jweixin.js,Not only can it reduce user traffic, but it is possible to fix certain bugs and copy them to third-party servers. Officials will not provide guarantees for any problems that arise. For specific payment signing algorithms, refer to JSSDK WeChat payment column.)

19.Currently the Android WeChat client does not support the new H5 feature of pushState, so using pushState to implement a webapp's page causes the signature to fail. This problem was fixed in Android 6.2

  1. UploadImage in the callback of chooseImage sometimes Android will not execute, Android6.2 will solve this problem, if you need to support the lower version can be called UploadImage in setTimeout delay 100ms to solve

  2. The requestsubscribe error indicates that you are not subscribed to the test number. The error appears only for the test number

  3. The coordinates returned by getLocation are deviations from openLocation because getLocation returns GPS coordinates. The Tencent map opened by openLocation is Mars coordinates, which requires a third party to make the conversion. From version 6.2, it has been supported to directly obtain Mars coordinates.

23.View Service Account (not added): "menuItem: addContact" is not displayed, currently only links propagated from the service number can be displayed, the source must be the service number

  1. ICP filing data synchronization has a day delay, so please bind on the second day

# Appendix | DEMO Page and Sample Code

DEMO Page:

https://www.weixinsxy.com/jssdk/

Example code: https://www.weixinsxy.com/jssdk/sample.zip Note: The link contains PHP, Java, Nodejs and Python sample code for reference by third parties, third parties remember to get accestoken and jsapi_ticket cache to ensure that the frequency limit does not trigger.

# Appendix | Question Feedback

WeChat JS-SDK Feedback

Describe the problem in plain language, and explain the scene where the problem occurred. Attach a screenshot. WeChat The team will process your feedback as soon as possible.