This article is the 16th article in the series of “Analysis of wechat Payment”. It mainly explains how to use the card coupon function of wechat public platform, how to use HTML5 to show users receiving coupons on the web page and the relationship between wechat card coupon and merchant platform voucher.


Analysis of wechat payment series has been updated 16 yo ~, have not seen the friends can have a look at oh.

Brief analysis of wechat Pay: How to open the functions of top-up free products and guide to interface upgrade

Analysis of wechat payment: merchant platform voucher or immediate discount opening, designated user voucher issuance, query, etc

Brief analysis of wechat payment: merchant platform to open cash red envelope, designated user distribution, red envelope record query

Analysis of wechat Pay: Payment acceptance Examples and acceptance guidelines

Wechat Pay: How to use sandbox environment test

The first few articles mainly introduce how to use vouchers and full discount and other product functions in the wechat merchant platform. Many friends say that [wechat public platform] also has a card coupon function, so what is the difference between them? How does this card function work? This article will give you an explanation.

The difference between the two

First of all, let’s explain the difference between merchant platform and wechat platform’s respective coupons. If anyone has tried, they should know that they are not universal, not universal, not universal!!

As for the key here, the logo is not universal? After the wechat card coupon function is opened, the corresponding coupon information of wechat card coupon will also appear on the merchant platform. Although there is no function of coupon issuance, it is only displayed. But if we use the interface to issue coupons, there will be failure of coupon issuance and the error of XXX type coupon cannot be supported, which will be embarrassing at this time.

Not over, because the platform is different, so wechat card coupons and payment coupons to send, receive the way (interface) is also different, including the user jump to the page is not the same, this also please pay attention to.

So, we need to treat these two kinds of bonds as two different kinds of bonds.

Public platform card coupon function opened

Log in the public platform https://mp.weixin.qq.com, click [function-Add function plug-in] on the left, enter the page of plug-in library, enter [card coupon function], and open the card coupon function.

Application conditions: wechat payment must be enabled !!!!

Function description: Card coupon function, is provided to merchants or third parties a set of coupons, management and management of members of the tool, can create card coupons in the public platform or through the interface, a variety of channels to the user, the user needs to cancel the card coupon, check the data after checking.

Main abilities:

● Coupons shared by friends — they can be quickly spread through social networks. If one person gets the coupons, both his or her friends can see and use them. View Video Introduction

● Ordinary coupon — traditional coupon electronic version, after receiving only I can see available, support a variety of types: discount coupons, vouchers, vouchers, group purchase vouchers, coupons.

● Membership card — support discounts, points and other gameplay, and provide member management, data reports and other rich tools, easy for merchants to operate members efficiently.

● wechat pay – without wechat pay development, and membership card, voucher, discount voucher through, for you to accumulate user consumption data, for business reference

● Value storage function — Membership card merchants do not need to apply, but can display the balance of members on the home page of wechat membership card by using the function of “Balance Display” directly through API interface. Merchants with pre-paid card qualifications can apply for the function of “value storage”. After successful application, they can set this entrance through THE API interface to help members recharge their membership cards through wechat Pay.

● Third-party proxy mode — after being authorized by merchants, merchants can quickly access and use the card coupon function on behalf of their sub-merchants, supporting the implementation of the function through public platforms or API interfaces.

Official development document address:

https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141229
Copy the code

Here it is known that partners have opened the card coupon function, how to manually create coupons can be operated on the public platform, it is very simple, here will not say, this article mainly talks about how to use the interface to create card coupons, users receive, query card coupon details.

Wechat card voucher guidelines

Official Document Address:

https://mp.weixin.qq.com/cgi-bin/readtemplate?t=cardticket/faq_tmpl&type=info&token=&lang=zh_CN# 0
Copy the code

The following are the application channels and application conditions corresponding to the opening guidelines of the card coupon function:

If you have a need, you can read through the official document above. After reading it, you will have an understanding of wechat card vouchers. Almost all the basic business can be done with a clear idea of it.

