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

准备工作

一.获取access_token

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

    public String getAccessToken() throws Exception{// 获取基础支持的access_tokenString 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;}}

java 微信卡券开发 --创建微信卡券相关推荐

  1. 微信 考勤 php,微信企业号开发之微信考勤Cookies的使用_javascript技巧

    在上篇文章给大家介绍了微信企业号开发之微信考勤百度地图定位,接下来通过本文学习微信企业号开发之微信考勤Cookies的使用,具体内容如下. 使用微信考勤,每次使用微信企业号开发:微信用户信息和web网 ...

  2. java微信红包开发_微信现金红包开发1(JAVA)

    参数3 : 商户订单号  mch_billno String mch_billno = mch_id + GenerateSequenceUtil.generateSequenceNo(); 些一个G ...

  3. 微信程序开发之微信接入(详细开发)

    目录 前言:关于微信程序开发的网站 一.公众号分类 二.微信公众号开发 1.先进入到测试号进行测试 2.获取令牌access_token 3.制作自定义菜单 4.接口配置信息 1.注册的时候必须要实名 ...

  4. 单点服务器微信公众号,腾讯云联合微信降低开发门槛 微信生态从单点云开发到全面云开发...

    本报记者 许洁 11月29日,由腾讯云与微信联合主办的第二届"小程序·云开发"技术峰会在京召开.来自腾讯的数据显示,云开发的注册用户数已达56万,较去年同期增长1.5倍,服务超过1 ...

  5. 微信程序开发之微信接入篇

    微信公众平台 订阅号:个人 服务号:    支付 : 公司-工商营业执照,个体户-工商营业执照 企业号:公司-工商营业执照 测试号: 拥有所有接口   测试号 进入  微信官方文档         微 ...

  6. 微信小游戏开发之Cocos Creator使用微信云开发和微信开放能力

    主题 Cocos Creator集成微信云开发和调用微信开放能力 特别说明 CocosCreator微信小游戏开发系列文章,是我在逐步开发过程中,基于官方文档之上,记录一些重点内容,以及对官方文档中有 ...

  7. 基于微信云开发的微信小程序之搜索功能的实现

    文章目录 搜索功能的设计 代码逻辑 页面设计 效果展示 搜索功能的设计 功能描述: 该模块主要是基于云开发实现小程序搜的搜索功能.如果搜索框输入为空或直接点击搜索按钮,显示对应弹窗:如果搜索框输入内容 ...

  8. 微信支付开发 认清微信支付v2和v3

    微信支付现在分为v2版和v3版 2014年9月10号之前申请的为v2版(旧版本),之后申请的为v3版. V2版中的参数有 AppID AppSecret 支付专用签名串PaySignKey 商户号Pa ...

  9. 微信平台开发与微信营销

    一个二维码,一个商家在线商城,一套管理系统及平台,一个营销渠道,一个时机 1998年马化腾开QQ,让你注册,你不注册,现在一个5位数的QQ好几万: 2003年马云说开淘宝店不要钱,让你开店,你不开,1 ...

  10. php+微信接口开发的微信分销平台拆分讲解(一)微信oauth2接口

    本文不提供整套系统源码,只会开放部分源码,讲诉开发的经历.思路.问题解答,希望对新手有帮助,至于高手和大神一下而过或留下宝贵意见在此谢过. 废话不多说了开始进入正题. 基础篇 php当前主流WEB开发 ...

最新文章

  1. Java为啥不建议用通配符_为什么在Java导入语句中使用通配符不好?
  2. CORS 请求未能成功_CORS攻击概述
  3. 你应该知道的Python3.6、3.7、3.8新特性 ,赶紧收藏!!
  4. 【ICCV2019】完整论文列表
  5. 手把手教我班小姐姐学java之多态
  6. TypeError: Unexpected keyword argument passed to optimizer: learning_rate解决方法
  7. covariance matrix r语言_R语言 第2章 数据对象与数据读写(3)
  8. 【Fiddler】从零开始学习Fiddler
  9. SSM SpringBoot vue办公自动化计划管理系统
  10. oracle一些基本函数
  11. 集群使用calico的bgp+ipip混合模式部署
  12. libxml2的安装和使用
  13. 反病毒三大国际权威认证介绍
  14. Elasticsearch-Cat命令详解
  15. 51nod 1276 岛屿的数量
  16. 【星云测试】星云精准测试之用例魔方
  17. Python3.x web.py安装报错
  18. 欧盟无线CE-RED认证
  19. idea中的Target bytecode Version版
  20. springboot毕设项目面向大学校园的设备保修系统cavpj(java+VUE+Mybatis+Maven+Mysql)

热门文章

  1. C 语言之父,UNIX 系统之父 Dennis Ritchie (丹尼斯 里奇)于 10 月 9 日去世,享年 70 岁
  2. 打开和关闭 Oralce PDB数据库
  3. 一张图片即可入侵你的电脑
  4. 安装windows server2008虚拟机
  5. 在计算机上最常用的英语单词,计算机常用英语单词
  6. 我遇到了Rational Rose
  7. Linux kernel 配置选项
  8. 小管家进销存_管钱、管货、管顾客,“北漂”京东便利店主点赞掌柜管家
  9. [系统安全] 二十.PE数字签名之(上)什么是数字签名及Signtool签名工具详解
  10. ActiveX 部件不能创建对象