微信小程序卡券领取 java开发

当时在写微信小程序卡券的时候,当时微信后台都没有接触过,对接微信后台也没学过。关于微信小程序卡券的开发教程也看过不少,看的都是一脸懵逼。关键是开发微信卡券的过程,其中的代码并不难,一开始用php写了一个版本,但是之前的后台是java所以又写了一个java版本。

关于卡券对于商家的营销还是很重要的,主要为大家讲解一下微信小程序卡券的准备工作,以及主要流程和当时开发时遇到的错误示范。

关于准备工作,关键还是要先看官方给的开发文档。
https://mp.weixin.qq.com/cgi-bin/announce?action=getannouncement&key=1490190158&version=1&lang=zh_CN&platform=2
是关于小程序&卡券打通的官网文档教程。

下面主要还是将关于小程序里面的卡券领取过程

准备材料:
微信公众号:APPID 和 appSecret 微信开通卡券功能,手动在后台创建一个卡券获取card_id

官网返回码说明:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1433747234

第一步:获取token(很多步骤都需要)
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
将里面的APPID和APPSECRET替换为自己公众号准备的材料里面。
这里写图片描述
返回的是这种JSON格式的,一定要填写正确的,返回码错误的话看上面官网返回码说明文档。
下面是获取token的部分代码

String url = ACCECC_TOKEN_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET);
            JSONObject jsonObject = doGetStr(url);  //调用get方法
            if (jsonObject != null) 
token = jsonObject.getString("access_token")); //获取得到的token 

第二步:获取 api_ticket
卡券 api_ticket 是用于调用卡券相关接口的临时票据
用第一步拿到的token值,采用get请求方式获得卡券api_ticket地址接口
https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=wx_card
部分代码,和上面获取token的代码类似

String url = API_TICKET.replace("ACCESS_TOKEN",Open_Id.getToken());
            JSONObject jsonObject = doGetStr(url);
            if(jsonObject != null)
                  api_ticket = jsonObject.getString("ticket"));

这个是官方的开发文档https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115在附录4:卡券扩展字段及签名生成算法

第三步:加密算法signature
首先获取时间戳timestamp:注意用System.currentTimeMillis()获取的是毫秒,加密要求的是秒,要除以1000才可以

/**
     * 获取时间戳
     * @return
     */
    public String timestamp(){
        String time = String.valueOf(System.currentTimeMillis()/1000);   //获取一个时间戳 转换为String类型
        return time;
    }

随机字符串nonce_str:自己随便写一个随机字符串就可以了

/**
 * Created by hubo on 2017/11/7
 * 随机字符串
 */
public class Accessnonce_str {
    private final static String string = "0123456789";
    final private static char[] chars =  string.toCharArray();

    public String nonce_str(){
        String nonce = new String();
        for(int i=0; i<10; i++){
            int rannum = (int)(Math.random()*1000) % (chars.length);
            nonce += chars[rannum];
        }
        return nonce;
    }
}

将获取的api_ticket,timestamp,nonce_str,card_id(这个我是在微信后台手动创建获取的)
加密算法主要是字典序,然后将这些参数字符串拼接成为一个字符串,之后进行Sha1加密
加密算法代码

/**
 * Created by hubo on 2017/11/7
 * 加密signature
 */
public class WeixinSignature {
    private  String api_ticket;
    private  String timestamp;
    private  String card_id;
    private  String nonce_str;

    public WeixinSignature(String api_ticket, String timestamp, String card_id, String nonce_str){
        this.api_ticket = api_ticket;
        this.timestamp = timestamp;
        this.card_id = card_id;
        this.nonce_str = nonce_str;
    }

    /**
     * 加密参数
     * @return
     */
    public String sign(){

        String[] str = {api_ticket,timestamp,card_id,nonce_str};
        Arrays.sort(str);
        String string = new String();
        for(int i=0; i<4; i++){
            string += str[i];
        }
        String signature = null;    //加密结果
        signature = CheckUtil.getSha1(string);  //Sha1加密
        return signature;
    }

}

下面是Sha1加密算法代码

 //Sha1加密
    public static String getSha1(String str){
        if(str==null||str.length()==0){
            return null;
        }
        char hexDigits[] = {'0','1','2','3','4','5','6','7','8','9',
                'a','b','c','d','e','f'};
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
            mdTemp.update(str.getBytes("UTF-8"));

            byte[] md = mdTemp.digest();
            int j = md.length;
            char buf[] = new char[j*2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(buf);
        } catch (Exception e) {
            // TODO: handle exception
            return null;
        }
    }

加密signature官方提供的检验地址
https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=cardsign
自己看加密的结果和官网给返回的结果比较
第四步:微信小程序领取卡券
代码部分