If you are a developer, just look at the following wechat card coupon interface document. After all, we are more concerned about the information related to the interface. The official document is as follows:

https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141229
Copy the code

Download card Coupon Information Pack:

https://mp.weixin.qq.com/zh_CN/htmledition/comm_htmledition/res/cardticket/wx_card_document.zip?token=&lang=zh_CN
Copy the code

According to the official document, there are seven steps required. The following are the specific steps:

  1. Get access_token
  2. Upload the card logo
  3. Create card voucher
  4. Create a QR code
  5. Display qr code
  6. Example Set the test whitelist
  7. Cancel after verification card stock

The official document mainly uses the sandbox test account for testing and verification. The application for the interface test number can be obtained through the following link:

https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
Copy the code

Let’s examine the interface step by step.

Get access_token

The page address: http://mp.weixin.qq.com/debug/

Interface type: Basic supported

Interface list: Obtain the access_token interface

Note: Enter the developer’s APPID and Secret

Click Check to return the access_token, which is valid for two hours after which it must be reacquired

https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140183 interface address: get access_token interface

Access to the global access_token interface of wechat will not be discussed here, can see this article partners should have written long ago, ha ha ha.

Upload the card logo

The page address: http://mp.weixin.qq.com/debug/

Interface type: Basic supported

Interface list: Interface for uploading picture materials

Access_token: Access_token obtained in the previous step

Buffer: The image you selected

Click Check the question to obtain the picture URL, which is required in the parameters of creating the card in the next step

The interface address: https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1451025056 upload pictures interface

If you do not want to use this interface to upload the logo, you can upload the logo when manually creating coupons on the public platform. After uploading, you can right-click on the logo picture and copy the picture path. The same is true for those who don’t want to adjust the interface.

Create card voucher

The page address: http://mp.weixin.qq.com/debug/

Interface type: Card interface

Interface list: Create card interface

Access_token: The access_token obtained in the first step

Create card interface address:

https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1451025056
Copy the code

The following is an example call interface:

https://api.weixin.qq.com/card/create?access_token=xxx
Copy the code

JSON example:

