Micro-Letter Applet-detailed micro-letter landing, micro-credit payment, template message _javascript skills

Source: Internet
Author: User
Tags error code openid sha1

Micro-trust public platform has quietly begun to beta-micro-credit program (micro-letter public number) function, attracted countless developers and ordinary users concerned about the ability to pay the micro-letter, with the release of small programs, with the introduction of the following:

Wx.login (OBJECT)

The calling interface acquires login credentials (code) in exchange for user logon state information, including the user's unique identifier (OpenID) and the session key (Session_key) for this login. The encryption and decryption of user data relies on session key completion.

Object parameter Description:

Success Return Parameter Description:

Sample code:

App.js
App ({
 onlaunch:function () {
  wx.login ({
   success:function (res) {
    if (res.code) {
     // Initiating network request
     wx.request ({
      URL: ' https://test.com/onLogin ',
      data: {
       code:res.code
      }}
     )
    else {
     console.log (' Get user login state failed! ' + Res.errmsg}}}}
)

Code in exchange for Session_key

This is an HTTP interface where the developer server uses the login voucher code to get Session_key and OpenID. Where Session_key is the key that encrypts the user data. For its own application security, Session_key should not be transmitted over the network.

Interface Address:

Https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type= Authorization_code

Request Parameters:

Return parameters:

Return Description:

Normal returned JSON packet
{
   "OpenID": "OpenID",
   "Session_key": "SessionKey"
   "expires_in": 2592000
}
Error returns JSON packet (example is code invalid)
{
  "Errcode": 40029,
  "errmsg": "Invalid Code"
}

Login State Maintenance

After Wx.login () gets to the user login state, the login state needs to be maintained. Developers should pay attention should not directly to the Session_key, OpenID and other fields as the user's identity or the identity of the session, but should distribute a session login state (please refer to the login sequence diagram). For the session that the developer generates, it should be secure and should not set a longer expiration time. After the session is distributed to the applet client, it can be stored in storage for subsequent communication use.

Login sequence Diagram

Wx.checksession (OBJECT)

Check if the landing state expires

Sample code:

Wx.checksession ({
 success:function () {
  //logon state not expired
 },
 fail:function () {
  //logon state expired
  Wx.login ()
 }
})

Signature verification and decryption of user data

Data Signature Checksum

To ensure that the open interface returns the security of the user's data, the micro-letter signs the plaintext data. The developer can verify the data package according to the business needs, and ensure the integrity of the data.

    • The signature verification algorithm involves the user's Session_key, obtains the user Session_key through the wx.login login process, and maintains the corresponding relation with the application own login state.
    • When fetching data by calling an interface (such as Wx.getuserinfo), the interface returns both RawData, signature, where signature = SHA1 (RawData + session_key)
    • Developers will send signature, rawdata to the developer server for validation. The server uses the same algorithm to compute the signature signature2 using the user's corresponding Session_key, and can verify the integrality of the data compared to signature and signature2.

Data validation such as Wx.getuserinfo:

RawData the interface returns:

{"
 nickname": "Band", "
 Gender": 1,
 "language": "ZH_CN",
 "City": "Guangzhou",
 "province": " Guangdong ",
 " Country ":" CN ",
 " Avatarurl ":" http://wx.qlogo.cn/mmopen/vi_32/ 1vzvi39nwfq9xm4ltqpfrqj1xlgzxx3w7bqxkarol6503iuswjjn6nigbiaycajatpujxyzysrztuuicqim5ibxq/0 "
}

User's Session-key:

hyvfkgl5f5oqwjzzanzbbg==

Therefore, the string used for the signature is:

{"
 nickname": "Band", "
 Gender": 1,
 "language": "ZH_CN",
 "City": "Guangzhou",
 "province": " Guangdong ",
 " Country ":" CN ",
 " Avatarurl ":" http://wx.qlogo.cn/mmopen/vi_32/ 1vzvi39nwfq9xm4ltqpfrqj1xlgzxx3w7bqxkarol6503iuswjjn6nigbiaycajatpujxyzysrztuuicqim5ibxq/0 "
} hyvfkgl5f5oqwjzzanzbbg==

The results obtained using SHA1 are

75e81ceda165f4ffa64f4068af58c64b8f54b88c

Encryption Data Decryption algorithm

Interfaces if they involve sensitive data (such as OpenId and Unionid in Wx.getuserinfo), the plaintext content of the interface will not contain these sensitive data. If developers need to obtain sensitive data, they need to symmetric decrypt the encrypted data (EncryptedData) returned by the interface. The decryption algorithm is as follows:

    • The algorithm used for symmetric decryption is AES-128-CBC, and the data is filled with pkcs#7.
    • The target ciphertext of symmetric decryption is Base64_decode (EncryptedData),
    • Symmetric decryption secret key Aeskey = Base64_decode (Session_key), Aeskey is 16 bytes
    • The symmetric decryption algorithm initial Vector IV is returned in the data interface.

Micro-Credit officials provide sample code for a variety of programming languages (click to download). The interface names for each language type are the same. The calling method can refer to the example.

Note: Previously provided encryption data (ENCRYPTDATA) and corresponding encryption algorithms will be discarded, so developers can no longer rely on the old logic.

User information:

### Wx.getuserinfo (OBJECT)

To get user information, you need to call the Wx.login interface first.

Object parameter Description:

Success Return Parameter Description:

Sample code:

Wx.getuserinfo ({
 success:function (res) {
  var userInfo = Res.userinfo
  var nickname = Userinfo.nickname
  var avatarurl = Userinfo.avatarurl
  var gender = userinfo.gender//Sex 0: Unknown, 1: Male, 2: female 
  var province = userinfo.pr Ovince
  var city = userinfo.city
  var country = userinfo.country
 }
)

EncryptedData decrypted after the following JSON structure, as detailed in the encryption data decryption algorithm

{"
  appId": "AppId", "
  OpenID": "OpenID",
  "nickname": "nickname",
  "gender": 1,
  "City": "City ",
  " province ":" Province ",
  " country ":" Country ",
  " Avatarurl ":" Avatarurl ",
  " Unionid ":" Unionid "
}

Unionid mechanism Description:

If developers have multiple mobile applications, Web applications, and public accounts (including small programs), can be unionid to differentiate the uniqueness of users, because as long as the same micro-trust Open platform account for mobile applications, Web applications and public accounts (including small programs), the user's Unionid is unique. In other words, the same user, Unionid is the same for different applications under the same micro-trust open platform.

Micro-letter Open Platform Binding applet process

Prerequisite: Micro-Credit open platform account must have completed the Developer qualification certification

Developer Qualification Certification process:

Login micro-Letter Open Platform (open.weixin.qq.com) – Account Center – Developer Qualification

Micro-Credit Payment:

Wx.requestpayment (OBJECT)
Initiate a micro-letter payment.

Object parameter Description:

Sample code:

Wx.requestpayment ({
  ' timeStamp ': ', '
  noncestr ': ', '
  package ': ',
  ' signtype ': ' MD5 ',
  ' Paysign ': ', '
  Success ': function (res) {
  },
  ' Fail ': function (res) {
  }
})

Based on the micro-credit notification channel, we provide developers with the ability to efficiently reach the user's template messaging capabilities to achieve a closed-loop service and provide a better experience.

Template Push location: Service notification

Template issued conditions: The user himself in the micro-trust system and the page has interactive behavior after the trigger, see the conditions of the note issued

Template Jump Ability: Click to view the details can only jump to the template of the account page

Instructions for use

Get template ID

Login https://mp.weixin.qq.com Get the template, if there is no suitable template, you can apply to add a new template, after the approval can be used, see template audit instructions

The <form/> component of the page, when the property Report-submit is true, you can declare that you want to send a template message, and then click the button to submit the form to get formid for sending the template message. Or when the user completes the payment behavior, you can get prepay_id to send the template message.

Call interface issued template message (see interface description)

Interface description

1. Get Access_token

Access_token is the global unique interface invocation credential, the developer calls each interface need to use Access_token, please save properly. Access_token storage should be reserved for at least 512 character spaces. The validity period of the Access_token is currently 2 hours and needs to be refreshed periodically, and repeated acquisition will cause the last acquired access_token to fail.

The use and generation of access_token required by API calls to the public platform are described as follows:

    • In order to keep the Appsecrect secret, a third party needs a access_token to obtain and refresh the control server. and other business logic server used by the Access_token are from the central control server, should not be each to refresh, otherwise it will cause access_token coverage and affect the business;
    • The current Access_token validity is communicated by the returned Expires_in, which is currently within 7,200 seconds. The central control server needs to refresh the new Access_token in advance according to this effective time. In the refresh process, the output of the central control server is still the old Access_token, at this time the public platform backstage will ensure that in a short period of refresh, new and old Access_token are available, which ensures a smooth transition of the third party business;
    • Access_token effective time may be adjusted in the future, so the central control server not only need internal timing active refresh, also need to provide a passive flush access_token interface, so that business Server in the API call to know that the Access_token has timed out, Can trigger the Access_token refresh process.

Developers can use AppID and Appsecret to invoke this interface to get Access_token. AppID and Appsecret can login to the micro-credit public platform website-settings-Development settings to obtain (need to have been bound to become a developer, and Account no abnormal status). Appsecret is saved after the build, because every time a view is generated on the public platform, the Appsecret is reset. Note The HTTPS protocol is required to invoke all micro-interfaces. If the third party does not use the central control server, but chooses each business logic point each to refresh the Access_token, then may have the conflict, causes the service to be unstable.

Interface Address:

Https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET

HTTP request Method:

Get

Parameter description:

Return parameter Description:

Normally, the micro-mail returns the following JSON packet to the developer:

{"Access_token": "Access_token", "expires_in": 7200}

2. Send Template message

Interface Address: (Access_token need to replace the Access_token obtained above)

Https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=ACCESS_TOKEN
HTTP request Method:

POST

Post parameter Description:

Example:

{"
 Touser": "OPENID", " 
 template_id": "template_id", 
 "page": "Index",     
 "form_id": "Formid",     
 " Data ": {" Keyword1 ": {"
     value ":" 339208499 ", 
     " color ":" #173177 "
   }, 
   " Keyword2 ": {"
     value ": "January 05, 2015 12:30", 
     "color": "#173177"
   }, 
   "Keyword3": {"
     value": "Sheraton Hotel Guangdong", 
     "Color": "# 173177 "
   }, 
   " Keyword4 ": {"
     value ":" Guangzhou Tianhe District Tianhe Road No. 208 ", 
     " color ":" #173177 "
   } 
 },
 " Emphasis_keyword ":" Keyword1. DATA " 
}

Return code Description:

After the template message interface is invoked, the JSON packet is returned.

Examples of returning JSON packets in normal time:

{
 "Errcode": 0,
 "errmsg": "OK",
}

Error code information is returned when errors are indicated as follows:

Use effect:

Note: The internal testing phase, the template message issued, in the client can only see by the "Public Security assistant" issued a simple notice. You receive this prompt, which indicates that the template message feature has been successfully debugged. After the function is officially online, it will be shown on the image.

Description of the condition of issuance

1. Payment

When the user completes the payment behavior in the small program, may allow the developer to push the limited number of templates message to the user within 7 days (1 payments can be issued 1, multiple payments issued by the number of independent, not affect each other)

2. Submit Form

When the user has committed a form line within the applet and the form is declared to be a template message, developers need to provide services to users, can allow developers to the user within 7 days to push the limited number of template messages (1 Submission form can be issued 1, multiple submissions issued number of independent, mutual not affect)

Audit instructions

1. Title

1.1 Titles cannot exist the same

1.2 title meaning cannot exist over similar

1.3 The title must end with a "reminder" or "notice"

1.4 Title can not be with special symbols, personalized words and so there is no industry commonality of content

1.5 title must be able to reflect the specific service scene

1.6 titles should not cover marketing related content, including not limited to:

Consumer preferences, shopping rebate categories, commodity updates, coupons, vouchers, red envelopes, membership cards, integration categories, activities such as marketing trends notice

2. Key words

2.1 Under the same heading, the keyword cannot exist the same

2.2 Under the same heading, the keyword cannot be overly similar

2.3 Keywords can not be with special symbols, personalized words and so there is no industry commonality content

2.4 Keyword content examples must match the keyword correspondence

2.5 keywords can not be too broad, need to be restrictive, such as: "Content" This is too broad to audit through

Description of violation

In addition to not violating the operating norms, the following rules cannot be violated, including but not limited to:

    1. Malicious user is not allowed to trigger the operation, in order to achieve the user can be issued template purposes
    2. Do not allow malicious harassment, issued to the user caused by the harassment template
    3. Do not allow malicious marketing, issued marketing purpose template
    4. The service number is not allowed to be issued by the template to inform the user in the small program triggered service-related content

Description of punishment

According to the violation of the corresponding gradient of punishment, the general penalty rules are as follows:

    1. First violation, delete the offending template as a warning,
    2. The second violation, the closure of the interface 7 days,
    3. Third violation, block interface 30 days,
    4. Fourth time violation, permanently blocked interface

The result and reason of punishment is informed in the form of station letter

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.