background

Tencent Digital Culture and Innovation Festival (TGC) will be held in Hainan in 2020. In order to let players know TGC’s culture and offline activities in advance, we launched the function of “booking tickets online in advance” one month before the event. In order to improve the experience of ticket reservation and better touch the users who have reached the ticket reservation in advance before the event starts, the team added the function of “adding tickets to wechat card coupons” on the basis of ticket reservation in mini program this year.

You must prepare the following account information in advance:

  • Wechat open platform account
  • Wechat mini program account
  • Wechat official account

Access to the process

1. Bind wechat mini program account and wechat public account under the same wechat open platform account

2. Open the wechat public account card coupon function

In mp.weixin.qq.com, log in the background of wechat official account, and click the left menu bar -> Functions -> Card ticket function (if there is no such function, please click Add Function plug-in to add).

Visit open.weixin.qq.com, log in to the wechat open platform, and bind the mini program account and wechat public account to the open platform account.

3. Generate the card template

In WeChat public, the background, the coupons and membership card types can be created manually, but for some special ticket you will need to use the API (event tickets, tickets and scenic spot tickets, etc.) in a way that is generated, the activities of the TGC is held in hainan offline, so we use the WeChat card for the scenic spot ticket types of securities, cannot be created directly in the background, So here is how to use the API to generate.

1. Obtain access_token

We need to use wechat’s Access_token to create card coupon API, and we need to pay special attention to the way of generating access_token for public account. We need to bind the server IP whitelist that generates access_token in the background of public account. Since we only need to create the card coupon once, Therefore, we can directly add the local IP as the whitelist IP.

2. Create a coupon

This step is to use the API for creating the card coupon, passing in the configuration of the card coupon. Related request parameters description View the documentation directly:

Developers.weixin.qq.com/doc/offiacc…

So it is important to note here, small program to add WeChat card voucher function allows us to add a user interface card voucher to jump back to the entrance of the small program, so in creating a card voucher, we can set some parameters, that card voucher service entrance can jump back to the small program, specific parameters, please go to view the related document, here is simple the use effect, for your reference.

Mpvideo. Qpic. Cn / 0 b787maacaa… Document links:

Developers.weixin.qq.com/doc/offiacc…

4. The server generates card coupons and delivers them(Applets cloud development)

After creating the card coupon, the next step is to receive the card coupon through some operations in the small program. Receiving card coupons in the small program requires the server to provide the verification parameters of card coupons, so in this step, we introduce how to generate the verification parameters of card coupons in the server.

1. Generate access_token

This step was mentioned in generating the card token template, but because it is frequently called by the client, we need to implement access_token acquisition at the code level. Since we are using the small program cloud, the default operation mechanism of the cloud function is non-fixed IP. We need to set the cloud function that obtains access_token as fixed IP in the Cloudbase console of Tencent Cloud.

After setting the fixed IP address successfully, configure the obtained IP address to the public number management background development -> Basic configuration -> IP whitelist:

After configuring the IP address whitelist, request access_token using AppID and AppSecret in the basic configuration:

let requestApiTicketResult = await request({
uri: 'https://api.weixin.qq.com/cgi-bin/ticket/getticket',
qs: {
access_token: accessToken,
type: 'wx_card'
}
})
Copy the code

2. Generate api_ticket

Generating api_ticket is similar to obtaining access_token. The access_token can be directly used to request the wechat interface. It should be noted that both access_token and API_ticket have a limit on the number of requests and an expiration time every day. So we need to cache these two values together.

let requestApiTicketResult = await request({
uri: 'https://api.weixin.qq.com/cgi-bin/ticket/getticket',
qs: {
access_token: accessToken,
type: 'wx_card'
}
})
Copy the code

3. Generate card ticket parameters

Card ticket parameters are mainly divided into the following parts: random string nonce_str, timestamp, user OpenID, card card number code, card card signature.

The generation of the card signature depends on other parameters.

Back-end code implementation:

Const cardExt = {cardId: 'cardId', // cardId code: code, api_ticket: apiTicket, nonce_str: generate(), timestamp: ParseInt ((date.now () / 1000), 10) + ''} return {cardId: 'cardId ', cardExt: json.stringify ({openid: ", // No openID specified get code: cardext. code, nonce_str: cardext. nonce_str, timestamp: cardext. timestamp, signature: Sha1 (valueToString(cardExt))})} // Generate random string const generate = (length = 16) => {const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' let noceStr = '', MaxPos = chars. Length while (length -) noceStr + = chars [Math. The random () * maxPos | 0] return noceStr} / / sorting const ValueToString = (obj) => object.values (obj).sort().join('') // const sha1 = (STR, const sha1) encoding = 'utf8') => crypto.createHash('sha1').update(str, encoding).digest('hex')Copy the code

Five, small program end to add card coupons

If the applets add card coupons, directly pass the parameters of the card coupons generated by the server into the applets add card coupons API:

wx.addCard({ cardList: [ { cardId: 'cardId', cardExt: 'cardExt'}], success (res) {console.log(res.cardlist) // cardcard add result}})Copy the code

Six, achieve the effect

Call wx. AddCard effect: mpvideo. Qpic. Cn / 0 bf2zqajcaa…

Call wx.openCard

Mpvideo. Qpic. Cn / 0 bf2keajuaa…

Vii. Cancellation of ticket card vouchers

Due to the particularity of the business (users can enter the event site through the qr code of the ticket card for many times), we did not cancel the card card. But card voucher itself of cancel after verification is also directly can be cancel after verification through interface WeChat card voucher cancel after verification, because this part is simple, there is no redundant expounded, can be done by looking at the document directly: developers.weixin.qq.com/doc/offiacc…

Product introduction

Cloud Development (TCB) is a cloud native integrated development environment and tool platform provided by Tencent Cloud. It provides developers with highly available, automatic and flexible expansion of back-end cloud services, including computing, storage, hosting and other serverless capabilities, which can be used for cloud integrated development of various end applications (small programs, Public account, Web application, Flutter client, etc.) to help developers build and manage back-end services and cloud resources in a unified manner, avoiding tedious server construction, operation and maintenance during application development. Developers can focus on the implementation of business logic, with lower development threshold and higher efficiency.

Open cloud development: console.cloud.tencent.com/tcb?tdl_anc…

The product documentation: cloud.tencent.com/product/tcb…

Technical documentation: Cloudbase.net? From =10004

Technical exchange plus Q group: 601134960

Latest news follow wechat official account [Tencent Yunyun Development]