Micro-letter JS interface Daquan _javascript Skills

Source: Internet
Author: User
Tags sha1 sha1 encryption ticket

This article for everyone to share the JS micro-letter interface detailed version for your reference, the specific content as follows

Basic description
Instructions for use
1. Introduction of JS file
in the need to call the JS interface page to introduce the following JS file, (support HTTPS): Http://res.wx.qq.com/open/js/jweixin-1.0.0.js
Note: Supports loading using the Amd/cmd standard module loading method
2. Injection Config Config interface
All pages that need to use JSSDK must first inject configuration information, or they will not be able to invoke (the same URL needs to be invoked only once, and the Web app for the spa that changes the URL can be invoked each time the URL changes).

 Wx.config ({
 debug:true,//Open debug mode, the return value of all invoked APIs will be on the client alert, to view incoming parameters, can be opened on the PC side, the parameter information will be typed through the log, only on the PC side will print.)
 appId: ',//must fill, public number unique identification
 timestamp:,//required, generate signature timestamp
 noncestr: ',//must fill, generate signed random string
 signature: ',//must fill, sign Name, see Appendix 1
 jsapilist: []//must fill in, need to use the JS interface list, all JS interface list see Appendix 2
});

3. Verify through the Ready interface

 Wx.ready (function () {

 //config information is validated to perform the Ready method, all interface calls must be obtained after the Config interface has the result, config is a client-side asynchronous operation. So if you need to call the relevant interface when the page loads, then you must place the relevant interface in the ready function to make sure it executes correctly. For interfaces that are invoked when a user fires, they can be called directly and do not need to be placed in the ready function.
});

4. Verify failure Error interface

 Wx.error (function (res) {
//config Information validation failure performs an error function, such as a signature expiration that causes validation to fail, and the specific error message can be viewed in the debug mode of config, or in the returned res parameter. For spa you can update your signature here.
});

Interface Invocation Description
all interfaces are invoked through the WX object (which can also be used with the Jweixin object), which is an object that, in addition to the parameters that each interface needs to pass, has the following general parameters:
1. Success: The callback function that is executed when the interface call succeeds.
2. Fail: A callback function that executes when an interface call fails.
3. Complete: A callback function that executes when an interface call completes, regardless of success or failure.
4. Cancel: When the user clicks on the cancellation function, only some of the users cancel the operation of the API will be used.
5. Trigger: A method that triggers when the button clicks on the menu, which supports only the relevant interfaces in menu.

Each of these functions comes with a parameter, the type is an object, in addition to the data returned by each interface itself, there is a common attribute errmsg, whose value is formatted as follows:
1. When the call succeeds: "Xxx:ok", where xxx is the calling interface name
2. When the user cancels: "Xxx:cancel", where xxx is the calling interface name
3. When the call fails: its value is a specific error message

