From 6efdb1c9d5c8a5fbe8cff07cbe9f82dffdba8466 Mon Sep 17 00:00:00 2001 From: zy_Java <654600784@qq.com> Date: Sat, 18 Sep 2021 17:45:48 +0800 Subject: [PATCH] =?UTF-8?q?=E5=88=86=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/ccsens/util/wx/WxGzhUtil.java | 5 +- .../ccsens/wechatutil/api/WxController.java | 160 +++++------ .../wechatutil/bean/dto/WxMessageDto.java | 69 +++++ .../wechatutil/payutil/WxMessageUtil.java | 76 ++--- .../wechatutil/service/IWxMessageService.java | 12 - .../ccsens/wechatutil/service/IWxService.java | 104 ------- .../ccsens/wechatutil/service/WxService.java | 266 ------------------ .../ccsens/wechatutil/util/WxConstant.java | 27 +- .../wechatutil/wxcommon/WxCommonUtil.java | 67 +++++ .../EnterpriseRobotUtil.java} | 14 +- .../ccsens/wechatutil/wxmini/MiniCode.java | 151 ++++++++++ .../ccsens/wechatutil/wxmini/MiniMessage.java | 82 ++++++ .../wechatutil/wxmini/MiniSigninUtil.java | 70 +++++ .../wxofficial/OfficialAccountSigninUtil.java | 96 +++++++ 14 files changed, 686 insertions(+), 513 deletions(-) delete mode 100644 wechatutil/src/main/java/com/ccsens/wechatutil/service/IWxMessageService.java delete mode 100644 wechatutil/src/main/java/com/ccsens/wechatutil/service/IWxService.java delete mode 100644 wechatutil/src/main/java/com/ccsens/wechatutil/service/WxService.java create mode 100644 wechatutil/src/main/java/com/ccsens/wechatutil/wxcommon/WxCommonUtil.java rename wechatutil/src/main/java/com/ccsens/wechatutil/{service/WxMessageService.java => wxenterprise/EnterpriseRobotUtil.java} (84%) create mode 100644 wechatutil/src/main/java/com/ccsens/wechatutil/wxmini/MiniCode.java create mode 100644 wechatutil/src/main/java/com/ccsens/wechatutil/wxmini/MiniMessage.java create mode 100644 wechatutil/src/main/java/com/ccsens/wechatutil/wxmini/MiniSigninUtil.java create mode 100644 wechatutil/src/main/java/com/ccsens/wechatutil/wxofficial/OfficialAccountSigninUtil.java diff --git a/util/src/main/java/com/ccsens/util/wx/WxGzhUtil.java b/util/src/main/java/com/ccsens/util/wx/WxGzhUtil.java index e1b7206d..b6dbb524 100644 --- a/util/src/main/java/com/ccsens/util/wx/WxGzhUtil.java +++ b/util/src/main/java/com/ccsens/util/wx/WxGzhUtil.java @@ -71,10 +71,8 @@ public class WxGzhUtil { = "https://api.weixin.qq.com/cgi-bin/get_current_selfmenu_info?access_token=%1$s"; private static final String GZH_AUTH_URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%1$s&redirect_uri=%2$s&response_type=code&scope=%3$s&state=STATE#wechat_redirect"; - //TODO private static final String URL_GET_OAUTH2_ACCESS_TOKEN = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%1$s&secret=%2$s&code=%3$s&grant_type=authorization_code"; - //TODO private static final String URL_GET_OAUTH2_USERINFO = "https://api.weixin.qq.com/sns/userinfo?access_token=%1$s&openid=%2$s"; public static final String MESSAGE_TEMPLATE_SEND = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%1$s"; @@ -98,6 +96,9 @@ public class WxGzhUtil { private static final String KEY = ""; public enum Template{ + /** + * 公众号消息模板 + */ TASK_FINISH("OtFNgGj9Eiy3MuWO6j3Mb-An4LsVnIEBQCn1ZBSAXR8","工作完成通知","{{first.DATA}}工作内容:{{keyword1.DATA}}创建时间:{{keyword2.DATA}}{{remark.DATA}}"), TASK_ADD("Tj0n5-aLvrrAksbGH5A1h-Dx44Z3c9u6cu7WZK5StEQ","工作分配通知", "{{first.DATA}}工作内容:{{keyword1.DATA}}创建时间:{{keyword2.DATA}}{{remark.DATA}}"), TASK_DELETE("0qi0qqFyNQL0UChGlXLx92EtsBDhTLMINnt0akK1pyM","工作取消通知", "{{first.DATA}}工作内容:{{keyword1.DATA}}工作时间:{{keyword2.DATA}}详情:{{keyword3.DATA}}{{remark.DATA}}"), diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/api/WxController.java b/wechatutil/src/main/java/com/ccsens/wechatutil/api/WxController.java index c120ac4a..9960a76d 100644 --- a/wechatutil/src/main/java/com/ccsens/wechatutil/api/WxController.java +++ b/wechatutil/src/main/java/com/ccsens/wechatutil/api/WxController.java @@ -1,80 +1,80 @@ -package com.ccsens.wechatutil.api; - -import com.ccsens.util.JsonResponse; -import com.ccsens.wechatutil.bean.dto.WxMessageDto; -import com.ccsens.wechatutil.service.IWxMessageService; -import com.ccsens.wechatutil.service.IWxService; -import com.ccsens.wechatutil.bean.po.MiniProgramUser; -import com.ccsens.wechatutil.bean.po.WxOauth2UserInfo; -import com.ccsens.wechatutil.bean.dto.WechatCode; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import lombok.extern.slf4j.Slf4j; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; - -import javax.annotation.Resource; - -/** - * @author 逗 - */ -@Api(tags = "DEBUG" , description = "DebugController | ") -@RestController -@RequestMapping("/wx") -@Slf4j -public class WxController { - - @Resource - private IWxService miniProgramService; - @Resource - private IWxMessageService wxMessageService; - - @ApiOperation(value = "小程序根据code获取appId", notes = "小程序") - @RequestMapping(value = "/signinByMini", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) - public JsonResponse signinByMini(@ApiParam @Validated String code) throws Exception{ - MiniProgramUser wxUser = miniProgramService.signinByMini(code); - return JsonResponse.newInstance().ok(); - } - - @ApiOperation(value = "公众号/网页二维码登录", notes = "公众号/网页二维码") - @RequestMapping(value = "/signinByH5", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) - public JsonResponse signinByH5(@ApiParam @Validated String code) throws Exception{ - WxOauth2UserInfo wxUser = miniProgramService.signinByH5(code); - return JsonResponse.newInstance().ok(); - } - - @ApiOperation(value = "生成小程序码-方案A", notes = "") - @RequestMapping(value = "/getWxCodeA", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) - public JsonResponse getWxCodeA(@ApiParam @Validated WechatCode.WechatCodeA wechatCodeA, String path) throws Exception{ - miniProgramService.getWxCodeA(wechatCodeA, path); - return JsonResponse.newInstance().ok(); - } - - - @ApiOperation(value = "生成小程序码-方案B", notes = "") - @RequestMapping(value = "/getWxCodeB", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) - public JsonResponse getWxCodeB(@ApiParam @Validated WechatCode.WechatCodeB wechatCodeB,String path) throws Exception{ - wechatCodeB = new WechatCode.WechatCodeB(); - wechatCodeB.setScene("id=1&type=SQ"); - wechatCodeB.setPage("pages/index/index"); - miniProgramService.getWxCodeB(wechatCodeB,path); - return JsonResponse.newInstance().ok(); - } - - @ApiOperation(value = "生成小程序码-方案B", notes = "") - @RequestMapping(value = "/getWxCodeC", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) - public JsonResponse getWxCodeC(@ApiParam @Validated WechatCode.WechatCodeC wechatCodeC,String path) throws Exception{ - miniProgramService.getWxCodeC(wechatCodeC,path); - return JsonResponse.newInstance().ok(); - } - - @ApiOperation(value = "群机器人发送消息", notes = "") - @RequestMapping(value = "/robotMessage", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) - public JsonResponse robotMessage(@ApiParam @Validated WxMessageDto.RobotMessage robotMessage) throws Exception{ - wxMessageService.sendRobotInfo(robotMessage); - return JsonResponse.newInstance().ok(); - } -} +//package com.ccsens.wechatutil.api; +// +//import com.ccsens.util.JsonResponse; +//import com.ccsens.wechatutil.bean.dto.WxMessageDto; +//import com.ccsens.wechatutil.service.IWxMessageService; +//import com.ccsens.wechatutil.service.IWxService; +//import com.ccsens.wechatutil.bean.po.MiniProgramUser; +//import com.ccsens.wechatutil.bean.po.WxOauth2UserInfo; +//import com.ccsens.wechatutil.bean.dto.WechatCode; +//import io.swagger.annotations.Api; +//import io.swagger.annotations.ApiOperation; +//import io.swagger.annotations.ApiParam; +//import lombok.extern.slf4j.Slf4j; +//import org.springframework.validation.annotation.Validated; +//import org.springframework.web.bind.annotation.RequestMapping; +//import org.springframework.web.bind.annotation.RequestMethod; +//import org.springframework.web.bind.annotation.RestController; +// +//import javax.annotation.Resource; +// +///** +// * @author 逗 +// */ +//@Api(tags = "DEBUG" , description = "DebugController | ") +//@RestController +//@RequestMapping("/wx") +//@Slf4j +//public class WxController { +// +// @Resource +// private IWxService miniProgramService; +// @Resource +// private IWxMessageService wxMessageService; +// +// @ApiOperation(value = "小程序根据code获取appId", notes = "小程序") +// @RequestMapping(value = "/signinByMini", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) +// public JsonResponse signinByMini(@ApiParam @Validated String code) throws Exception{ +// MiniProgramUser wxUser = miniProgramService.signinByMini(code); +// return JsonResponse.newInstance().ok(); +// } +// +// @ApiOperation(value = "公众号/网页二维码登录", notes = "公众号/网页二维码") +// @RequestMapping(value = "/signinByH5", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) +// public JsonResponse signinByH5(@ApiParam @Validated String code) throws Exception{ +// WxOauth2UserInfo wxUser = miniProgramService.signinByH5(code); +// return JsonResponse.newInstance().ok(); +// } +// +// @ApiOperation(value = "生成小程序码-方案A", notes = "") +// @RequestMapping(value = "/getWxCodeA", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) +// public JsonResponse getWxCodeA(@ApiParam @Validated WechatCode.WechatCodeA wechatCodeA, String path) throws Exception{ +// miniProgramService.getWxCodeA(wechatCodeA, path); +// return JsonResponse.newInstance().ok(); +// } +// +// +// @ApiOperation(value = "生成小程序码-方案B", notes = "") +// @RequestMapping(value = "/getWxCodeB", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) +// public JsonResponse getWxCodeB(@ApiParam @Validated WechatCode.WechatCodeB wechatCodeB,String path) throws Exception{ +// wechatCodeB = new WechatCode.WechatCodeB(); +// wechatCodeB.setScene("id=1&type=SQ"); +// wechatCodeB.setPage("pages/index/index"); +// miniProgramService.getWxCodeB(wechatCodeB,path); +// return JsonResponse.newInstance().ok(); +// } +// +// @ApiOperation(value = "生成小程序码-方案B", notes = "") +// @RequestMapping(value = "/getWxCodeC", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) +// public JsonResponse getWxCodeC(@ApiParam @Validated WechatCode.WechatCodeC wechatCodeC,String path) throws Exception{ +// miniProgramService.getWxCodeC(wechatCodeC,path); +// return JsonResponse.newInstance().ok(); +// } +// +// @ApiOperation(value = "群机器人发送消息", notes = "") +// @RequestMapping(value = "/robotMessage", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) +// public JsonResponse robotMessage(@ApiParam @Validated WxMessageDto.RobotMessage robotMessage) throws Exception{ +// wxMessageService.sendRobotInfo(robotMessage); +// return JsonResponse.newInstance().ok(); +// } +//} diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/bean/dto/WxMessageDto.java b/wechatutil/src/main/java/com/ccsens/wechatutil/bean/dto/WxMessageDto.java index afb9857a..dd7c3eb0 100644 --- a/wechatutil/src/main/java/com/ccsens/wechatutil/bean/dto/WxMessageDto.java +++ b/wechatutil/src/main/java/com/ccsens/wechatutil/bean/dto/WxMessageDto.java @@ -1,6 +1,10 @@ package com.ccsens.wechatutil.bean.dto; +import cn.hutool.core.collection.CollectionUtil; +import com.ccsens.wechatutil.payutil.WxMessageUtil; import lombok.Data; +import lombok.Getter; +import lombok.Setter; import java.util.List; @@ -43,4 +47,69 @@ public class WxMessageDto { private String content; } + /*** -----------------小程序订阅消息相关---------------------- */ + @Getter + @Setter + private static class CommonEntity { + private String value; + } + + @Getter + @Setter + public static class SubscribeEntity { + private String touser; + private String template_id; + private String page; + private T data; + } + + @Getter + @Setter + public static class ReceiveSubscriBuyData { + public ReceiveSubscriBuyData(List params) { + if (CollectionUtil.isNotEmpty(params) && params.size() >= 2) { + character_string1 = new CommonEntity(); + amount3 = new CommonEntity(); + thing4 = new CommonEntity(); + time2 = new CommonEntity(); + number11 = new CommonEntity(); + character_string1.setValue(params.get(0)); + amount3.setValue(params.get(1)); + thing4.setValue(params.get(2)); + time2.setValue(params.get(3)); + number11.setValue(params.get(4)); + } + } + + private CommonEntity character_string1;//订单编号 + private CommonEntity amount3;//订单金额 + private CommonEntity thing4;//商品名称 + private CommonEntity time2;//支付时间 + private CommonEntity number11;//购买数量 + } + + @Getter + @Setter + public static class ReceiveSubscriOrderSendData { + public ReceiveSubscriOrderSendData(List params) { + if (CollectionUtil.isNotEmpty(params) && params.size() >= 2) { + thing1 = new CommonEntity(); + character_string2 = new CommonEntity(); + date3 = new CommonEntity(); + thing4 = new CommonEntity(); + character_string5 = new CommonEntity(); + thing1.setValue(params.get(0)); + character_string2.setValue(params.get(1)); + date3.setValue(params.get(2)); + thing4.setValue(params.get(3)); + character_string5.setValue(params.get(4)); + } + } + + private CommonEntity thing1;//商品名称 + private CommonEntity character_string2;//订单号 + private CommonEntity date3;//发货时间 + private CommonEntity thing4;//快递公司 + private CommonEntity character_string5;//快递单号 + } } diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/payutil/WxMessageUtil.java b/wechatutil/src/main/java/com/ccsens/wechatutil/payutil/WxMessageUtil.java index 58b42281..c5611089 100644 --- a/wechatutil/src/main/java/com/ccsens/wechatutil/payutil/WxMessageUtil.java +++ b/wechatutil/src/main/java/com/ccsens/wechatutil/payutil/WxMessageUtil.java @@ -1,6 +1,7 @@ package com.ccsens.wechatutil.payutil; import cn.hutool.core.collection.CollectionUtil; +import com.ccsens.util.HttpsUtil; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; @@ -25,6 +26,9 @@ public class WxMessageUtil { private static String SUBSCRIBE_MSG_ID_ORDERSEND = "5-rhM8h3x1W82tHCt18g9iXyGELyUKQtBDZiFjgItOo"; public enum Packet_Notify_Type { + /** + * 消息类型 + */ Buy(1, "购买"), ReceiveSubscriBuyData(2, "订单发货"); @@ -112,40 +116,40 @@ public class WxMessageUtil { * @return * @throws Exception // */ -// public static boolean sendSubcribeMsg(Packet_Notify_Type notifyType, String toUser, String page, List params) throws Exception { -// String ret = null; -// String url = String.format(URL_SEND_SUBSCRIBE_MESSAGE, WxTokenUtil.getToken()); -// switch (notifyType) { -// //订单支付成功通知 -// case Buy: { -// SubscribeEntity t = new SubscribeEntity<>(); -// t.setTouser(toUser); -// t.setTemplate_id(SUBSCRIBE_MSG_ID_BUY); -// t.setPage(page); -// t.setData(new ReceiveSubscriBuyData(params)); -// System.out.println(JacksonUtil.beanToJson(t)); -// ret = HttpsUtil.httpsRequest(url, "POST", pers.wei.wx.pay.util.JacksonUtil.beanToJson(t)); -// break; -// } -// //订单发货 -// case ReceiveSubscriBuyData: { -// SubscribeEntity t = new SubscribeEntity<>(); -// t.setTouser(toUser); -// t.setTemplate_id(SUBSCRIBE_MSG_ID_ORDERSEND); -// t.setData(new ReceiveSubscriOrderSendData(params)); -// System.out.println(JacksonUtil.beanToJson(t)); -// ret = httpsRequest(url, "POST", JacksonUtil.beanToJson(t)); -// break; -// } -// default: { -// break; -// } -// } -// //ok: {"errcode":0,"errmsg":"ok"} -// //err: {"errcode":43101,"errmsg":"user refuse to accept the msg hint: [V_GEdA02503942]"} -// System.out.println("Send Subscribe Message:" + ret); -// String errCode = pers.wei.wx.pay.util.JacksonUtil.getJsonValue(ret, "errcode"); -// System.out.println(errCode); -// return errCode.equals("0"); -// } + public static boolean sendSubcribeMsg(Packet_Notify_Type notifyType, String toUser, String page, List params) throws Exception { + String ret = null; + String url = String.format(URL_SEND_SUBSCRIBE_MESSAGE, WxTokenUtil.getToken()); + switch (notifyType) { + //订单支付成功通知 + case Buy: { + SubscribeEntity t = new SubscribeEntity<>(); + t.setTouser(toUser); + t.setTemplate_id(SUBSCRIBE_MSG_ID_BUY); + t.setPage(page); + t.setData(new ReceiveSubscriBuyData(params)); + System.out.println(JacksonUtil.beanToJson(t)); + ret = HttpsUtil.httpsRequest(url, "POST", JacksonUtil.beanToJson(t)); + break; + } + //订单发货 + case ReceiveSubscriBuyData: { + SubscribeEntity t = new SubscribeEntity<>(); + t.setTouser(toUser); + t.setTemplate_id(SUBSCRIBE_MSG_ID_ORDERSEND); + t.setData(new ReceiveSubscriOrderSendData(params)); + System.out.println(JacksonUtil.beanToJson(t)); + ret = HttpsUtil.httpsRequest(url, "POST", JacksonUtil.beanToJson(t)); + break; + } + default: { + break; + } + } + //ok: {"errcode":0,"errmsg":"ok"} + //err: {"errcode":43101,"errmsg":"user refuse to accept the msg hint: [V_GEdA02503942]"} + System.out.println("Send Subscribe Message:" + ret); + String errCode = JacksonUtil.getJsonValue(ret, "errcode"); + System.out.println(errCode); + return errCode.equals("0"); + } } diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/service/IWxMessageService.java b/wechatutil/src/main/java/com/ccsens/wechatutil/service/IWxMessageService.java deleted file mode 100644 index 84d5c5ab..00000000 --- a/wechatutil/src/main/java/com/ccsens/wechatutil/service/IWxMessageService.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.ccsens.wechatutil.service; - -import com.ccsens.wechatutil.bean.dto.WxMessageDto; - -public interface IWxMessageService { - /** - * 群机器人发送消息 - * @param robotMessage - * @throws Exception - */ - void sendRobotInfo(WxMessageDto.RobotMessage robotMessage)throws Exception; -} diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/service/IWxService.java b/wechatutil/src/main/java/com/ccsens/wechatutil/service/IWxService.java deleted file mode 100644 index caa92aad..00000000 --- a/wechatutil/src/main/java/com/ccsens/wechatutil/service/IWxService.java +++ /dev/null @@ -1,104 +0,0 @@ -package com.ccsens.wechatutil.service; - -import com.ccsens.wechatutil.bean.po.MiniProgramUser; -import com.ccsens.wechatutil.bean.po.WxOauth2UserInfo; -import com.ccsens.wechatutil.bean.dto.WechatCode; - -/** - * @author 逗 - */ -public interface IWxService { - - /** - * 小程序登录 - * -- 从配置文件中获取默认appId - * 配置文件内的名称 h5.appId: 和 h5.secret: - * @param code code - * @return 返回当前用户的openId等 - */ - MiniProgramUser signinByMini(String code); - - /** - * 小程序登录 -- 传入appId - * @param code code - * @param appId appId - * @param secret secret - * @return 返回当前用户的openId等 - */ - MiniProgramUser signinByMini(String code, String appId, String secret); - - /** - * H5扫码登录,公众号登录 - * -- 从配置文件中获取默认appId - * 配置文件内的名称 h5.appId: 和 h5.secret: - * @param code code - * @return 返回微信用户信息 - */ - WxOauth2UserInfo signinByH5(String code); - - /** - * H5扫码登录,公众号登录 -- 传入appId - * @param code code - * @param appId appId - * @param secret secret - * @return 返回微信用户信息 - */ - WxOauth2UserInfo signinByH5(String code, String appId, String secret); - - /** - * 获取小程序码--方案A,可接受 path 参数较长,生成个数受限 - * 接口 A 加上接口 C,总共生成的码数量限制为 100,000,请谨慎调用。 - * 使用默认appId - * @param wechatCodeA 传入参数 - * @param path 小程序码存储位置 - */ - void getWxCodeA(WechatCode.WechatCodeA wechatCodeA,String path) throws Exception; - - /** - * 获取小程序码--方案A,可接受 path 参数较长,生成个数受限 - * 接口 A 加上接口 C,总共生成的码数量限制为 100,000,请谨慎调用。 - * @param wechatCodeA 传入参数 - * @param path 小程序码存储位置 - * @param appId appId - * @param secret secret - */ - void getWxCodeA(WechatCode.WechatCodeA wechatCodeA,String path, String appId, String secret) throws Exception; - - /** - * 获取小程序码--方案B,可接受页面参数较短,生成个数不受限。 - * 接口 B 调用分钟频率受限(5000次/分钟),如需大量小程序码,建议预生成 - * 使用默认appId - * @param wechatCodeB 传入参数 - * @param path 小程序码存储位置 - */ - void getWxCodeB(WechatCode.WechatCodeB wechatCodeB,String path) throws Exception; - - /** - * 获取小程序码--方案B,可接受页面参数较短,生成个数不受限。 - * 接口 B 调用分钟频率受限(5000次/分钟),如需大量小程序码,建议预生成 - * @param wechatCodeB 传入参数 - * @param path 小程序码存储位置 - * @param appId appId - * @param secret secret - */ - void getWxCodeB(WechatCode.WechatCodeB wechatCodeB,String path, String appId, String secret) throws Exception; - - /** - * 方案C-生成小程序码(二维码),可接受 path 参数较长,生成个数受限,数量限制见 - * 接口 A 加上接口 C,总共生成的码数量限制为 100,000,请谨慎调用。 - * 使用默认appId - * @param wechatCodeC 传入参数 - * @param path 小程序码存储位置 - */ - void getWxCodeC(WechatCode.WechatCodeC wechatCodeC,String path) throws Exception; - - /** - * 方案C-生成小程序码(二维码),可接受 path 参数较长,生成个数受限,数量限制见 - * 接口 A 加上接口 C,总共生成的码数量限制为 100,000,请谨慎调用。 - * @param wechatCodeC 传入参数 - * @param path 小程序码存储位置 - * @param appId appId - * @param secret secret - */ - void getWxCodeC(WechatCode.WechatCodeC wechatCodeC,String path, String appId, String secret) throws Exception; -} diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/service/WxService.java b/wechatutil/src/main/java/com/ccsens/wechatutil/service/WxService.java deleted file mode 100644 index 1b8d8c9e..00000000 --- a/wechatutil/src/main/java/com/ccsens/wechatutil/service/WxService.java +++ /dev/null @@ -1,266 +0,0 @@ -package com.ccsens.wechatutil.service; - -import cn.hutool.core.util.StrUtil; -import cn.hutool.http.HttpRequest; -import com.ccsens.util.*; -import com.ccsens.util.bean.wx.po.WxAccessToken; -import com.ccsens.util.exception.BaseException; -import com.ccsens.wechatutil.bean.po.WxBaseEntity; -import com.ccsens.wechatutil.util.WxCodeError; -import com.ccsens.wechatutil.util.WxConstant; -import com.ccsens.wechatutil.bean.po.MiniProgramUser; -import com.ccsens.wechatutil.bean.po.WxOauth2AccessToken; -import com.ccsens.wechatutil.bean.po.WxOauth2UserInfo; -import com.ccsens.wechatutil.bean.dto.WechatCode; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Propagation; -import org.springframework.transaction.annotation.Transactional; - -import javax.annotation.Resource; -import java.io.*; - -/** - * @author 逗 - */ -@Slf4j -@Service -@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) -public class WxService implements IWxService { - - @Resource - private RedisUtil redisUtil; - - @Value("${mini.appId:}") - private String miniAppId; - @Value("${mini.secret:}") - private String miniSecret; - @Value("${h5.appId:}") - private String appIdH5; - @Value("${h5.secret:}") - private String secretH5; - - @Override - public MiniProgramUser signinByMini(String code) { - return signinByMini(code, miniAppId, miniSecret); - } - - @Override - public MiniProgramUser signinByMini(String code, String appId, String secret) { - MiniProgramUser wxUser; - //拼接wx的访问的路径 - String url = String.format(WxConstant.MINI_PROGRAM_LOGIN, appId, secret, code, WxConstant.GRANT_TYPE); - //调用微信的接口 - String response = HttpRequest.get(url).execute().body(); - log.info("url: {}\nresponse: {}", url, response); - try { - if (StrUtil.isEmpty(response) || null == (wxUser = JacksonUtil.jsonToBean(response, MiniProgramUser.class))) { - throw new BaseException(WxCodeError.WX_HTTP_ERROR); - } - } catch (IOException e) { - throw new BaseException(e.getMessage()); - } - if (null != wxUser.getErrcode()) { - throw new BaseException(wxUser.getErrcode(), wxUser.getErrmsg()); - } - return wxUser; - } - - @Override - public WxOauth2UserInfo signinByH5(String code) { - return signinByH5(code, appIdH5, secretH5); - } - - @Override - public WxOauth2UserInfo signinByH5(String code, String appId, String secret) { - //获取accessToken - WxOauth2AccessToken wxOauth2AccessToken = getOauth2AccessToken(code, appId, secret); - //获取用户信息 - return getOauth2UserInfo(wxOauth2AccessToken.getAccessToken(), wxOauth2AccessToken.getOpenId()); - } - - - - @Override - public void getWxCodeA(WechatCode.WechatCodeA wechatCodeA, String path)throws Exception { - getWxCodeA(wechatCodeA,path,miniAppId,miniSecret); - } - - @Override - public void getWxCodeA(WechatCode.WechatCodeA wechatCodeA, String path, String appId, String secret) throws Exception { - String url = String.format(WxConstant.URL_GET_WX_CODE_A, getAccessToken(appId, secret)); - log.info("调用生成二维码路径和accessToken:{}", url); - String postStr = JacksonUtil.beanToJson(wechatCodeA); - log.info("二维码的参数:{}", postStr); - //调用微信接口在指定位置生成图片 - httpWxCode(path, url, postStr); - } - - @Override - public void getWxCodeB(WechatCode.WechatCodeB wechatCodeB, String path)throws Exception { - getWxCodeB(wechatCodeB,path,miniAppId, miniSecret); - } - - @Override - public void getWxCodeB(WechatCode.WechatCodeB wechatCodeB, String path, String appId, String secret) throws Exception { - String url = String.format(WxConstant.URL_GET_WX_CODE_B, getAccessToken(appId, secret)); - log.info("调用生成二维码路径和accessToken:{}", url); - String postStr = JacksonUtil.beanToJson(wechatCodeB); - log.info("二维码的参数:{}", postStr); - //调用微信接口在指定位置生成图片 - httpWxCode(path, url, postStr); - } - - @Override - public void getWxCodeC(WechatCode.WechatCodeC wechatCodeC, String path) throws Exception { - getWxCodeC(wechatCodeC,path,miniAppId, miniSecret); - } - - @Override - public void getWxCodeC(WechatCode.WechatCodeC wechatCodeC, String path, String appId, String secret) throws Exception { - String url = String.format(WxConstant.URL_GET_WX_CODE_C, getAccessToken(appId, secret)); - log.info("调用生成二维码路径和accessToken:{}", url); - String postStr = JacksonUtil.beanToJson(wechatCodeC); - log.info("二维码的参数:{}", postStr); - //调用微信接口在指定位置生成图片 - httpWxCode(path, url, postStr); - } - - /** - * 获取网页授权凭证 - * - * @param code OAuth2授权码 - * @return WxOauth2AccessToken - */ - private WxOauth2AccessToken getOauth2AccessToken(String code, String appId, String secret) { - WxOauth2AccessToken wxOauth2AccessToken; - //拼接访问路径 - String url = String.format(WxConstant.URL_GET_OAUTH2_ACCESS_TOKEN, appId, secret, code); - //调用微信接口 - String response = HttpRequest.get(url).execute().body(); - log.info("url: {}\nresponse: {}", url, response); - try { - if (StrUtil.isEmpty(response) || null == (wxOauth2AccessToken = JacksonUtil.jsonToBean(response, WxOauth2AccessToken.class))) { - throw new BaseException(WxCodeError.WX_HTTP_ERROR); - } - } catch (IOException e) { - throw new BaseException(e.getMessage()); - } - if (null != wxOauth2AccessToken.getErrcode()) { - throw new BaseException(wxOauth2AccessToken.getErrcode(), wxOauth2AccessToken.getErrmsg()); - } - if (StrUtil.isEmpty(wxOauth2AccessToken.getAccessToken())) { - throw new BaseException(WxCodeError.ACCESS_TOKEN_ERROR); - } - wxOauth2AccessToken.setCreatedAt(DateUtil.currentSeconds()); - return wxOauth2AccessToken; - } - - /** - * 通过网页授权accessToken获取用户信息 - * - * @param accessToken 网页授权接口调用凭证 - * @param openId 用户标识 - * @return SNSUserInfo - */ - private WxOauth2UserInfo getOauth2UserInfo(String accessToken, String openId) { - WxOauth2UserInfo wxOauth2UserInfo; - //拼接访问路径 - String url = String.format(WxConstant.URL_GET_OAUTH2_USER_INFO, accessToken, openId); - //调用微信接口 - String response = HttpRequest.get(url).execute().body(); - log.info("url: {}\nresponse: {}", url, response); - try { - if (StrUtil.isEmpty(response) || null == (wxOauth2UserInfo = JacksonUtil.jsonToBean(response, WxOauth2UserInfo.class))) { - throw new BaseException(WxCodeError.WX_HTTP_ERROR); - } - } catch (IOException e) { - throw new BaseException(e.getMessage()); - } - if (null != wxOauth2UserInfo.getErrcode()) { - throw new BaseException(wxOauth2UserInfo.getErrcode(), wxOauth2UserInfo.getErrmsg()); - } - if (StrUtil.isEmpty(wxOauth2UserInfo.getOpenId())) { - throw new BaseException(WxCodeError.OPENID_ERROR); - } - return wxOauth2UserInfo; - } - - /** - * 调用微信的接口在指定位置生成二维码 - * @param path 图片储存位置 - * @param url 微信接口路径 - * @param postStr 传入参数 - * @throws Exception 异常 - */ - public void httpWxCode(String path, String url, String postStr) throws Exception { -// HttpsUtil.httpsRequest(url, "POST", postStr,path); - WxBaseEntity wxBaseEntity; - byte[] response = HttpsUtil.httpsRequestByte(url, "POST", postStr); - - if(response.length == 0){ - throw new BaseException(WxCodeError.WX_HTTP_ERROR); - } - try { - if (null == (wxBaseEntity = JacksonUtil.jsonToBean(new String(response), WxBaseEntity.class))) { - throw new BaseException(WxCodeError.WX_HTTP_ERROR); - } - if (null != wxBaseEntity.getErrcode()) { - throw new BaseException(wxBaseEntity.getErrcode(), wxBaseEntity.getErrmsg()); - } - } catch (IOException e) { - // 从输入流读取返回内容 - File file = new File(path); - if (!file.getParentFile().exists()) { - file.getParentFile().mkdirs(); - } - InputStream inputStream = new ByteArrayInputStream(response); - BufferedInputStream bis = new BufferedInputStream(inputStream); - OutputStream os = new FileOutputStream(file); - int len; - byte[] arr = new byte[1024]; - while ((len = bis.read(arr)) != -1) - { - os.write(arr, 0, len); - os.flush(); - } - os.close(); - } - } - - /** - * 小程序获取Access_token - */ - private String getAccessToken(String appId, String secret) throws BaseException { - log.info("获取accessToken,appid:{}", appId.substring(appId.length() - 4)); - Object obj = redisUtil.get(WxConstant.ACCESS_TOKEN + appId); - if (obj == null || StrUtil.isBlank((String) obj)) { - WxAccessToken wxAccessToken; - String url = String.format(WxConstant.URL_GET_ACCESS_TOKEN, "client_credential", appId, secret); - String response = HttpRequest.get(url).execute().body(); - log.info("getAccessToken: {}", response); - try { - if (StrUtil.isEmpty(response) || null == (wxAccessToken = JacksonUtil.jsonToBean(response, WxAccessToken.class))) { - throw new BaseException(WxCodeError.WX_HTTP_ERROR); - } - } catch (IOException e) { - throw new BaseException(e.getMessage()); - } - - if (null != wxAccessToken.getErrcode()) { - throw new BaseException(wxAccessToken.getErrcode(), wxAccessToken.getErrmsg()); - } - if (StrUtil.isEmpty(wxAccessToken.getAccessToken())) { - throw new BaseException(WxCodeError.ACCESS_TOKEN_ERROR); - } - redisUtil.set(WebConstant.Wx.ACCESS_TOKEN + appId, wxAccessToken.getAccessToken(), WebConstant.Wx.EXPIRE_TIME); - log.info("存储access_token:{}", wxAccessToken.getAccessToken()); - return wxAccessToken.getAccessToken(); - } - log.info("读取reids的token:{}", obj); - return (String) obj; - } - - -} diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/util/WxConstant.java b/wechatutil/src/main/java/com/ccsens/wechatutil/util/WxConstant.java index 5c66b719..604e51f6 100644 --- a/wechatutil/src/main/java/com/ccsens/wechatutil/util/WxConstant.java +++ b/wechatutil/src/main/java/com/ccsens/wechatutil/util/WxConstant.java @@ -25,7 +25,15 @@ public class WxConstant { /*** 获取小程序码C */ public static final String URL_GET_WX_CODE_C = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=%1$s"; /*** 小程序获取accessToken */ - public static final String URL_GET_ACCESS_TOKEN = "https://api.weixin.qq.com/cgi-bin/token?grant_type=%1$s&appid=%2$s&secret=%3$s"; + public static final String URL_GET_ACCESS_TOKEN = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credentia&appid=%1$s&secret=%2$s"; + + /*** 小程序发送订阅消息 */ + public static final String URL_SEND_SUBSCRIBE_MESSAGE = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=%1$s"; + + /*** 小程序消息模板--支付 */ + public static String SUBSCRIBE_MSG_ID_BUY = "bqdx4FW51G-JLU6HjL6LyvUbjpo4rFK6CPor2-w3VwM"; + /*** 小程序消息模板--订单发送 */ + public static String SUBSCRIBE_MSG_ID_ORDERSEND = "5-rhM8h3x1W82tHCt18g9iXyGELyUKQtBDZiFjgItOo"; /*** 小程序登录路径内的type */ public static final String GRANT_TYPE = "authorization_code"; @@ -39,9 +47,24 @@ public class WxConstant { public static final String MARKDOWN = "markdown"; + /** + * 小程序订阅消息类型 + */ + public enum Packet_Notify_Type { + /** + * 消息类型 + */ + Buy(1, "购买"), + ReceiveSubscriBuyData(2, "订单发货"); + public int value; + public String phase; - + Packet_Notify_Type(int value, String thePhase) { + this.value = value; + this.phase = thePhase; + } + } /*** 小程序appId */ public static final Map APP_ID = new HashMap<>(); diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/wxcommon/WxCommonUtil.java b/wechatutil/src/main/java/com/ccsens/wechatutil/wxcommon/WxCommonUtil.java new file mode 100644 index 00000000..a53b35dd --- /dev/null +++ b/wechatutil/src/main/java/com/ccsens/wechatutil/wxcommon/WxCommonUtil.java @@ -0,0 +1,67 @@ +package com.ccsens.wechatutil.wxcommon; + +import cn.hutool.core.util.StrUtil; +import cn.hutool.http.HttpRequest; +import com.ccsens.util.JacksonUtil; +import com.ccsens.util.RedisUtil; +import com.ccsens.util.WebConstant; +import com.ccsens.util.bean.wx.po.WxAccessToken; +import com.ccsens.util.exception.BaseException; +import com.ccsens.wechatutil.util.WxCodeError; +import com.ccsens.wechatutil.util.WxConstant; +import lombok.extern.slf4j.Slf4j; + +import javax.annotation.PostConstruct; +import javax.annotation.Resource; +import java.io.IOException; +/** + * @author 逗 + */ +@Slf4j +public class WxCommonUtil { + + + @Resource + private RedisUtil redisUtil; + + private static WxCommonUtil util; + + @PostConstruct + public void init(){ + util = this; + } + + + /** + * 小程序获取Access_token + */ + public static String getAccessToken(String appId, String secret) throws BaseException { + log.info("获取accessToken,appid:{}", appId.substring(appId.length() - 4)); + Object obj = util.redisUtil.get(WxConstant.ACCESS_TOKEN + appId); + if (obj == null || StrUtil.isBlank((String) obj)) { + WxAccessToken wxAccessToken; + String url = String.format(WxConstant.URL_GET_ACCESS_TOKEN, appId, secret); + String response = HttpRequest.get(url).execute().body(); + log.info("getAccessToken: {}", response); + try { + if (StrUtil.isEmpty(response) || null == (wxAccessToken = JacksonUtil.jsonToBean(response, WxAccessToken.class))) { + throw new BaseException(WxCodeError.WX_HTTP_ERROR); + } + } catch (IOException e) { + throw new BaseException(e.getMessage()); + } + + if (null != wxAccessToken.getErrcode()) { + throw new BaseException(wxAccessToken.getErrcode(), wxAccessToken.getErrmsg()); + } + if (StrUtil.isEmpty(wxAccessToken.getAccessToken())) { + throw new BaseException(WxCodeError.ACCESS_TOKEN_ERROR); + } + util.redisUtil.set(WebConstant.Wx.ACCESS_TOKEN + appId, wxAccessToken.getAccessToken(), WebConstant.Wx.EXPIRE_TIME); + log.info("存储access_token:{}", wxAccessToken.getAccessToken()); + return wxAccessToken.getAccessToken(); + } + log.info("读取reids的token:{}", obj); + return (String) obj; + } +} diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/service/WxMessageService.java b/wechatutil/src/main/java/com/ccsens/wechatutil/wxenterprise/EnterpriseRobotUtil.java similarity index 84% rename from wechatutil/src/main/java/com/ccsens/wechatutil/service/WxMessageService.java rename to wechatutil/src/main/java/com/ccsens/wechatutil/wxenterprise/EnterpriseRobotUtil.java index 4c2c36bd..c06d0efc 100644 --- a/wechatutil/src/main/java/com/ccsens/wechatutil/service/WxMessageService.java +++ b/wechatutil/src/main/java/com/ccsens/wechatutil/wxenterprise/EnterpriseRobotUtil.java @@ -1,13 +1,10 @@ -package com.ccsens.wechatutil.service; +package com.ccsens.wechatutil.wxenterprise; import cn.hutool.core.collection.CollectionUtil; import com.ccsens.util.JacksonUtil; import com.ccsens.wechatutil.bean.dto.WxMessageDto; import com.ccsens.wechatutil.util.WxConstant; import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Propagation; -import org.springframework.transaction.annotation.Transactional; import java.io.*; import java.net.URL; @@ -18,17 +15,13 @@ import java.nio.charset.StandardCharsets; * @author 逗 */ @Slf4j -@Service -@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) -public class WxMessageService implements IWxMessageService { - +public class EnterpriseRobotUtil { /** * 微信机器人 * @param robotMessage 机器人消息 * @throws Exception 异常 */ - @Override - public void sendRobotInfo(WxMessageDto.RobotMessage robotMessage)throws Exception { + public static void sendRobotInfo(WxMessageDto.RobotMessage robotMessage)throws Exception { WxMessageDto.WxRobotVo wxRobotVo = new WxMessageDto.WxRobotVo(); wxRobotVo.setMsgtype(robotMessage.getMsgType()); if(WxConstant.TEXT.equalsIgnoreCase(robotMessage.getMsgType())){ @@ -87,5 +80,4 @@ public class WxMessageService implements IWxMessageService { } } } - } diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/wxmini/MiniCode.java b/wechatutil/src/main/java/com/ccsens/wechatutil/wxmini/MiniCode.java new file mode 100644 index 00000000..0f07aa0a --- /dev/null +++ b/wechatutil/src/main/java/com/ccsens/wechatutil/wxmini/MiniCode.java @@ -0,0 +1,151 @@ +package com.ccsens.wechatutil.wxmini; + +import com.ccsens.util.HttpsUtil; +import com.ccsens.util.JacksonUtil; +import com.ccsens.util.exception.BaseException; +import com.ccsens.wechatutil.bean.dto.WechatCode; +import com.ccsens.wechatutil.bean.po.WxBaseEntity; +import com.ccsens.wechatutil.util.WxCodeError; +import com.ccsens.wechatutil.util.WxConstant; +import com.ccsens.wechatutil.wxcommon.WxCommonUtil; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; + +import java.io.*; + +/** + * @author 逗 + */ +@Slf4j +public class MiniCode { + + @Value("${mini.appId:}") + private static String miniAppId; + @Value("${mini.secret:}") + private static String miniSecret; + + /** + * 获取小程序码--方案A,可接受 path 参数较长,生成个数受限 + * 接口 A 加上接口 C,总共生成的码数量限制为 100,000,请谨慎调用。 + * 使用默认appId + * @param wechatCodeA 传入参数 + * @param path 小程序码存储位置 + */ + public static void getWxCodeA(WechatCode.WechatCodeA wechatCodeA, String path)throws Exception { + getWxCodeA(wechatCodeA,path,miniAppId,miniSecret); + } + + /** + * 获取小程序码--方案A,可接受 path 参数较长,生成个数受限 + * 接口 A 加上接口 C,总共生成的码数量限制为 100,000,请谨慎调用。 + * @param wechatCodeA 传入参数 + * @param path 小程序码存储位置 + * @param appId appId + * @param secret secret + */ + public static void getWxCodeA(WechatCode.WechatCodeA wechatCodeA, String path, String appId, String secret) throws Exception { + String url = String.format(WxConstant.URL_GET_WX_CODE_A, WxCommonUtil.getAccessToken(appId, secret)); + log.info("调用生成二维码路径和accessToken:{}", url); + String postStr = JacksonUtil.beanToJson(wechatCodeA); + log.info("二维码的参数:{}", postStr); + //调用微信接口在指定位置生成图片 + httpWxCode(path, url, postStr); + } + + /** + * 获取小程序码--方案B,可接受页面参数较短,生成个数不受限。 + * 接口 B 调用分钟频率受限(5000次/分钟),如需大量小程序码,建议预生成 + * 使用默认appId + * @param wechatCodeB 传入参数 + * @param path 小程序码存储位置 + */ + public static void getWxCodeB(WechatCode.WechatCodeB wechatCodeB, String path)throws Exception { + getWxCodeB(wechatCodeB,path,miniAppId, miniSecret); + } + + /** + * 获取小程序码--方案B,可接受页面参数较短,生成个数不受限。 + * 接口 B 调用分钟频率受限(5000次/分钟),如需大量小程序码,建议预生成 + * @param wechatCodeB 传入参数 + * @param path 小程序码存储位置 + * @param appId appId + * @param secret secret + */ + public static void getWxCodeB(WechatCode.WechatCodeB wechatCodeB, String path, String appId, String secret) throws Exception { + String url = String.format(WxConstant.URL_GET_WX_CODE_B, WxCommonUtil.getAccessToken(appId, secret)); + log.info("调用生成二维码路径和accessToken:{}", url); + String postStr = JacksonUtil.beanToJson(wechatCodeB); + log.info("二维码的参数:{}", postStr); + //调用微信接口在指定位置生成图片 + httpWxCode(path, url, postStr); + } + + /** + * 方案C-生成小程序码(二维码),可接受 path 参数较长,生成个数受限,数量限制见 + * 接口 A 加上接口 C,总共生成的码数量限制为 100,000,请谨慎调用。 + * 使用默认appId + * @param wechatCodeC 传入参数 + * @param path 小程序码存储位置 + */ + public static void getWxCodeC(WechatCode.WechatCodeC wechatCodeC, String path) throws Exception { + getWxCodeC(wechatCodeC,path,miniAppId, miniSecret); + } + + /** + * 方案C-生成小程序码(二维码),可接受 path 参数较长,生成个数受限,数量限制见 + * 接口 A 加上接口 C,总共生成的码数量限制为 100,000,请谨慎调用。 + * @param wechatCodeC 传入参数 + * @param path 小程序码存储位置 + * @param appId appId + * @param secret secret + */ + public static void getWxCodeC(WechatCode.WechatCodeC wechatCodeC, String path, String appId, String secret) throws Exception { + String url = String.format(WxConstant.URL_GET_WX_CODE_C, WxCommonUtil.getAccessToken(appId, secret)); + log.info("调用生成二维码路径和accessToken:{}", url); + String postStr = JacksonUtil.beanToJson(wechatCodeC); + log.info("二维码的参数:{}", postStr); + //调用微信接口在指定位置生成图片 + httpWxCode(path, url, postStr); + } + + /** + * 调用微信的接口在指定位置生成二维码 + * @param path 图片储存位置 + * @param url 微信接口路径 + * @param postStr 传入参数 + * @throws Exception 异常 + */ + public static void httpWxCode(String path, String url, String postStr) throws Exception { + WxBaseEntity wxBaseEntity; + byte[] response = HttpsUtil.httpsRequestByte(url, "POST", postStr); + + if(response.length == 0){ + throw new BaseException(WxCodeError.WX_HTTP_ERROR); + } + try { + if (null == (wxBaseEntity = JacksonUtil.jsonToBean(new String(response), WxBaseEntity.class))) { + throw new BaseException(WxCodeError.WX_HTTP_ERROR); + } + if (null != wxBaseEntity.getErrcode()) { + throw new BaseException(wxBaseEntity.getErrcode(), wxBaseEntity.getErrmsg()); + } + } catch (IOException e) { + // 从输入流读取返回内容 + File file = new File(path); + if (!file.getParentFile().exists()) { + file.getParentFile().mkdirs(); + } + InputStream inputStream = new ByteArrayInputStream(response); + BufferedInputStream bis = new BufferedInputStream(inputStream); + OutputStream os = new FileOutputStream(file); + int len; + byte[] arr = new byte[1024]; + while ((len = bis.read(arr)) != -1) + { + os.write(arr, 0, len); + os.flush(); + } + os.close(); + } + } +} diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/wxmini/MiniMessage.java b/wechatutil/src/main/java/com/ccsens/wechatutil/wxmini/MiniMessage.java new file mode 100644 index 00000000..2879e00d --- /dev/null +++ b/wechatutil/src/main/java/com/ccsens/wechatutil/wxmini/MiniMessage.java @@ -0,0 +1,82 @@ +package com.ccsens.wechatutil.wxmini; + +import com.ccsens.util.HttpsUtil; +import com.ccsens.wechatutil.bean.dto.WxMessageDto; +import com.ccsens.wechatutil.util.WxConstant; +import com.ccsens.wechatutil.wxcommon.WxCommonUtil; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; + +import java.util.List; + +/** + * @author 逗 + */ +@Slf4j +public class MiniMessage { + + @Value("${mini.appId:}") + private static String miniAppId; + @Value("${mini.secret:}") + private static String miniSecret; + + /** + * 发送微信订阅消息 (使用默认appId) + * + * @param notifyType 通知类型 + * @param toUser 用户openid + * @param page 小程序页面路径 + * @param params 小程序模板数据 + */ + public static boolean sendSubcribeMsg(WxConstant.Packet_Notify_Type notifyType, String toUser, String page, List params) throws Exception { + return sendSubcribeMsg(notifyType,toUser,page,params,miniAppId,miniSecret); + } + + /** + * 发送微信订阅消息 + * + * @param notifyType 通知类型 + * @param toUser 用户openid + * @param page 小程序页面路径 + * @param params 小程序模板数据 + */ + public static boolean sendSubcribeMsg(WxConstant.Packet_Notify_Type notifyType, String toUser, String page, List params,String appId, String secret) throws Exception { + String ret = null; + String url = String.format(WxConstant.URL_SEND_SUBSCRIBE_MESSAGE, WxCommonUtil.getAccessToken(appId, secret)); + switch (notifyType) { + //订单支付成功通知 + case Buy: { + WxMessageDto.SubscribeEntity t = new WxMessageDto.SubscribeEntity<>(); + t.setTouser(toUser); + t.setTemplate_id(WxConstant.SUBSCRIBE_MSG_ID_BUY); + t.setPage(page); + t.setData(new WxMessageDto.ReceiveSubscriBuyData(params)); + System.out.println(com.ccsens.wechatutil.payutil.JacksonUtil.beanToJson(t)); + ret = HttpsUtil.httpsRequest(url, "POST", com.ccsens.wechatutil.payutil.JacksonUtil.beanToJson(t)); + break; + } + //订单发货 + case ReceiveSubscriBuyData: { + WxMessageDto.SubscribeEntity t = new WxMessageDto.SubscribeEntity<>(); + t.setTouser(toUser); + t.setTemplate_id(WxConstant.SUBSCRIBE_MSG_ID_ORDERSEND); + t.setData(new WxMessageDto.ReceiveSubscriOrderSendData(params)); + System.out.println(com.ccsens.wechatutil.payutil.JacksonUtil.beanToJson(t)); + ret = HttpsUtil.httpsRequest(url, "POST", com.ccsens.wechatutil.payutil.JacksonUtil.beanToJson(t)); + break; + } + default: { + break; + } + } + //ok: {"errcode":0,"errmsg":"ok"} + //err: {"errcode":43101,"errmsg":"user refuse to accept the msg hint: [V_GEdA02503942]"} + System.out.println("Send Subscribe Message:" + ret); + String errCode = com.ccsens.wechatutil.payutil.JacksonUtil.getJsonValue(ret, "errcode"); + System.out.println(errCode); + return "0".equals(errCode); + } + + + +} diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/wxmini/MiniSigninUtil.java b/wechatutil/src/main/java/com/ccsens/wechatutil/wxmini/MiniSigninUtil.java new file mode 100644 index 00000000..e58e443a --- /dev/null +++ b/wechatutil/src/main/java/com/ccsens/wechatutil/wxmini/MiniSigninUtil.java @@ -0,0 +1,70 @@ +package com.ccsens.wechatutil.wxmini; + +import cn.hutool.core.util.StrUtil; +import cn.hutool.http.HttpRequest; +import com.ccsens.util.HttpsUtil; +import com.ccsens.util.JacksonUtil; +import com.ccsens.util.exception.BaseException; +import com.ccsens.wechatutil.bean.dto.WechatCode; +import com.ccsens.wechatutil.bean.dto.WxMessageDto; +import com.ccsens.wechatutil.bean.po.MiniProgramUser; +import com.ccsens.wechatutil.bean.po.WxBaseEntity; +import com.ccsens.wechatutil.util.WxCodeError; +import com.ccsens.wechatutil.util.WxConstant; +import com.ccsens.wechatutil.wxcommon.WxCommonUtil; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; + +import java.io.*; +import java.util.List; + +/** + * @author 逗 + */ +@Slf4j +public class MiniSigninUtil { + + @Value("${mini.appId:}") + private static String miniAppId; + @Value("${mini.secret:}") + private static String miniSecret; + + /** + * 小程序登录 + * -- 从配置文件中获取默认appId + * 配置文件内的名称 h5.appId: 和 h5.secret: + * @param code code + * @return 返回当前用户的openId等 + */ + public static MiniProgramUser signinByMini(String code) { + return signinByMini(code, miniAppId, miniSecret); + } + /** + * 小程序登录 -- 传入appId + * @param code code + * @param appId appId + * @param secret secret + * @return 返回当前用户的openId等 + */ + public static MiniProgramUser signinByMini(String code, String appId, String secret) { + MiniProgramUser wxUser; + //拼接wx的访问的路径 + String url = String.format(WxConstant.MINI_PROGRAM_LOGIN, appId, secret, code, WxConstant.GRANT_TYPE); + //调用微信的接口 + String response = HttpRequest.get(url).execute().body(); + log.info("url: {}\nresponse: {}", url, response); + try { + if (StrUtil.isEmpty(response) || null == (wxUser = JacksonUtil.jsonToBean(response, MiniProgramUser.class))) { + throw new BaseException(WxCodeError.WX_HTTP_ERROR); + } + } catch (IOException e) { + throw new BaseException(e.getMessage()); + } + if (null != wxUser.getErrcode()) { + throw new BaseException(wxUser.getErrcode(), wxUser.getErrmsg()); + } + return wxUser; + } + + +} diff --git a/wechatutil/src/main/java/com/ccsens/wechatutil/wxofficial/OfficialAccountSigninUtil.java b/wechatutil/src/main/java/com/ccsens/wechatutil/wxofficial/OfficialAccountSigninUtil.java new file mode 100644 index 00000000..55d3c834 --- /dev/null +++ b/wechatutil/src/main/java/com/ccsens/wechatutil/wxofficial/OfficialAccountSigninUtil.java @@ -0,0 +1,96 @@ +package com.ccsens.wechatutil.wxofficial; + +import cn.hutool.core.util.StrUtil; +import cn.hutool.http.HttpRequest; +import com.ccsens.util.DateUtil; +import com.ccsens.util.JacksonUtil; +import com.ccsens.util.exception.BaseException; +import com.ccsens.wechatutil.bean.po.WxOauth2AccessToken; +import com.ccsens.wechatutil.bean.po.WxOauth2UserInfo; +import com.ccsens.wechatutil.util.WxCodeError; +import com.ccsens.wechatutil.util.WxConstant; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; + +import java.io.IOException; + +/** + * @author 逗 + */ +@Slf4j +public class OfficialAccountSigninUtil { + + @Value("${h5.appId:}") + private static String appIdH5; + @Value("${h5.secret:}") + private static String secretH5; + + public static WxOauth2UserInfo signinByH5(String code) { + return signinByH5(code, appIdH5, secretH5); + } + + public static WxOauth2UserInfo signinByH5(String code, String appId, String secret) { + //获取accessToken + WxOauth2AccessToken wxOauth2AccessToken = getOauth2AccessToken(code, appId, secret); + //获取用户信息 + return getOauth2UserInfo(wxOauth2AccessToken.getAccessToken(), wxOauth2AccessToken.getOpenId()); + } + + /** + * 获取网页授权凭证 + * @param code OAuth2授权码 + * @return WxOauth2AccessToken + */ + private static WxOauth2AccessToken getOauth2AccessToken(String code, String appId, String secret) { + WxOauth2AccessToken wxOauth2AccessToken; + //拼接访问路径 + String url = String.format(WxConstant.URL_GET_OAUTH2_ACCESS_TOKEN, appId, secret, code); + //调用微信接口 + String response = HttpRequest.get(url).execute().body(); + log.info("url: {}\nresponse: {}", url, response); + try { + if (StrUtil.isEmpty(response) || null == (wxOauth2AccessToken = JacksonUtil.jsonToBean(response, WxOauth2AccessToken.class))) { + throw new BaseException(WxCodeError.WX_HTTP_ERROR); + } + } catch (IOException e) { + throw new BaseException(e.getMessage()); + } + if (null != wxOauth2AccessToken.getErrcode()) { + throw new BaseException(wxOauth2AccessToken.getErrcode(), wxOauth2AccessToken.getErrmsg()); + } + if (StrUtil.isEmpty(wxOauth2AccessToken.getAccessToken())) { + throw new BaseException(WxCodeError.ACCESS_TOKEN_ERROR); + } + wxOauth2AccessToken.setCreatedAt(DateUtil.currentSeconds()); + return wxOauth2AccessToken; + } + + /** + * 通过网页授权accessToken获取用户信息 + * @param accessToken 网页授权接口调用凭证 + * @param openId 用户标识 + * @return SNSUserInfo + */ + private static WxOauth2UserInfo getOauth2UserInfo(String accessToken, String openId) { + WxOauth2UserInfo wxOauth2UserInfo; + //拼接访问路径 + String url = String.format(WxConstant.URL_GET_OAUTH2_USER_INFO, accessToken, openId); + //调用微信接口 + String response = HttpRequest.get(url).execute().body(); + log.info("url: {}\nresponse: {}", url, response); + try { + if (StrUtil.isEmpty(response) || null == (wxOauth2UserInfo = JacksonUtil.jsonToBean(response, WxOauth2UserInfo.class))) { + throw new BaseException(WxCodeError.WX_HTTP_ERROR); + } + } catch (IOException e) { + throw new BaseException(e.getMessage()); + } + if (null != wxOauth2UserInfo.getErrcode()) { + throw new BaseException(wxOauth2UserInfo.getErrcode(), wxOauth2UserInfo.getErrmsg()); + } + if (StrUtil.isEmpty(wxOauth2UserInfo.getOpenId())) { + throw new BaseException(WxCodeError.OPENID_ERROR); + } + return wxOauth2UserInfo; + } +}