java 微信卡券开发 --创建微信卡券

微信卡券官方api文档地址:微信卡券api

准备工作

一.获取access_token

注:access_token 获取接口 权限 需要在微信公众平台上配置服务器的ip,只支持外网

    public String getAccessToken() throws Exception{
        // 获取基础支持的access_token
        String resultUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ 你的appId +"&secret="+你的secret;
        HttpClient httpClient = HttpClients.createDefault();
        HttpGet get = new HttpGet(resultUrl);
        HttpResponse tokenResponse = httpClient.execute(get);
        String openIdJson = EntityUtils.toString(tokenResponse.getEntity());
        System.out.println(openIdJson);
        Map tokenMap = JSONObject.parseObject(openIdJson, Map.class);
        String access_token = (String) tokenMap.get("access_token");
        System.out.println("access_token:"+access_token);
        return access_token;
    }

一些类找不到引用以下jar包

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.30</version>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5.12</version>
        </dependency>



        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.12</version>
        </dependency>

二.上传卡券logo

 /**
     * 上传微信卡券logo
     * //accessToken  获取的微信token
     * //fileUrl  图片的路径
     * */
    public String uploadLogo(String fileUrl,String accessToken){
        try {

            File file = new File(fileUrl);
            if (!file.exists() || !file.isFile()) {
                throw new IOException("上传的文件不存在");
            }
            String action = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token="
                    + accessToken + "&type=image";
            URL url = new URL(action);
            String result = null;
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("POST"); // 以Post方式提交表单,默认get方式
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setUseCaches(false); // post方式不能使用缓存
            // 设置请求头信息
            con.setRequestProperty("Connection", "Keep-Alive");
            con.setRequestProperty("Charset", "UTF-8");
            // 设置边界
            String BOUNDARY = "----------" + System.currentTimeMillis();
            con.setRequestProperty("Content-Type", "multipart/form-data; boundary="
                    + BOUNDARY);
            // 请求正文信息
            // 第一部分:
            StringBuilder sb = new StringBuilder();
            sb.append("--"); // 必须多两道线
            sb.append(BOUNDARY);
            sb.append("\r\n");
            sb.append("Content-Disposition: form-data;name=\"file\";filename=\""
                    + file.getName() + "\"\r\n");
            sb.append("Content-Type:application/octet-stream\r\n\r\n");
            byte[] head = sb.toString().getBytes("utf-8");
            // 获得输出流
            OutputStream out = new DataOutputStream(con.getOutputStream());
            // 输出表头
            out.write(head);
            // 文件正文部分
            // 把文件已流文件的方式 推入到url中
            DataInputStream in = new DataInputStream(new FileInputStream(file));
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
            in.close();
            // 结尾部分
            byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
            out.write(foot);
            out.flush();
            out.close();
            StringBuffer buffer = new StringBuffer();
            BufferedReader reader = null;
            try {
                // 定义BufferedReader输入流来读取URL的响应
                reader = new BufferedReader(new InputStreamReader(con
                        .getInputStream()));
                String line = null;
                while ((line = reader.readLine()) != null) {
                    buffer.append(line);
                }
                if (result == null) {
                    result = buffer.toString();
                }
            } catch (IOException e) {
                System.out.println("发送POST请求出现异常!" + e);
                e.printStackTrace();
                throw new IOException("数据读取异常");
            } finally {
                if (reader != null) {
                    reader.close();
                }
            }
            JSONObject json = JSON.parseObject(result);
            String logo_url = StringEscapeUtils.unescapeJava(json.getString("url"));
            return logo_url;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

 三.拼接创建卡券的传参json字符串

 /**
     * 拼接创建卡券参数
     * //couponEntity   参数实体类(根据自己需要的参数编写) 可根据微信接口文档查看各个参数
     * //logoUrl   上方上传logo图片返回的路径
     * */
    public String getWxCardParams(WXCardEntity wxCardEntity, String logoUrl){
        JSONObject wxCradJson = new JSONObject();
        JSONObject baseInfoJson = new JSONObject();
        baseInfoJson.put("logo_url",logoUrl); //卡券的商户logo,建议像素为300*300。 必填
        baseInfoJson.put("code_type","CODE_TYPE_NONE");//码型 必填
        baseInfoJson.put("brand_name",wxCardEntity.getBrandName()); //商户名字 字数上限为12个汉字。 必填
        baseInfoJson.put("title",wxCardEntity.getTitle()); //卡券名,字数上限为9个汉字。(建议涵盖卡券属性、服务及金额)。
        baseInfoJson.put("color","Color010"); //卡券颜色 按色彩规范标注填写Color010-Color100。
        baseInfoJson.put("notice","请在有效期内使用!"); //卡券使用提醒 字数上限为16个汉字。
        baseInfoJson.put("description",wxCardEntity.getDescription()); //卡券使用说明,字数上限为1024个汉字。
        JSONObject skuJson = new JSONObject();
        skuJson.put("quantity",wxCardEntity.getQuantity() == 0 ? 100000: wxCardEntity.getQuantity()); //卡券库存数量 上限为100000000 必填
        baseInfoJson.put("sku",skuJson); //商品信息。 必填
        JSONObject dateInfoJson = new JSONObject();
        // 判断优惠卷过期类型(自领取后时间或者规定时间)
        if(wxCardEntity.getTimeType().equals("0")){
            dateInfoJson.put("type","DATE_TYPE_FIX_TERM");
            dateInfoJson.put("fixed_term",wxCardEntity.getFixedTerm() == 0 ? 1 : wxCardEntity.getFixedTerm());
            dateInfoJson.put("fixed_begin_term",wxCardEntity.getFixedBeginTerm());
        }else if(wxCardEntity.getTimeType().equals("1")){
            dateInfoJson.put("type","DATE_TYPE_FIX_TIME_RANGE");
            dateInfoJson.put("begin_timestamp",wxCardEntity.getStartDate().toEpochSecond(ZoneOffset.of("+8")));
            dateInfoJson.put("end_timestamp",wxCardEntity.getEndDate().toEpochSecond(ZoneOffset.of("+8")));
        }
        baseInfoJson.put("date_info",dateInfoJson); //使用日期,有效期的信息。 必填
        baseInfoJson.put("center_title","立即使用"); //卡券顶部居中的按钮,仅在卡券状 态正常(可以核销)时显示  非必填
        baseInfoJson.put("center_url","www.qq.com");//顶部居中的url ,仅在卡券状态正常(可以核销)时显示  非必填
        baseInfoJson.put("custom_url_name","马上使用"); //自定义跳转外链的入口名字。
        baseInfoJson.put("center_url","https://www.baidu.com"); //自定义跳转的URL。


        JSONObject advancedInfoJson = new JSONObject();
        JSONObject mainJson = new JSONObject();
        mainJson.put("base_info",baseInfoJson); //卡券的基础信息 必填
        mainJson.put("advanced_info",advancedInfoJson); //advanced_info 卡券的高级信息 非必填
        BigDecimal num1 = new BigDecimal(100);
        BigDecimal leastCost = num1.multiply(wxCardEntity.getLeastCost()); //代金券专用,表示起用金额(单位为分),如果无起用门槛则填0。 必填
        BigDecimal reduceCost = num1.multiply(wxCardEntity.getReduceCost()); // 代金券专用,表示减免金额。(单位为分) 必填
        mainJson.put("least_cost",leastCost);
        mainJson.put("reduce_cost",reduceCost);
        wxCradJson.put("card_type","CASH");  //代金券类型 必填
        wxCradJson.put("cash",mainJson);
        JSONObject allJson = new JSONObject();
        allJson.put("card",wxCradJson);
        System.out.println(allJson);
        System.out.println(allJson.toString());
        return allJson.toString();
    }

 四.创建微信卡券

 /**
     * 创建微信卡券
     * //  content  上方拼接返回的 参数
     * // accessToken   微信token
     * */
    public String createWxCard(String content,String accessToken) {
        String url = "https://api.weixin.qq.com/card/create?access_token="+accessToken;
        String line = "";
        String message = "";
        String returnData = "";
        String cardId = "";
        boolean postState = false;
        BufferedReader bufferedReader = null;
        try {
            URL urlObject = new URL(url);
            HttpURLConnection urlConn = (HttpURLConnection) urlObject.openConnection();
            urlConn.setDoOutput(true);
            /*设定禁用缓存*/
            urlConn.setRequestProperty("Cache-Control", "no-cache");
            /*维持长连接*/
            urlConn.setRequestProperty("Connection", "Keep-Alive");
            /*设置字符集*/
            urlConn.setRequestProperty("Charset", "UTF-8");
            /*设定输出格式为json*/
            urlConn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            /*设置使用POST的方式发送*/
            urlConn.setRequestMethod("POST");
            /*设置不使用缓存*/
            urlConn.setUseCaches(false);
            /*设置容许输出*/
            urlConn.setDoOutput(true);
            /*设置容许输入*/
            urlConn.setDoInput(true);
            urlConn.connect();
            OutputStreamWriter outStreamWriter = new OutputStreamWriter(urlConn.getOutputStream(),"UTF-8");
            outStreamWriter.write(content);
            outStreamWriter.flush();
            outStreamWriter.close();
            /*若post失败*/
            if((urlConn.getResponseCode() != 200)){
                returnData = "{\"jsonStrStatus\":0,\"processResults\":[]}";
                message = "发送POST失败!"+ "code="+urlConn.getResponseCode() + "," + "失败消息:"+ urlConn.getResponseMessage();
                // 定义BufferedReader输入流来读取URL的响应
                InputStream errorStream = urlConn.getErrorStream();

                if(errorStream != null)
                {
                    InputStreamReader inputStreamReader = new InputStreamReader(errorStream,"utf-8");
                    bufferedReader = new BufferedReader(inputStreamReader);

                    while ((line = bufferedReader.readLine()) != null) {
                        message += line;
                    }
                    inputStreamReader.close();
                }
                errorStream.close();
                System.out.println("发送失败!错误信息为:"+message);
            }else{
                /*发送成功返回发送成功状态*/
                postState = true;

                // 定义BufferedReader输入流来读取URL的响应
                InputStream inputStream = urlConn.getInputStream();

                InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"utf-8");
                bufferedReader = new BufferedReader(inputStreamReader);

                while ((line = bufferedReader.readLine()) != null) {
                    message += line;
                }
                returnData = message;
                inputStream.close();
                inputStreamReader.close();
                JSONObject json = JSONObject.parseObject(returnData);
                cardId = json.getString("card_id");
                System.out.println("发送POST成功!返回内容为:" + returnData);
                if(StringUtils.isBlank(cardId)){
                    return "发送POST成功!返回内容为:" + returnData;
                }
                return cardId;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            return cardId;
        }
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值