微信卡券开发具体的步骤,不会踩坑

首先要获取到公众号的appid和密钥,要去微信的公众平台测试号管理查看

先能获取到token,下面就是获取token的方法,大概是这么实现的,代码中ACCESS_TOKEN_URL 是我定义在工具类里的静态变量

    /**
     * ACCESS_TOKEN_URL  全局接口调用凭证获取路径
     */
    public static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-                    
    bin/token?" +"grant_type=client_credential&appid=APPID&secret=APPSECRET"
                    .replace("APPID", WeChatConstant.APPID)
                    .replace("APPSECRET", WeChatConstant.APPSECRET);

    /**
     * 获取 AccessToken
     *
     * @return the access token
     */
 public WeChatAccessToken fetchAccessToken() {
        String accessTokenStr = stringRedisTemplate.opsForValue().get(REDIS_WE_CHAT_ACCESS_TOKEN_KEY);
        logger.info("redis中获取微信accesstoken:" + accessTokenStr);
        if (StringUtils.isBlank(accessTokenStr)) {
            return getAccessToken();
        } else {
            WeChatAccessToken weChatAccessToken = JsonUtil.parse(accessTokenStr, WeChatAccessToken.class);
            return weChatAccessToken;
        }
    }

    /**
     * 请求获取 AccessToken
     *
     * @return the access token
     */
    public WeChatAccessToken getAccessToken() {

        String result = HttpRequest.get(WeChatConstant.ACCESS_TOKEN_URL)
                //超时,毫秒
                .timeout(20000)
                .execute()
                .body();

        JSONObject jsonObject = JSONUtil.parseObj(result);

        if (StringUtils.isNotBlank(jsonObject.getStr("access_token"))) {
            WeChatAccessToken weChatAccessToken = WeChatAccessToken.getInstance().setAccess_token(jsonObject.getStr("access_token"))
                    .setExpires_in(jsonObject.getLong("expires_in"));
            stringRedisTemplate.opsForValue().set(REDIS_WE_CHAT_ACCESS_TOKEN_KEY, JsonUtil.serialize(weChatAccessToken), REDIS_WE_CHAT_ACCESS_TOKEN_EXPIRE, TimeUnit.MINUTES);
            logger.info("请求获取微信accesstoken:" + result);
            return weChatAccessToken;
        } else {
            throw new GlobalException(ExceptionEnum.WE_CHAT_ACCESS_TOKEN_ERROR);
        }
    }

