This article mainly introduces applets-logon, payment, and template messages. it has some reference value and can be understood if necessary. The public platform has quietly started beta testing of the mini-program (public account) function recently, attracting the attention of countless developers and common users. the ability to pay is introduced along with the release of the mini-program, with the following introduction:
Wx. login (OBJECT)
Call the interface to obtain the login credential (code) in exchange for the user's login status information, including the user's unique identity (openid) and the session key (session_key) of the current login ). The encryption and decryption of user data depends on the session key.
OBJECT parameter description:
Sample code:
// App. jsApp ({onLaunch: function () {wx. login ({success: function (res) {if (res. code) {// initiate a network request wx. request ({url: 'https: // test.com/onLogin', data: {code: res. code }})} else {console. log ('failed to get the user logon status! '+ Res. errMsg )}}});}})
This is an HTTP interface. the developer server uses the logon credential code to obtain session_key and openid. Session_key is the key to encrypt and sign user data. For the sake of 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:
Response parameters:
Return description:
// Normally returned JSON data packet {"openid": "OPENID", "session_key": "SESSIONKEY" "expires_in ": 2592000} // return the JSON data packet when the error occurs (the Code in the example is invalid) {"errcode": 40029, "errmsg": "invalid code "}
Logon mode maintenance
After obtaining the user logon status through wx. login (), you must maintain the logon status. Developers should note that they should not directly use session_key, openid, and other fields as user IDs or session IDs, but should dispatch a session logon state by themselves (refer to the logon time sequence diagram ). For Sessions generated by developers, ensure their security and do not set a long expiration time. After the session is distributed to the applet client, it can be stored in storage for subsequent communication.
Logon sequence diagram
Wx. checkSession (OBJECT)
Check whether the logon status has expired
Sample code:
Wx. checkSession ({success: function () {// The logon status has not expired}, fail: function () {// The logon status has expired wx. login ()}})
User data signature verification and encryption/decryption
Data signature verification
To ensure the security of user data returned by open interfaces, plaintext data is signed. Developers can perform signature verification on data packets based on business needs to ensure data integrity.
The signature verification algorithm involves the user's session_key. the user's session_key is obtained through the wx. login logon process, and the corresponding relationship with the application's own logon state is maintained on its own.
When you call an interface (for example, wx. getUserInfo) to obtain data, the interface returns rawData and signature at the same time, where signature = sha1 (rawData + session_key)
The developer sends signature and rawData to the developer server for verification. The server uses the user's corresponding session_key to calculate the signature signature2 using the same algorithm, and compares signature with signature2 to verify data integrity.
For example, wx. getUserInfo data verification:
RawData returned by the interface:
{ "nickName": "Band", "gender": 1, "language": "zh_CN", "city": "Guangzhou", "province": "Guangdong", "country": "CN", "avatarUrl": "http://wx.qlogo.cn/mmopen/vi_32/1vZvI39NWFQ9XM4LtQpFrQJ1xlgZxx3w7bQxKARol6503Iuswjjn6nIGBiaycAjAtpujxyzYsrztuuICqIM5ibXQ/0"}
User session-key:
HyVFkGl5F5OQWJZZaNzBBg =
Therefore, the string used for 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 result obtained by using sha1 is
75e81ceda165f4ffa64f4068af58c64b8f54b88c
Encryption and decryption algorithms
If the interface involves sensitive data (such as the openId and unionId in wx. getUserInfo), the plaintext content of the interface does not contain the sensitive data. To obtain sensitive data, developers must perform symmetric decryption on the encrypted data returned by the interface. The decryption algorithm is as follows:
Symmetric decryption algorithm is used for AES-128-CBC, data is filled with PKCS #7.
The target ciphertext for symmetric decryption is Base64_Decode (encryptedData ),
Symmetric decryption key aeskey = Base64_Decode (session_key), aeskey is 16 bytes
The initial vector iv of the symmetric decryption algorithm is returned in the data interface.
The official website provides sample code in multiple programming languages (click to download ). The names of interfaces in each language are the same. For more information about the call method, see the example.
Note: previously provided encryption data (encryptData) and the corresponding encryption algorithm will be discarded. developers should not rely on the old logic any more.
User information:
### Wx. getUserInfo (OBJECT)
To obtain user information, you must first call the wx. login interface.
OBJECT parameter description:
Success return parameters:
Sample code:
Wx. getUserInfo ({success: function (res) {var userInfo = res. userInfo var nickName = userInfo. nickName var avatarUrl = userInfo. avatarUrl var gender = userInfo. gender // gender 0: unknown, 1: male, 2: female var province = userInfo. province var city = userInfo. city var country = userInfo. country }})
EncryptedData is decrypted in the following json structure. for details, refer to 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 a developer has multiple mobile apps, website apps, and public accounts (including applets), you can use unionid to differentiate the uniqueness of users, as long as it is a mobile application, website application, or public account (including a small program) under the same open platform account, the user's unionid is unique. In other words, unionid is the same for different applications on the same open platform.
Procedure for binding a applet to an open platform
Prerequisites: The open platform account must have completed the developer qualification certification.
Developer qualification certification process:
Log on to the open platform (open.weixin.qq.com)-account Center-developer qualification certification
Payment:
Wx. requestPayment (OBJECT)
Initiate payment.
Object parameter description:
Sample code:
wx.requestPayment({ 'timeStamp': '', 'nonceStr': '', 'package': '', 'signType': 'MD5', 'paySign': '', 'success':function(res){ }, 'fail':function(res){ }})
Based on the notification channel, we provide developers with the ability to efficiently reach the user's template message, in order to achieve a closed loop of services and provide a better experience.
Template push Location: service notification
Template issuance condition: triggered when the user interacts with the page in the system. for details, see the delivery condition description.
Template jump capability: Click to view details and only jump to the pages of the account that issue the template
Instructions for Use
Get template id
Log on to the https://mp.weixin.qq.com to get the template, if there is no suitable template, you can apply to add a new template, can be used after the review, see template review instructions
Page
When report-submit is set to true, you can declare that you want to send a template message. click the button to submit a form to obtain formId, which is used to send a template message. Alternatively, you can obtain the prepay_id to send the template message when the user completes the payment.
Send template messages by calling the interface (for details, refer to the interface description)
Interface Description
1. get access_token
Access_token is the globally unique interface call credential. the developer must use access_token when calling each interface. please save it properly. The storage of access_token must contain at least 512 characters. The validity period of access_token is currently 2 hours. you need to refresh it regularly. repeated access_token acquisition will invalidate the last access_token.
Description of how to use and generate access_token for API calls on the public platform:
To keep the appsecrect Confidential, a third party needs an access_token to obtain and refresh the central control server. The access_token used by other business logic servers comes from the central control server and should not be refreshed separately. Otherwise, the access_token overwrites the service;
Currently, the validity period of access_token is expressed by the returned expires_in. Currently, the value is within 7200 seconds. The central control server needs to refresh the new access_token in advance based on the validity period. During the refresh process, the central control server still outputs the old access_token. at this time, the background of the public platform will ensure that the new and old access_token are available within a short period of time, this ensures the smooth transition of third-party services;
The validity period of access_token may be adjusted in the future. Therefore, the central control server not only needs to actively refresh internally, but also needs to provide an interface for passively refresh access_token, in this way, the service server can trigger the refresh process of the access_token when the access_token has timed out during API calls.
Developers can use AppID and AppSecret to call this interface to obtain access_token. AppID and AppSecret can be obtained by logging on to the official website of the public platform-settings-development settings (it must have been bound to a developer and the account is not abnormal ). After the AppSecret is generated, save it by yourself, because the AppSecret is reset every time it is generated and viewed on the public platform. Note that https is required to call all interfaces. If a third party does not use the central control server, but selects each business logic point to refresh the access_token, a conflict may occur, resulting in service instability.
Interface address:
Https://api.weixin.qq.com/cgi-bin/token? Grant_type = client_credential & appid = APPID & secret = APPSECRET
HTTP request method:
GET
Parameter description:
Response parameters:
Normally, the following JSON data packet is returned to the developer:
{"access_token": "ACCESS_TOKEN", "expires_in": 7200}
2. send template messages
Interface address: (replace ACCESS_TOKEN with the obtained access_token)
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 ", "color": "#173177"}, "keyword3": {"value": "Sheraton Yuehai Hotel", "color": "#173177"}, "keyword4 ": {"value": "208 Tianhe Road, Tianhe district, Guangzhou", "color": "#173177" }}, "emphasis_keyword": "keyword1.DATA "}
Return code description:
After the template message interface is called, a JSON data packet is returned.
Example of a JSON data packet returned normally:
{ "errcode": 0, "errmsg": "ok",}
An error code is returned, which is described as follows:
Effect:
Note: in the internal test phase, after the template message is sent, you can only see the simple notification issued by the "public account security assistant" on the client. If you receive this prompt, it indicates that the template message function has been successfully debugged. After the function is officially launched, it will be displayed as an effect.
Delivery condition description
1. payment
When a user has completed the payment in the applet, the developer can push a limited number of template messages to the user within 7 days (one payment can be issued, multiple payments are issued independently without affecting each other)
2. submit a form
If a user has submitted a form in a applet and the form declaration is to send a template message, the developer must provide services to the user, allows developers to push a limited number of template messages to users within 7 days (one single submission form can be issued, and multiple submissions can be issued independently without affecting each other)
Review description
1. title
1.1 The title cannot be the same
1.2 Title meaning cannot be overly similar
1.3 The title must end with a "reminder" or "notification"
1.4 The Title cannot contain special characters, personalized words, and other content without industry versatility
1.5 The title must reflect specific service scenarios
1.6 The Title cannot contain marketing-related content, including but not limited:
Notification of marketing preferences such as consumption discounts, shopping rebates, product updates, coupons, coupons, red packets, membership cards, points, and activities
2. Keywords
2.1 The keywords cannot be the same under the same title.
2.2 Keywords under the same title cannot be overly similar.
2.3 keywords cannot contain special symbols, personalized words, and other content without industry universality
2.4 The keyword content example must match the keyword
2.5 The keyword cannot be too broad or restrictive. for example, the keyword "content" is too broad and cannot be approved.
Violation description
In addition to operating specifications, the following rules cannot be violated, including but not limited:
Users cannot be maliciously induced to trigger the operation to deliver templates to users.
Malicious harassment is not allowed, and templates that cause harassment to users are issued
Malicious marketing is not allowed to issue marketing target templates
It is not allowed to inform the user of service-related content triggered in the applet through the service number delivery template.
Penalty description
You are given a graded penalty based on violations. the general penalty rules are as follows:
For the first violation, delete the violation template as a warning,
The second violation. The API is banned for 7 days,
For the third violation, the API is banned for 30 days,
For the fourth violation, the interface is permanently banned.
Inform the penalty result and cause in the form of an Insite email
The above is all the content of this article. I hope it will help you learn and support PHP.
More applets-for details about login, payment, and template messages, please follow the PHP Chinese website!