Home > WeChat Applet > Mini Program Development > Detailed explanation of examples of mini program development login, payment and template messages

Detailed explanation of examples of mini program development login, payment and template messages

Y2J
Release: 2017-05-11 13:29:28
Original
2577 people have browsed it

This article mainly introduces the WeChat applet-WeChat login, WeChat payment, and template messages. It has certain reference value and you can learn more if you need it.

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. , the introduction is 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:

success Return 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)
    }
   }
  });
 }
})
Copy after login

code In exchange for session_key

This is an HTTP interface. The developer server uses the login credentials code to obtain session_key and openid. where session_key is the key used to encrypt and sign user data. For the security of your own application, session_key should not be uploaded and entered over the network.

Interface address:

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

Request parameters

Return parameter:

Return description:

//正常返回的JSON数据包
{
   "openid": "OPENID",
   "session_key": "SESSIONKEY"
   "expires_in": 2592000
}
//错误时返回JSON数据包(示例为Code无效)
{
  "errcode": 40029,
  "errmsg": "invalid code"
}
Copy after login

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()
 }
})
Copy after 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. The user's session_key is obtained through the wx.login login process, and the corresponding relationship with the application's own login state is maintained by itself.

  • 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.

For example, 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"
}
Copy after login

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==
Copy after login

The result obtained by 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 of the interface The content will not contain this 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 filled with PKCS#7.

  • The target ciphertext of symmetric decryption is Base64_Decode(encryptedData),

  • The symmetric decryption key aeskey = Base64_Decode(session_key), aeskey is 16 Bytes

  • The symmetric decryption algorithm initial vector iv will be returned in the data interface.

微信官方提供了多种编程语言的示例代码(点击下载)。每种语言类型的接口名字均一致。调用方式可以参照示例。

注:此前提供的加密数据(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
 }
})
Copy after login

encryptedData 解密后为以下 json 结构,详见加密数据解密算法

{
  "appId": "APPID",
  "openId": "OPENID",
  "nickName": "NICKNAME",
  "gender": 1,
  "city": "CITY",
  "province": "PROVINCE",
  "country": "COUNTRY",
  "avatarUrl": "AVATARURL",
  "unionId": "UNIONID"
}
Copy after login

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){
  }
})
Copy after login

基于微信的通知渠道,我们为开发者提供了可以高效触达用户的模板消息能力,以便实现服务的闭环并提供更佳的体验。

模板推送位置:服务通知

模板下发条件:用户本人在微信体系内与页面有交互行为后触发,详见下发条件说明

模板跳转能力:点击查看详情仅能跳转下发模板的该帐号的各个页面

使用说明

获取模板 id

登录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,那么就可能会产生冲突,导致服务不稳定。

接口地址:

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}
Copy after login

2. 发送模板消息

接口地址:(ACCESS_TOKEN 需换成上文获取到的 access_token)

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" 
}
Copy after login

返回码说明:

在调用模板消息接口后,会返回JSON数据包。

正常时的返回JSON数据包示例:

{
 "errcode": 0,
 "errmsg": "ok",
}
Copy after login

错误时会返回错误码信息,说明如下:

使用效果:

 注意:内部测试阶段,模板消息下发后,在客户端仅能看到由“公众号安全助手”下发的简单通知。能收到该提示,即表明模板消息功能已经调试成功。待该功能正式上线后,将可以展示成上图效果。

 下发条件说明

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关键词不能带特殊符号、个性化字词等没有行业通用性的内容

2.4关键词内容示例必须与关键词对应匹配

2.5关键词不能太过宽泛,需要具有限制性,例如:“内容”这个就太宽泛,不能审核通过

违规说明

除不能违反运营规范外,还不能违反以下规则,包括但不限于:

  1. 不允许恶意诱导用户进行触发操作,以达到可向用户下发模板目的

  2. 不允许恶意骚扰,下发对用户造成骚扰的模板

  3. 不允许恶意营销,下发营销目的模板

  4. 不允许通过服务号下发模板来告知用户在小程序内触发的服务相关内容

处罚说明

根据违规情况给予相应梯度的处罚,一般处罚规则如下:

  1. 第一次违规,删除违规模板以示警告,

  2. 第二次违规,封禁接口7天,

  3. For the third violation, the interface will be banned for 30 days.

  4. For the fourth violation, the interface will be permanently banned

The punishment results and reasons will be informed in the form of an in-site letter

[Related recommendations]

1. Complete source code of WeChat mini program

2. WeChat mini program demo: imitating NetEase Cloud Music

The above is the detailed content of Detailed explanation of examples of mini program development login, payment and template messages. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template