这是我们需要调用的controller,必填的参数用apiImpactcitParam备注好了,可以去微信的开发文档看下,每个优惠券必填的参数。

 /**
     * 创建卡卷controller
     */
    @PostMapping("create")
    @ApiOperation(value = "创建卡包优惠卷", notes = "创建卡包优惠卷API", response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "logoUrl", value = "卡券的商户logo", paramType = "body", required = true, dataType = "String"),
            @ApiImplicitParam(name = "codeType", value = "码型: \"CODE_TYPE_TEXT\"文 本 ;" +
                    " \"CODE_TYPE_BARCODE\"一维码" +
                    " \"CODE_TYPE_QRCODE\"二维码 " +
                    "\"CODE_TYPE_ONLY_QRCODE\",二维码无code显示; " +
                    "\"CODE_TYPE_ONLY_BARCODE\"," +
                    "一维码无code显示;CODE_TYPE_NONE, 不显示code和条形码类型",
                    paramType = "body", required = true, dataType = "String"),
            @ApiImplicitParam(name = "brandName", value = "商户名字,字数上限为12个汉字", paramType = "body", required = true, dataType = "String"),
            @ApiImplicitParam(name = "title", value = "卡券名,字数上限为9个汉字。(建议涵盖卡券属性、服务及金额)", paramType = "body", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "notice", value = "卡券使用提醒,字数上限为16个汉字(请出示二维码)", paramType = "body", required = true, dataType = "String"),
            @ApiImplicitParam(name = "description", value = "卡券使用说明,字数上限为1024个汉字(不可与其他优惠同享\\n如需团购券发票,请在消费时向商户提出\\n店内均可使用,仅限堂食)", paramType = "body", required = true, dataType = "String"),
            @ApiImplicitParam(name = "sku", value = "商品信息数量{ 'sku': { 'quantity ': 500000 }", paramType = "body", required = true, dataType = "String"),
            @ApiImplicitParam(name = "dateInfo", value = "  //使用日期,有效期的信息('type': 'DATE_TYPE_FIX_TIME_RANGE', 'begin_timestamp': 1397577600 ,'end_timestamp': 1472724261)", paramType = "body", required = true, dataType = "String"),
            @ApiImplicitParam(name = "leastCost", value = "代金券专用,表示起用金额(单位为分),如果无起用门槛则填0", paramType = "body", required = true, dataType = "int"),
            @ApiImplicitParam(name = "reduceCost", value = "代金券专用,表示减免金额。(单位为分)", paramType = "body", required = true, dataType = "int"),
            @ApiImplicitParam(name = "discount", value = "折扣券专用,表示打折额度(百分比)。填30就是七折", paramType = "body", required = true, dataType = "int"),
            @ApiImplicitParam(name = "defaultDetail", value = "优惠券专用,填写优惠详情", paramType = "body", required = true, dataType = "String"),
            @ApiImplicitParam(name = "useCustomCode", value = "是否开启自定义code", paramType = "body", required = true, dataType = "boolean")
    })
    public Result createCouponToWeChatServer(@RequestBody @ApiIgnore WeChatBaseInfo weChatBaseInfo,@RequestParam("coupon") String coupon){
        //要封装得数据
        HashMap<String,Object> map = Maps.newHashMap();
        //代卷的不同类型
        HashMap<String,Object> couponMap = Maps.newHashMap();
        //json对象必填map
        HashMap<String,Object> couponContext = Maps.newHashMap();
        //创建base_info实例对象
        BaseInfoDto baseInfo = new BaseInfoDto(weChatBaseInfo.getLogoUrl(),weChatBaseInfo.getCodeType(),weChatBaseInfo.getBrandName(),weChatBaseInfo.getTitle()
        ,weChatBaseInfo.getNotice(),weChatBaseInfo.getDescription(),weChatBaseInfo.getSku(),weChatBaseInfo.getDateInfo(),weChatBaseInfo.isUseCustomCode());
        couponContext.put("base_info",baseInfo);
        //当创建类型为代金卷时额外要添加的参数对象
        switch (coupon) {
            case "cash":
                couponContext.put("least_cost",weChatBaseInfo.getLeastCost());
                couponContext.put("reduce_cost",weChatBaseInfo.getReduceCost());
                break;
            case "discount":
                couponContext.put("discount",weChatBaseInfo.getDiscount());
                break;
            case "groupon":
                couponContext.put("deal_detail",weChatBaseInfo.getDefaultDetail());
                break;
            default:
                break;
        }
        couponMap.put("card_type",coupon.toUpperCase());
        couponMap.put(coupon,couponContext);
        map.put("card",couponMap);
        String object = JsonUtil.serialize(map);
        //调用tx接口
        String result =  WeChatHttpUtil.post(JsonUtil.serialize(map)
                ,WeChatConstant.CREATE_COUPON_URL.replace("ACCESS_TOKEN", weChatAccessTokenUtil.fetchAccessToken().getAccess_token()));
        return  Result.success(result);
    }

我是为了更快一点去开发,所以把逻辑写在controller里面,规范的话,需要写在对应的service里面。然后请求腾讯接口的post方法为:

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;

/**
 * @author BruceLin
 * @data 16:52
 */
public class WeChatHttpUtil {

    public static final String post(String body,String url) {
        String result = HttpRequest.post(url)
                .header(Header.CONTENT_TYPE, "application/json")
                .body(body)
                .execute()
                .body();
        return result;
    }
}

大概这样子能返回微信的回响数据

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值