wx.request({
      url: 'http://访问返回数据的地址',
      data: {
        card: card
      },
      method: 'GET', 
      success: function (res) {
        var res = res.data;
        console.log(res);
        var card = res.card_id;
        var timestamp = res.timestamp;
        var signature = res.signature;
        var nonceStr = res.nonce_str;
        wx.addCard({
          cardList: [
            {
              cardId: card,
              cardExt: '{"code": "", "openid": "", "timestamp": ' + timestamp + ', "signature":"' + signature + '","nonce_str": ' + nonceStr+'}'
            }
          ],  
}

访问返回数据就是返回card_id,timestamp,signature,nonceStr我获取的是这四个
这里获得的timestamp,nonceStr这两个必须是signature加密里面的两个,不然领取卡券的时候会出现签名错误

还有一个非常注意的地方:在获取cardExt 需进行 JSON 序列化为字符串传入
不要直接传入对象,这个地方卡了我一星期,因为之前签名加密的数据步骤什么的都对,但是一领取就是签名错误这个原因,之后看了很多遍开发文档,关键是java后段返回的数据是对象类型,一定要转换为字符串类型,不然领取的时候还是签名错误。

java后段返回参数代码:返回的是JSON对象

WeixinSignature signature = new WeixinSignature(Open_Id.getApiTicket(),Open_Id.getTime(), Card_Id.getCardid(),nonce);   //获取signature

        PrintWriter out = resp.getWriter(); //返回网页请求的数据
        JSONObject jsonObject = new JSONObject();   //返回JSON格式数据
        //jsonObject.put("apitick",Open_Id.getApiTicket());

//        System.out.println("时间:"+Open_Id.getTime());
//        System.out.println("随机串:"+nonce);
//        System.out.println("加密字符:"+signature.sign());   
//        System.out.println("cardid:"+Card_Id.getCardid());

        jsonObject.put("timestamp", Open_Id.getTime());
        jsonObject.put("nonce_str", nonce);
        jsonObject.put("signature",signature.sign());
        jsonObject.put("card_id",Card_Id.getCardid());
        out.print(jsonObject.toString());

这里写图片描述
这个是我获取的四个参数,获取参数后转换为字符串类型,不然会出现签名错误。

获取这四个参数后调用微信小程序的卡券领取
https://mp.weixin.qq.com/debug/wxadoc/dev/api/card.html
我主要是通过这四个步骤做好的微信小程序卡券领取功能,其余的功能就需要扩展开发了。

自己也是小白,开发过程也没多复杂的,主要是领取卡券的过程步骤还有一些细节我都写下了,由于写完之后又添加了许多功能,代码也就传了一部分。
有可能还有什么没写上去的,可以加qq交流下。

  • 0
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
对于微信卡券开发,需要先进行微信公众号小程序的授权认证,获取到相关的 API 信息。然后根据不同的卡券类型,进行相应的开发。 下面以微信小程序为例,介绍一下卡券开发流程: 1. 配置小程序的接口权限,包括卡券相关的接口权限。 2. 创建卡券,可以在微信公众平台或小程序后台进行创建。创建时需要填写卡券的基本信息,包括卡券的类型、商户信息等。 3. 使用 API 接口进行卡券的管理,包括卡券的发放、核销等。需要对 API 进行相应的封装,方便开发人员进行调用。 4. 在小程序中展示卡券,可以通过卡券列表、卡券详情页等方式进行展示。 这里提供一个简单的 PHP 微信卡券 demo,供参考: ```php <?php // 设置公众号或小程序的 appid 和 appsecret $appid = 'your_appid'; $appsecret = 'your_appsecret'; // 获取 access_token $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret; $response = file_get_contents($url); $result = json_decode($response, true); $access_token = $result['access_token']; // 创建卡券 $url = 'https://api.weixin.qq.com/card/create?access_token='.$access_token; $data = array( 'card' => array( 'card_type' => 'GROUPON', 'groupon' => array( 'base_info' => array( 'logo_url' => 'http://mmbiz.qpic.cn/mmbiz_jpg/xxxxxxxx/0', 'brand_name' => '测试商户', 'code_type' => 'CODE_TYPE_QRCODE', 'title' => '测试优惠券', 'sub_title' => '测试商户', 'color' => 'Color010', 'notice' => '测试优惠券', 'service_phone' => '18888888888', 'description' => '测试优惠券', 'date_info' => array( 'type' => 'DATE_TYPE_FIX_TIME_RANGE', 'begin_timestamp' => strtotime('2021-01-01'), 'end_timestamp' => strtotime('2021-12-31') ), 'sku' => array( 'quantity' => 1000000 ), 'get_limit' => 1, 'use_custom_code' => false, 'bind_openid' => false, 'can_share' => true, 'can_give_friend' => true, 'location_id_list' => array(), 'url_name_type' => 'URL_NAME_TYPE_RESERVATION', 'custom_url' => 'http://www.xxx.com', 'source' => '测试商户' ), 'deal_detail' => '测试详情' ) ) ); $data = json_encode($data, JSON_UNESCAPED_UNICODE); $response = http_post_data($url, $data); $result = json_decode($response, true); $card_id = $result['card_id']; // 发放卡券 $url = 'https://api.weixin.qq.com/card/groupon/add?access_token='.$access_token; $data = array( 'card_id' => $card_id, 'quantity' => 10 ); $data = json_encode($data, JSON_UNESCAPED_UNICODE); $response = http_post_data($url, $data); $result = json_decode($response, true); echo $result['errcode'] == 0 ? '发放成功' : '发放失败'; // 核销卡券 $url = 'https://api.weixin.qq.com/card/code/consume?access_token='.$access_token; $data = array( 'code' => 'xxxxxxxx', 'card_id' => $card_id ); $data = json_encode($data, JSON_UNESCAPED_UNICODE); $response = http_post_data($url, $data); $result = json_decode($response, true); echo $result['errcode'] == 0 ? '核销成功' : '核销失败'; // 查询卡券详情 $url = 'https://api.weixin.qq.com/card/get?access_token='.$access_token; $data = array( 'card_id' => $card_id ); $data = json_encode($data, JSON_UNESCAPED_UNICODE); $response = http_post_data($url, $data); $result = json_decode($response, true); print_r($result); function http_post_data($url, $data_string) { $ch = curl_init(); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($data_string) )); $response = curl_exec($ch); curl_close($ch); return $response; } ?> ``` 需要注意的是,此 demo 中的 access_token 获取方式不够安全,建议使用官方 SDK 或者其他安全的方式进行获取。另外,卡券的创建、发放、核销等操作需要根据实际情况进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值