The WeChat public platform has quietly begun internal testing of the WeChat mini program (WeChat public account) function recently, attracting the attention of countless developers and ordinary users. The ability to pay on WeChat was launched with the release of the mini program, and its features are introduced as follows:
wx.login(OBJECT)
Call the interface to obtain the login credentials (code) and then exchange the user login status information, including the user's unique identifier (openid) and the session key (session_key) for this login. Encryption and decryption of user data communication depends on the session key.
OBJECT parameter description:
Sample code:
//app.js App({ onLaunch: function() { wx.login({ success: function(res) { if (res.code) { //发起网络请求 wx.request({ url: 'https://test.com/onLogin', data: { code: res.code } }) } else { console.log('获取用户登录态失败!' + res.errMsg) } } }); } })
This is an HTTP interface, and the developer server uses the login credentials code to obtain the session_key and openid. where session_key is the key used 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:
Return parameters:
Return instructions:
//正常返回的JSON数据包 { "openid": "OPENID", "session_key": "SESSIONKEY" "expires_in": 2592000 } //错误时返回JSON数据包(示例为Code无效) { "errcode": 40029, "errmsg": "invalid code" }
Login status maintenance
After obtaining the user login status through wx.login(), the login status needs to be maintained. Developers should be careful not to directly use fields such as session_key and openid as user identifiers or session identifiers. Instead, they should dispatch a session login state by themselves (please refer to the login sequence diagram). For sessions generated by developers themselves, their security should be ensured and long expiration times should not be set. After the session is dispatched to the mini program client, it can be stored in storage for subsequent communication.
Login sequence diagram
wx.checkSession(OBJECT)
Check whether the login status has expired
Sample code:
wx.checkSession({ success: function(){ //登录态未过期 }, fail: function(){ //登录态过期 wx.login() } })
Signature verification and encryption and decryption of user data
Data signature verification
In order to ensure the security of user data returned by the open interface, WeChat will sign the plain text data. 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, which is obtained through the wx.login login process and maintains the corresponding relationship with the application's own login state.
When obtaining data by calling an interface (such as wx.getUserInfo), the interface will return 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 and signature2 to verify the integrity of the data.
Such as data verification of wx.getUserInfo:
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’s session-key:
HyVFkGl5F5OQWJZZaNzBBg==
So, 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 using sha1 is
75e81ceda165f4ffa64f4068af58c64b8f54b88c
Encrypted data decryption algorithm
If the interface involves sensitive data (such as openId and unionId in wx.getUserInfo), the plain text content of the interface will not contain these sensitive data. If developers need to obtain sensitive data, they need to symmetrically 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 padded 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
对称解密算法初始向量 iv 会在数据接口中返回。
微信官方提供了多种编程语言的示例代码(点击下载)。每种语言类型的接口名字均一致。调用方式可以参照示例。
注:此前提供的加密数据(encryptData)以及对应的加密算法将被弃用,请开发者不要再依赖旧逻辑。
用户信息:
### wx.getUserInfo(OBJECT)
获取用户信息,需要先调用 wx.login 接口。
OBJECT参数说明:
success返回参数说明:
示例代码:
wx.getUserInfo({ success: function(res) { var userInfo = res.userInfo var nickName = userInfo.nickName var avatarUrl = userInfo.avatarUrl var gender = userInfo.gender //性别 0:未知、1:男、2:女 var province = userInfo.province var city = userInfo.city var country = userInfo.country } })
encryptedData 解密后为以下 json 结构,详见加密数据解密算法
{ "appId": "APPID", "openId": "OPENID", "nickName": "NICKNAME", "gender": 1, "city": "CITY", "province": "PROVINCE", "country": "COUNTRY", "avatarUrl": "AVATARURL", "unionId": "UNIONID" }
UnionID机制说明:
如果开发者拥有多个移动应用、网站应用、和公众帐号(包括小程序),可通过unionid来区分用户的唯一性,因为只要是同一个微信开放平台帐号下的移动应用、网站应用和公众帐号(包括小程序),用户的unionid是唯一的。换句话说,同一用户,对同一个微信开放平台下的不同应用,unionid是相同的。
微信开放平台绑定小程序流程
前提:微信开放平台帐号必须已完成开发者资质认证
开发者资质认证流程:
登录微信开放平台(open.weixin.qq.com) – 帐号中心 – 开发者资质认证
微信支付:
wx.requestPayment(OBJECT)
发起微信支付。
Object参数说明:
示例代码:
wx.requestPayment({ 'timeStamp': '', 'nonceStr': '', 'package': '', 'signType': 'MD5', 'paySign': '', 'success':function(res){ }, 'fail':function(res){ } })
基于微信的通知渠道,我们为开发者提供了可以高效触达用户的模板消息能力,以便实现服务的闭环并提供更佳的体验。
模板推送位置:服务通知
模板下发条件:用户本人在微信体系内与页面有交互行为后触发,详见下发条件说明
模板跳转能力:点击查看详情仅能跳转下发模板的该帐号的各个页面
使用说明
获取模板 id
登录https://mp.weixin.qq.com获取模板,如果没有合适的模板,可以申请添加新模板,审核通过后可使用,详见模板审核说明
页面的
组件,属性report-submit为true时,可以声明为需发模板消息,此时点击按钮提交表单可以获取formId,用于发送模板消息。或者当用户完成支付行为,可以获取prepay_id用于发送模板消息。调用接口下发模板消息(详见接口说明)
接口说明
1. 获取 access_token
access_token 是全局唯一接口调用凭据,开发者调用各接口时都需使用 access_token,请妥善保存。access_token 的存储至少要保留512个字符空间。access_token 的有效期目前为2个小时,需定时刷新,重复获取将导致上次获取的 access_token 失效。
公众平台的 API 调用所需的 access_token 的使用及生成方式说明:
为了保密 appsecrect,第三方需要一个 access_token 获取和刷新的中控服务器。而其他业务逻辑服务器所使用的 access_token 均来自于该中控服务器,不应该各自去刷新,否则会造成 access_token 覆盖而影响业务;
目前 access_token 的有效期通过返回的 expires_in 来传达,目前是7200秒之内的值。中控服务器需要根据这个有效时间提前去刷新新 access_token。在刷新过程中,中控服务器对外输出的依然是老 access_token,此时公众平台后台会保证在刷新短时间内,新老 access_token 都可用,这保证了第三方业务的平滑过渡;
access_token 的有效时间可能会在未来有调整,所以中控服务器不仅需要内部定时主动刷新,还需要提供被动刷新 access_token 的接口,这样便于业务服务器在 API 调用获知 access_token 已超时的情况下,可以触发 access_token 的刷新流程。
开发者可以使用 AppID 和 AppSecret 调用本接口来获取 access_token。AppID 和 AppSecret 可登录微信公众平台官网-设置-开发设置中获得(需要已经绑定成为开发者,且帐号没有异常状态)。AppSecret 生成后请自行保存,因为在公众平台每次生成查看都会导致 AppSecret 被重置。注意调用所有微信接口时均需使用 https 协议。如果第三方不使用中控服务器,而是选择各个业务逻辑点各自去刷新 access_token,那么就可能会产生冲突,导致服务不稳定。
接口地址:
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
HTTP请求方式:
GET
参数说明 :
返回参数说明:
正常情况下,微信会返回下述 JSON 数据包给开发者:
{"access_token": "ACCESS_TOKEN", "expires_in": 7200}
2. 发送模板消息
接口地址:(ACCESS_TOKEN 需换成上文获取到的 access_token)
https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=ACCESS_TOKEN
HTTP请求方式:
POST
POST参数说明:
示例:
{ "touser": "OPENID", "template_id": "TEMPLATE_ID", "page": "index", "form_id": "FORMID", "data": { "keyword1": { "value": "339208499", "color": "#173177" }, "keyword2": { "value": "2015年01月05日 12:30", "color": "#173177" }, "keyword3": { "value": "粤海喜来登酒店", "color": "#173177" } , "keyword4": { "value": "广州市天河区天河路208号", "color": "#173177" } }, "emphasis_keyword": "keyword1.DATA" }
返回码说明:
在调用模板消息接口后,会返回JSON数据包。
正常时的返回JSON数据包示例:
{ "errcode": 0, "errmsg": "ok", }
错误时会返回错误码信息,说明如下:
使用效果:
注意:内部测试阶段,模板消息下发后,在客户端仅能看到由“公众号安全助手”下发的简单通知。能收到该提示,即表明模板消息功能已经调试成功。待该功能正式上线后,将可以展示成上图效果。
下发条件说明
1、支付
当用户在小程序内完成过支付行为,可允许开发者向用户在7天内推送有限条数的模板消息(1次支付可下发1条,多次支付下发条数独立,互相不影响)
2、提交表单
当用户在小程序内发生过提交表单行为且该表单声明为要发模板消息的,开发者需要向用户提供服务时,可允许开发者向用户在7天内推送有限条数的模板消息(1次提交表单可下发1条,多次提交下发条数独立,相互不影响)
审核说明
1.标题
1.1标题不能存在相同
1.2标题意思不能存在过度相似
1.3标题必须以“提醒”或“通知”结尾
1.4标题不能带特殊符号、个性化字词等没有行业通用性的内容
1.5标题必须能体现具体服务场景
1.6标题不能涉及营销相关内容,包括不限于:
消费优惠类、购物返利类、商品更新类、优惠券类、代金券类、红包类、会员卡类、积分类、活动类等营销倾向通知
2.关键词
2.1同一标题下,关键词不能存在相同
2.2同一标题下,关键词不能存在过度相似
2.3 Keywords cannot contain special symbols, personalized words, or other content that is not industry-wide.
2.4 Keyword content examples must match the keywords
2.5 Keywords cannot be too broad and need to be restrictive. For example: "content" is too broad and cannot be approved.
Violation description
In addition to not violating operating regulations, the following rules may not be violated, including but not limited to:
It is not allowed to maliciously induce users to perform trigger operations in order to achieve the purpose of delivering templates to users.
Malicious harassment is not allowed, and templates that cause harassment to users are not allowed.
Malicious marketing is not allowed and marketing purpose templates are issued.
It is not allowed to issue templates through service accounts to inform users of service-related content triggered within the mini program.
Punishment description
Corresponding gradient penalties will be given according to the violation. The general penalty rules are as follows:
For the first violation, the offending template will be deleted as a warning.
For the second violation, the interface will be banned for 7 days.
For the third violation, the interface will be banned for 30 days.
For the fourth violation, the interface will be permanently banned.
The punishment results and reasons will be notified in the form of an in-site letter.
The above is the entire content of this article. I hope it will be helpful to everyone's learning. I also hope that everyone will support the PHP Chinese website.
For more WeChat mini programs - detailed explanations of WeChat login, WeChat payment, and template messages related articles, please pay attention to the PHP Chinese website!