Base interface
determines whether the current client version supports the specified JS interface

 Wx.checkjsapi ({
jsapilist: [' chooseimage ']///need to detect a list of JS interfaces, List of all JS interfaces See Appendix 2,
success:function (res) {
// Returns as a key-value pair, the available API value is true, and cannot be used to false
//such as: {"Checkresult": {"Chooseimage": "True}", "ErrMsg": "Checkjsapi:ok"}

);

Sharing Interface
Get "Share to Circle" button click Status and custom Share content interface

 Wx.onmenusharetimeline ({
 title: ',//share title
 Link: ',//Share link
imgurl: ',//share icon
success:function ( { 
//user confirms the share after the callback function executed
},
cancel:function () { 
//user cancel sharing after the callback function
}
});

Get "Share to Friend" button click Status and custom Share content interface

 Wx.onmenushareappmessage ({title: ',//share title desc: ',//Share description Link: ',//share
 link
 imgurl: ',
 //share icon Type: ',//share types, music, video, or link, do not fill default for link
dataurl: ',//if type is music or video, provide data link, default is empty
success: function () { 
//user confirm share after the execution of callback functions
},
cancel:function () { 
//user cancel sharing after the implementation of the callback function
}
});

Get "Share to QQ" button click State and custom Sharing content interface

 Wx.onmenushareqq ({title: ',//share title desc: ',//share
 Description Link: ',//share
 link
 imgurl: '//share icon
succ Ess:function () { 
//The callback function executed after the user confirms the share
},
cancel:function () { 
//user cancels sharing the callback function
}
});

Get "share to Tencent Weibo" button click Status and custom Share content interface

 Wx.onmenushareweibo ({title: ',//share title desc: ',//share
 Description Link: ',//share
 link
 imgurl: '//share icon
s Uccess:function () { 
//The callback function executed after the user confirms the share
},
cancel:function () { 
//user cancels sharing the callback function
}
});

Image interface
Take a picture or select an interface from a mobile album

 Wx.chooseimage ({
 success:function (res) {
  var localids = res.localids;//Returns a list of local IDs for the selected photos. Localid can be used as the SRC attribute of the IMG tag to display the picture
 }
});

Preview Picture Interface

 Wx.previewimage ({
 current: ',//The currently displayed picture link
 URLs: []//List of pictures to be previewed
});

Upload Image interface

 Wx.uploadimage ({
localid: '///////////////////////////////////////)
 Success:function (res) {
  var serverid = Res.serverid;//Return the server-side ID of the picture}
});

Note: Use the micro-letter download multimedia file interface Download uploaded pictures, the ServerID is media_id, reference documents. /12/58bfcfabbd501c7cd77c19bd9cfa8354.html

Download Picture interface

 Wx.downloadimage ({
serverid: ',//the server-side ID of the picture that needs to be downloaded, isshowprogresstips:1//by the Uploadimage interface
, defaults to 1, showing progress tips
 Success:function (res) {
  var localid = res.localid;//return the local ID} after the picture is downloaded
 }
);

Audio interface
Start Recording interface
Wx.startrecord ();
Stop Recording Interface

 Wx.stoprecord ({
 success:function (res) {
  var localid = res.localid;
 }
});

Monitor audio to automatically stop the interface

 Wx.onvoicerecordend ({
 ////recording time is not stopped for more than one minute will execute complete callback
complete:function (res) {
var localid = res.localid; 
}
});

Play Voice interface

 Wx.playvoice ({
 localid: '//local ID of the audio to be played, obtained by the Stoprecord Interface
});

Pause Playback Interface

 Wx.pausevoice ({
 localid: '//local ID of the audio to be paused, obtained by the Stoprecord Interface
});

Stop Playback interface

 Wx.stopvoice ({
 localid: '//local ID of the audio to be stopped, obtained by the Stoprecord Interface
});
 

Monitor Voice Playback Complete interface

 Wx.onvoiceplayend ({
 serverid: ',//server-side ID of audio to be downloaded, obtained
 success:function (res) {var by the Uploadvoice interface
  Localid = Res.localid; Returns the local ID of the audio
 }
});

Upload Voice interface

 Wx.uploadvoice ({
localid: '////////////////////////////////////////
 Success:function (res) {
  var serverid = Res.serverid;//Return the server-side ID of the audio
 }
});

Note: The use of micro-letter download multimedia file interface to download the voice of the upload, the ServerID is media_id, reference documents. /12/58bfcfabbd501c7cd77c19bd9cfa8354.html
Download Voice interface

 Wx.downloadvoice ({
serverid: ',//the server-side ID of the audio that needs to be downloaded, isshowprogresstips:1//by the Uploadvoice interface
defaults to 1, showing progress tips
 Success:function (res) {
  var localid = res.localid;//return audio local ID
 }
});

Intelligent interface
Identify the audio and return the recognition result interface

Wx.translatevoice ({
localid: "////
/////////////////////////////////////////) Success:function (res) {
alert (res.translateresult);//Speech recognition Results
}
});

Device information
Get Network State interface

 Wx.getnetworktype ({
 success:function (res) {
  var networktype = Res.networktype;//return network type 2g,3g,4g,wifi
 }
});

Location
Use the micro-letter built-in map to view the location interface

 Wx.openlocation ({
 latitude:0,//latitude, floating-point number, range is ~ -90
 longitude:0,//longitude, floating point number, RANGE 180 ~-180.)
 name: ',//Location name
 : ',//address details Description
 scale:1,//Map zoom level, reshape value, range from 1~28. Default is maximum
Infourl: '//The hyperlink displayed at the bottom of the view position interface, click Jump
};

Get the Geography interface

 Wx.getlocation ({
 timestamp:0,//Position signature timestamp, available only if a compatible 6.0.2 version is required before
 noncestr: ',//position signature random string, available only if compatible with 6.0.2 version required
 addrsign: ',//location signature, available only prior to compatibility with 6.0.2 versions, as detailed in Appendix 4
 success:function (res) {
  var longitude = res.longitude; Latitude, floating point number, range of -90
  var latitude = res.latitude;//longitude, floating-point number, range 180 ~ 180.
  var speed = res.speed//speed, var accuracy = Res.accuracy in M/s;/
  /position Precision
 }
};

Interface operation
Hide the upper right corner menu Interface Wx.hideoptionmenu ();
Display the upper right corner menu Interface Wx.showoptionmenu ();
Closes the current page window interface Wx.closewindow ();
Bulk Hide Function Button interface

 Wx.hidemenuitems ({
 menulist: []//menu items to hide, all menus are shown in Appendix 3
});

Bulk Display Function Button interface

 Wx.showmenuitems ({
 menulist: []//menu items to display, all menus are shown in Appendix 3
});

Hides all non-basic button interface Wx.hideallnonbasemenuitem ();
Display all Function button interface Wx.showallnonbasemenuitem ();

micro-letter sweep
To adjust the micro-letter sweep interface

 Wx.scanqrcode ({
desc: ' Scanqrcode desc ',
needresult:0,//defaults to 0, scan results by micro-mail processing, 1 direct return scan results,
scantype: ["  QRCode "," BarCode "],//can specify a sweep two-dimensional code or a one-dimensional code, the default both have
Success:function () {
var result = res.resultstr;//When Needresult is 1 o'clock, the result of the sweep code return
}
});

Harvest Address
Edit Receipt Address interface

 Wx.editaddress (
 timestamp:0,//Position signature timestamp, available only if a compatible 6.0.2 version is required)
 noncestr: ',//position signature random string, available
 only if compatible with 6.0.2 version required Addrsign: ',//location signature, available only prior to compatibility with 6.0.2 versions, as detailed in Appendix 4
 success:function (res) {
  var userName = res.username;//Consignee name 
   var telnumber = Res.telnumber; Consignee telephone
  var postalCode = Res.postalcode;//Postal code
  var provincename = res.provincename;//GB receipt address First level address
  var Cityna me = Res.cityname; National standard receiving address the second level address
  var countryname = res.countryname;//GB receiving address the third level address
  var adress = res.address;//Detailed delivery address information
  VA R Nationalcode = Res.nationalcode; Delivery address country code
 }
});

Get the nearest delivery address interface

 Wx.getlatestaddress ({
 timestamp:0,//Position signature timestamp, available only if a compatible 6.0.2 version is required before
 noncestr: ',//position signature random string, Provide addrsign: ',//position signatures only prior to compatibility with the 6.0.2 version,
 only if 6.0.2 version is required, as detailed in Appendix 4
 success:function (res) {
  var userName = Res.username; Consignee name
  var telnumber = res.telnumber;//Consignee telephone
  var postalCode = res.postalcode;//Zip code
  var provincename = Res . provincename; GB receiving address the first level address
  var cityname = res.cityname;//GB receiving address the second level address
  var countryname = res.countryname;//GB receiving address third-level address 
   var address = res.address; Detailed receipt address information
  var nationalcode = Res.nationalcode;//delivery address country code
 }
);

Little Faith Store
Jump micro-Credit Product page interface

 Wx.openproductspecificview {
productId: ',//Product ID
viewtype: '//0. Default value, general merchandise details page 1. Sweep the Merchandise Details page 2. Shop Details page
});

Micro-credit card voucher
Adjust the coupon list for the store and get the user selection list

 Wx.choosecard ({
 shopid: ',//Store ID
 cardtype: ',//card voucher type
 cardid: ',//card voucher ID
 timestamp:0,//Card voucher signature Timestamp 
   
    NONCESTR: ',//Card voucher signature random string
 cardsign: ',//card voucher signature, see Appendix 6
 success:function (res) {
  var cardlist= res.cardlist; User selected card list information
 }
});

   

Bulk Add Card interface

 Wx.addcard ({
cardlist: [{
cardid: ',
cardext: '
}],//card list to be added
 success:function (res) { C18/>var cardlist = res.cardlist; Added card list information
 }
});

To view the card coupon interface in a micro-credit card package

 Wx.opencard ({
cardlist: [{
cardid: ',
code: '
}]//need to open the card list
});

Micro-Credit Payment
Initiate a micro-letter payment Request

 Wx.choosewxpay ({
timestamp:0,//signature timestamp
noncestr: ',//payment signed random string
package: ',//order Details extension string, see Appendix 5
Paysign: ',//payment signature, as detailed in Appendix 5
});

Appendix 1-JSSDK using permission Signature algorithm
Jsapi_ticket
Before you can generate a signature, you must understand that Jsapi_ticket,jsapi_ticket is a temporary ticket that the public number is used to invoke the micro-letter JS interface. Normally, the Jsapi_ticket is valid for 7,200 seconds and is obtained by Access_token. Because the number of API calls to get Jsapi_ticket is very limited, frequent refresh Jsapi_ticket can cause API calls to be limited and affect its own business, and developers must cache Jsapi_ticket in their own services globally.
1. Refer to the following documents to obtain Access_token (valid 7,200 seconds, the developer must be in their own service global cache Access_token):. /12/4b08382e91217687730a2dfc71e9218c.html
2. Use the first step to obtain the Access_token using the HTTP GET method request obtains the Jsapi_ticket (valid 7,200 seconds, the developer must in own service global cache Jsapi_ticket):https:// Api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=access_token&type=jsapi
successfully returned the following JSON:

 {
"Errcode": 0,
"errmsg": "OK",
"Ticket": " Bxldikrxvbtpdhsm05e5u5suoxnkd8-41zo3mhkoyn5ofkwitdggnr2fwj0m9e8nyzwkvzvdvtaugwvsdshfka ",
" expires_in ": 7200
}

After you get the Jsapi_ticket, you can generate the signature of the JSSDK permission verification.

Signature Algorithm
The signature generation rules are as follows: The fields participating in the signature include NONCESTR (random string), valid jsapi_ticket, timestamp (timestamp), url (the URL of the current Web page, not including # and its back section). Use the format of the URL key value pair (that is, key1=value1&key2=value2 ...) for all pending signature parameters, sorted by the ASCII code of the field name from small to large (dictionary order). ) stitching into string string1. Note here that all parameter names are lowercase characters. For string1 as SHA1 encryption, the field name and field values are all in the original value, and no URL escapes are used.

namely SIGNATURE=SHA1 (string1). Example:
NONCESTR=WM3WZYTPZ0WZCCNW
JSAPI_TICKET=SM4AOVDWFPE4DXKXGES8VMCPGGVI4C3VM0P37WVUCFVKVAY_90U5H9NBSLYY3-SL-HHTDFL2FZFY1AOCHKP7QG
timestamp=1414587457
url=http://mp.weixin.qq.com

Step 1. Use the format of the URL key value pair (that is, key1=value1&key2=value2 ...) for all pending signature parameters, sorted by the ASCII code of the field name from small to large (dictionary order). ) stitching into a string string1:
jsapi_ticket=sm4aovdwfpe4dxkxges8vmcpggvi4c3vm0p37wvucfvkvay_90u5h9nbslyy3-sl-hhtdfl2fzfy1aochkp7qg& Noncestr=wm3wzytpz0wzccnw&timestamp=1414587457&url=http://mp.weixin.qq.com

Step 2. SHA1 signature of string1 to get signature:
f4d90daf4b3bca3078ab155816175ba34c443a7b

Attention matters
1. Noncestr and timestamp for signatures must be the same as NONCESTR and timestamp in Wx.config.
2. The URL used for the signature must be the full URL of the calling JS interface page.
3. For security reasons, the developer must implement the logic of the signature on the server side.

Appendix 2-List of all JS interfaces
Onmenusharetimeline
Onmenushareappmessage
ONMENUSHAREQQ
Onmenushareweibo
Startrecord
Stoprecord
Onvoicerecordend
Playvoice
Pausevoice
Stopvoice
Onvoiceplayend
Uploadvoice
Downloadvoice
Chooseimage
Previewimage
Uploadimage
Downloadimage
Translatevoice
Getnetworktype
openlocation
getlocation
Hideoptionmenu
Showoptionmenu
Hidemenuitems
Showmenuitems
Hideallnonbasemenuitem
Showallnonbasemenuitem
CloseWindow
Scanqrcode
Choosewxpay
getlatestaddress
editaddress
Openproductspecificview
Addcard
Choosecard
Opencard

Appendix 3 -All button list &NBSP
Basic class
  report: "Menuitem:exposearticle"
• Adjust font: "Menuitem:setfont"
• Daytime mode: "Menuitem:daymode"
• Night mode: "Menuitem:nightmode"
• Refresh: "Menuitem:refresh"
• View public number (added): "MenuItem: Profile
• View public number (not added): "Menuitem:addcontact"  
Propagate class
  send to friend: "MenuItem:share:appMessage"
· Share to the circle of Friends: "MenuItem:share:timeline"
• Share to QQ: "MENUITEM:SHARE:QQ"
• Share to Weibo: "MenuItem:share:weiboApp"
• Favorites: " Menuitem:favorite "
• Share to FB:" MenuItem:share:facebook " 
Protection class
  debugging:" Menuitem:jsdebug "
• Edit label:" Menuitem:edittag "
• Delete:" Menuitem:delete "
• Copy link:" Menuitem:copyurl "
• Original page:" Menuitem:originpage "
• Reading mode: "Menuitem:readmode"
• Open in QQ browser: "Menuitem:openwithqqbrowser"
• Open in Safari: "Menuitem:openwithsafari"
• Mail : "MenuItem:share:email"
• Some special public numbers: "MenuItem:share:brand"

Appendix 4-Location and address signature generation algorithm
The Addrsign generation rules are the same as the signature generation rules for JSSDK permission validation (refer to Appendix 1), except that the participating signature parameters differ. The signature parameters participating in Addrsign are: appId, url (current Web page URL), timestamp, noncestr, Accesstoken (User authorization voucher, please refer to oauth2.0 protocol for obtaining).

Appendix 5-Payment Extension field and signature generation algorithm
Order Details (package) Extended string definition
When the merchant sets up the JS API, the merchant needs to determine the order details at this time and put the order details into the package by a certain way. After the JS API is invoked, the micro-letter will generate the pre-payment form via the package content. The following defines the list of required fields for package and the signature method. The interface needs to be aware that all incoming parameters are string types!

This article has been organized into the "JavaScript micro-Credit Development Skills Summary", welcome to learn to read.

For everyone to recommend now more attention than the micro-letter Program Tutorial: "Micro-letter Small Program Development tutorial" Small series for everyone carefully organized, hope like.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.