{
    "card": {
        "card_type": "CASH"."cash": {
            "base_info": {
                "logo_url": "https://mmbiz.qlogo.cn/mmbiz_png/E5Q3G4ku9nf7UiafOetcAPLyfia7kdWWWauHukNN7ZXnggtZcTzEPGa8IUDiaLIv14EkNdPvmbCFyHibh0G8ti a7Eibw/0?wx_fmt=png"// Here is the address for uploading the logo"pay_info": {
                    "swipe_card": {
                        "use_mid_list": [
                            "xxx"// store id],"create_mid": "xxx", // Merchant number"is_swipe_card": true}},"brand_name": "Test voucher"."code_type": "CODE_TYPE_NONE"."title": "111"."color": "Color090"// Theme color"service_phone": "18888888888"."description": "Can not be shared with other offers. If you need the coupon invoice, please present it to the merchant when consuming."."date_info": {
                    "type": "DATE_TYPE_FIX_TIME_RANGE"."begin_timestamp": 1536768000, // Start time"end_timestamp": 1536940800},"can_share": false."center_title": "Immediate use"."center_app_brand_user_name": "gh_7195ea80d2e6@app"."center_app_brand_pass": "pages/index/index"."can_give_friend": false."sku": {
                    "quantity": 500000}."get_limit": 30."custom_url_name": "Immediate use"."custom_url": "http://www.qq.com"."custom_url_sub_title": "6 Chinese Character Tips"."promotion_url_name": "More benefits"."promotion_url": "http://www.qq.com"
            }, 
            "advanced_info": {
                "use_condition": {
                    "accept_category": "Shoe"."reject_category": Adidas."can_use_with_other_discount": true."least_cost": "51"
                }, 
                "abstract": {
                    "abstract": "Wechat restaurant launches a variety of seasonal dishes, looking forward to your visit."."icon_url_list": [
                        "http://mmbiz.qpic.cn/mmbiz/p98FjXy8LacgHxp3sJ3vn97bGLz0ib0Sfz1bjiaoOYA027iasqSG0sjpiby4vce3AtaPu6cIhBHkt6IjlkY9YnDsfw/0 "]},"text_image_list": [{"image_url": "http://mmbiz.qpic.cn/mmbiz/p98FjXy8LacgHxp3sJ3vn97bGLz0ib0Sfz1bjiaoOYA027iasqSG0sjpiby4vce3AtaPu6cIhBHkt6IjlkY9YnDsfw/0 "."text": "This dish is exquisitely selected ingredients and prepared in a unique way to maximize the taste buds of the diners."
                    }, 
                    {
                        "image_url": "http://mmbiz.qpic.cn/mmbiz/p98FjXy8LacgHxp3sJ3vn97bGLz0ib0Sfz1bjiaoOYA027iasqSG0sj piby4vce3AtaPu6cIhBHkt6IjlkY9YnDsfw/0"."text": "This dish caters to all tastes and is nutritious for all ages."}]."time_limit": [{"type": "MONDAY"."begin_hour": 0."end_hour": 10, 
                        "begin_minute": 10, 
                        "end_minute": 59}, {"type": "HOLIDAY"}]."business_service": [
                    "BIZ_SERVICE_FREE_WIFI"."BIZ_SERVICE_WITH_PET"."BIZ_SERVICE_FREE_PARK"."BIZ_SERVICE_DELIVER"]},"reduce_cost": 5}}}Copy the code

Using the above interface and parameters, you can create a coupon message. The JSON example can also be used as the official one. Here are a few issues to focus on:

  1. Use_mid_list Merchant number for the merchant
  2. Color The color can be selected according to the document
  3. Begin_timestamp and end_timestamp are very important. First, the end time must be longer than the start time and must be larger than a certain limit. The test span should be longer than one day. Note that the time format must be a 10-digit value, for example, 1536768000. Other formats will generate an error.
  4. The value for time_limit is specified in the document
  5. Set sku and get_limit as required
  6. Logo_url uses the official wechat logo picture address

Note: date_info is a Unix timestamp, pay attention to the begin_timestamp is less than the current time, end_TIMESTAMP is changed to a time later than today, so that the card test can be successfully cancelled later

Create a QR code

Page address: mp.weixin.qq.com/debug

Interface type: Card interface

Interface list: Create a QR code ticket interface

Access_token: The access_token obtained in the first step

Interface document address:

https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1451025062
Copy the code

Examples of interface calls:

https://api.weixin.qq.com/card/qrcode/create?access_token=TOKEN
Copy the code

Json parameters:

{
    "action_name":"QR_CARD"."expire_seconds": 1800,"action_info": {"card": {"card_id":"pFS7Fjg8kV1IdDz01r4SQwMkuCKc"."code":"198374613512"."openid":"oFS7Fjl0WsZ9AMZqrI80nbIq8xrA"."is_unique_code":false."outer_str":"12b"}}}Copy the code

Display qr code

Click the link in the field show_qrCODE_URL in the return of the previous step to display the QR code for card coupon collection. Open wechat and scan, and then get the card coupon. If it shows that the card coupon does not pass the audit, the next step is to set up the test whitelist. If the card coupon can be obtained, the sixth step is ignored.

Example Set the test whitelist

Document Address:

https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1451025062
Copy the code

Cancel after verification card stock

Document Address:

https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1451025239
Copy the code

Note: Only approved and valid cards are supported

HTML5 Web Coupon (JS-SDK)

I think the above way of issuing coupons through TWO-DIMENSIONAL code has been clearly explained in the official document, and the interface is relatively simple, so I won’t repeat it here. What I mainly need to talk about is the HTML5 web coupon (JS-SDK) here. The official document link is as follows:

https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1451025062
Copy the code

To put it simply, the user clicks the button in zour system H5, and the wechat official coupon receiving interface pops up. The official page is provided by wechat, so we don’t need to develop it. We just need to pay attention to how to call the official method.

The official explanation is as follows: The addCard interface provided by wechat is called by the front-end webpage of merchants for adding one or more card coupons to the user card package

The interface address is as follows (search addCard on the following page) :

https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115
Copy the code

Above is the interface to add card coupons. We focus on these parameters:

  1. CardId: card coupon ID, or batch ID in case of merchant platform
  2. CardExt: Extended parameter of the card coupon. The JSON serialization is passed in as a string
  3. CardExt > openID: Specifies the openID of the receiver. Only the user can claim it. Cards with the bind_openID field true must be filled in. Cards with the bind_openID field false cannot be filled in.
  4. CardExt >code: indicates the code obtained by the user. Only the card with custom code mode must be filled in
  5. CardExt >nonce_str: random string, passed in by the developer Settings to enhance security (if left blank may be requested by replay). A random string of up to 32 characters. It is recommended to use upper and lower case letters and numbers. Nonce_str for different add requests must be generated dynamically.
  6. CardExt >signature: indicates that the merchant signs the parameters in the interface list according to the specified mode. The signature mode is SHA1. For details about the signature scheme, see Card signature
  7. CardExt >timestamp: timestamp,UTC+8, in seconds
  8. CardExt >outer_str: channel parameter, which identifies the channel value.
  9. CardExt > fixed_BEGINtimestamp: The actual time when the card was collected on a third-party system, in the eastern 8th zone timestamp (UTC+8, accurate to seconds). When the validity class of the card coupon is DATE_TYPE_FIX_TERM, it identifies the actual effective time of the card coupon, and is used to solve the problem that the starting time in the merchant system is not synchronized with the time of receiving the wechat card coupon.

The combined cardList is obtained based on the voucher batch ID

To get the cardList interface, you need to first get the Access_token, then the API_ticket, and finally assemble the desired collection. Here is the sample code.

The combined cardList can be obtained according to the voucher batch ID:

/** * cardList ** @param cardId card package ID * @return cardList
 * @author yclimb
 * @date 2018/9/21
 */
public JSONArray getCardList(String cardId) {
    if (StringUtils.isBlank(cardId)) {
        returnnull; } try {// Get access_Token String accessToken = this.getAccesstoken (WXConstants.WX_MINI_PROGRAM_CODE); String timestamp = String.valueOf(WXPayUtil.getCurrentTimestamp()); String nonce_str = WXPayUtil.generateNonceStr(); // Extension parameters for the card ticket. CardExt = new JSONObject(); //cardExt.put("code"."");
        //cardExt.put("openid"."");
        //cardExt.put("fixed_begintimestamp"."");
        //cardExt.put("outer_str"."");
        cardExt.put("timestamp", timestamp);
        cardExt.put("nonce_str", nonce_str); /** * 1. Sort the values of api_ticket, timestamp, card_id, code, openID, and nonce_str lexicographically. * 2. Concatenate all parameter strings into a string for SHA1 encryption to obtain signature. * 3. The timestamp and nonce fields in signature must be consistent with the timestamp and nonce_str fields in card_ext. */ Map<String, String> map = new HashMap<>(8); //map.put("code"."");
        //map.put("openid"."");
        map.put("api_ticket", this.getWxCardApiTicket(accessToken));
        map.put("timestamp", timestamp);
        map.put("card_id", cardId);
        map.put("nonce_str", nonce_str);
        cardExt.put("signature", WXPayUtil.SHA1(WXPayUtil.dictionaryOrder(map, 2))); JSONObject cardInfo = new JSONObject(); cardInfo.put("cardId", cardId);
        cardInfo.put("cardExt", cardExt.toJSONString()); JSONArray cardList = new JSONArray(1); cardList.add(cardInfo);return cardList;
    } catch (Exception e) {
        WXPayUtil.getLogger().error(e.getMessage(), e);
    }
    return null;
}
Copy the code

Access to wechat global accessToken:

/** * Get wechat global accessToken ** @param code * @returnAccessToken */ public String getAccessToken(String code) {String key = WXConstants.WECHAT_ACCESSTOKEN + code; String accessToken = (String) redisTemplate.opsForValue().get(key);if(accessToken ! = null) {returnaccessToken; } / / through interfaces access_token JSONObject JSONObject = restTemplate. GetForObject (MessageFormat. The format (WXURL BASE_ACCESS_TOKEN, WXPayConstants.APP_ID, WXPayConstants.SECRET), JSONObject.class); String token = (String) jsonObject.get("access_token");
    if(StringUtils. IsNotBlank (token)) {/ / storage redis redisTemplate. OpsForValue (). The set (key, token, 7000, TimeUnit. SECONDS);return token;
    } else {
        log.error("Error obtaining wechat accessToken, wechat return message: [{}]", jsonObject.toString());
    }
    return null;
}
Copy the code

Get the API of the card api_ticket:

/ * * * for card voucher api_ticket API * request path: https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token= {0} &type=wx_card
 *
 * @param access_token token
 * @return api_ticket json obj
 * @author yclimb
 * @date 2018/9/21
 */
public String getWxCardApiTicket(String access_token) {
    if (StringUtils.isBlank(access_token)) {
        returnnull; } try { // redis key String redisKey = RedisKeyUtil.keyBuilder(RedisKeyEnum.IMALL_WXCARD_APITICKET, access_token); / / get from redis cache Object obj = redisTemplate. OpsForValue (). The get (redisKey);if(obj ! = null) {returnobj.toString(); } / / access card voucher api_ticket String api_ticket = restTemplate. GetForObject (WXURL. BASE_API_TICKET, String class, access_token); WXPayUtil.getLogger().info("getWxCardApiTicket:api_ticket:{}", api_ticket);
        if (StringUtils.isBlank(api_ticket)) {
            return null;
        }
        JSONObject jsonObject = JSON.parseObject(api_ticket);
        if (0 != jsonObject.getIntValue("errcode")) {
            returnnull; String ticket = jsonObject.getString("ticket");
        redisTemplate.opsForValue().set(redisKey, ticket, jsonObject.getIntValue("expires_in"), TimeUnit.SECONDS);

        return ticket;
    } catch (Exception e) {
        WXPayUtil.getLogger().error(e.getMessage(), e);
    }
    return null;
}
Copy the code

The above code can obtain the cardList. Replace this parameter with the official method of wechat to evoke the page of getting coupons. It should be noted that the voucher collection methods of public platform and merchant platform are different. Here is an example of public platform. If a partner wants to use merchant platform to issue coupons for users, it will not be successful.

Check out card details

Developers can call this interface to query for creation information, review status, and inventory for a card_id.

Interface call:

The HTTP request method: POST URL:https://api.weixin.qq.com/card/get?access_token=TOKEN parameters: card_id, ID card vouchersCopy the code

Interface document (enter the link to query and view the details of the card ticket can be quickly located) :

https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1451025272
Copy the code

The official introduction of this interface has been very detailed, here is not detailed, you can refer to the official documentation.

conclusion

Above is wechat public platform – card ticket function related explanation and source, partners must pay attention to look at the official document oh, the specific source can see the author’s Github, in the face of each method has a detailed note.

If you have a problem that you can’t solve, you can follow the author’s wechat official account and join a discussion group to ask questions and solve them with your friends

Notice: In the next article, we will talk about another way to distribute rewards.

If you want to see the friend of the source in advance, can first take a look at my lot, address is as follows: https://github.com/YClimb/wxpay-sdk/blob/master/README.md

Follow the author’s wechat official account, click on the discussion group below, scan the code to join the wechat Pay discussion group with your friends

To this article is over, pay attention to the public account to view more push!!