Prechádzať zdrojové kódy

添加消息推送公众号的接口

yq 3 rokov pred
rodič
commit
42a241d491

+ 24 - 90
src/main/java/com/usky/dxtop/controller/web/WxController.java

@@ -1,24 +1,16 @@
 package com.usky.dxtop.controller.web;
 
-import com.alibaba.fastjson.JSON;
-import com.alibaba.fastjson.JSONObject;
-import com.usky.dxtop.common.core.redis.RedisCache;
-import com.usky.dxtop.common.exception.CustomException;
-import com.usky.dxtop.common.utils.Assert;
-import com.usky.dxtop.common.utils.http.HttpUtils;
-import com.usky.dxtop.common.utils.sign.Sha1;
-import com.usky.dxtop.common.utils.uuid.UUID;
 import com.usky.dxtop.service.api.TopApiConfiger;
+import com.usky.dxtop.service.api.WxApi;
 import lombok.extern.slf4j.Slf4j;
-import org.apache.commons.lang3.StringUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.RequestParam;
 import org.springframework.web.bind.annotation.RestController;
 
-import java.util.Objects;
+import java.util.HashMap;
+import java.util.Map;
 import java.util.TreeMap;
-import java.util.concurrent.TimeUnit;
 
 /**
  * @author yq
@@ -28,102 +20,44 @@ import java.util.concurrent.TimeUnit;
 @RestController
 public class WxController {
 
-    private static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";
-
-    private static final String GET_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";
-
-    private static final String GET_TICKET_URL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
-
-    private static final String WX_TOKEN_KEY = "wxTokenKey";
-
-    private static final String WX_TICKET_KEY = "wxTicketKey";
-
-
     @Autowired
     private TopApiConfiger topApiConfiger;
 
     @Autowired
-    private RedisCache redisCache;
+    private WxApi wxApi;
     @GetMapping("/wxLogin")
     public String wxLogin(@RequestParam String jsCode){
-        TreeMap<String, String> treeMap = new TreeMap<>();
-        treeMap.put("appid", topApiConfiger.wxAppId);
-        treeMap.put("secret", topApiConfiger.wxAppSecret);
-        treeMap.put("js_code", jsCode);
-        treeMap.put("grant_type", "authorization_code");
-        String result = HttpUtils.sendGet(WX_LOGIN_URL, topApiConfiger.joinParam(treeMap),null);
-        JSONObject obj= JSON.parseObject(result);
-        log.info("获取到的相应"+obj);
-        String openId = "";
-        if (null == obj.get("errcode")){
-            openId = obj.get("openid").toString();
-        }else {
-            throw new CustomException(String.format("登录异常:code:%s,message:%s",obj.get("errcode"),obj.get("errmsg")));
-        }
-        return openId;
+        return wxApi.wxLogin(topApiConfiger.getWxAppId(),topApiConfiger.getWxAppSecret(),jsCode);
     }
 
+    /**
+     * 拉起支付
+     * @param url
+     * @return
+     */
     @GetMapping("/wxAccToken")
     public TreeMap<String, String> getAccToken(@RequestParam String url){
-        TreeMap<String, String> treeMap = new TreeMap<>();
-        treeMap.put("appid", topApiConfiger.wxAppId);
-        String currentTimeMillis = String.valueOf(System.currentTimeMillis());
-        treeMap.put("timeStamp",currentTimeMillis);
-        String noncestr = UUID.randomUUID().toString(true);
-        treeMap.put("nonceStr", noncestr);
-
-        String ticket = getTicket(getToken());
-        //验签参数
-        TreeMap<String, String> signMap = new TreeMap<>();
-        signMap.put("jsapi_ticket",ticket);
-        signMap.put("noncestr",noncestr);
-        signMap.put("timestamp",currentTimeMillis);
-        signMap.put("url",url);
-        String joinParam = topApiConfiger.joinParam(signMap);
-        treeMap.put("signature", Sha1.getSha1(joinParam));
-        return treeMap;
+        return wxApi.getPayParam(topApiConfiger.getWxAppId(),topApiConfiger.getWxAppSecret(),url);
     }
 
     /**
      * 获取token
      * @return
      */
-    public String getToken(){
-        Object cacheObject = redisCache.getCacheObject(WX_TOKEN_KEY);
-        if (!Objects.isNull(cacheObject)){
-            return cacheObject.toString();
-        }
-        TreeMap<String,String> tokenMap = new TreeMap<>();
-        tokenMap.put("grant_type","client_credential");
-        tokenMap.put("appid",topApiConfiger.getWxAppId());
-        tokenMap.put("secret",topApiConfiger.getWxAppSecret());
-        String token = HttpUtils.sendGet(GET_TOKEN_URL, topApiConfiger.joinParam(tokenMap), null);
-        Assert.check(StringUtils.isNotBlank(token),"获取微信token异常");
-        JSONObject obj= JSON.parseObject(token);
-        if (null != obj.get("errcode")){
-            throw new CustomException(obj.get("errmsg").toString());
+    @GetMapping("/accentToken")
+    public String getToken(@RequestParam Integer type){
+        if (1 == type){
+            return wxApi.getToken(topApiConfiger.getWxAppId(),topApiConfiger.getWxAppSecret());
+        }else {
+            return wxApi.getToken(WxApi.APP_ID,WxApi.SECRET);
         }
-        String s = obj.get("access_token").toString();
-        redisCache.setCacheObject(WX_TOKEN_KEY, s, 7200, TimeUnit.MINUTES);
-        return s;
     }
-
-    public String getTicket(String token){
-        Object cacheObject = redisCache.getCacheObject(WX_TICKET_KEY);
-        if (!Objects.isNull(cacheObject)){
-            return cacheObject.toString();
-        }
-        TreeMap<String,String> ticketMap = new TreeMap<>();
-        ticketMap.put("access_token",token);
-        ticketMap.put("type","jsapi");
-        String ticket = HttpUtils.sendGet(GET_TICKET_URL, topApiConfiger.joinParam(ticketMap), null);
-        Assert.check(StringUtils.isNotBlank(ticket),"获取时间异常");
-        JSONObject obj= JSON.parseObject(ticket);
-        if (!"0".equals(obj.get("errcode").toString())){
-            throw new CustomException(obj.get("errmsg").toString());
-        }
-        String s = obj.get("ticket").toString();
-        redisCache.setCacheObject(WX_TICKET_KEY, s, 7200, TimeUnit.MINUTES);
-        return s;
+    @GetMapping("/testt")
+    public String sendMessageTest(String openId){
+        Map<String, Object> map = new HashMap<>();
+        Map<String, Object> firstMap = new HashMap<>();
+        firstMap.put("value","支付成功");
+        map.put("first",firstMap);
+        return wxApi.sendMessageApi(openId,map,wxApi.getToken(WxApi.APP_ID,WxApi.SECRET));
     }
 }

+ 9 - 0
src/main/java/com/usky/dxtop/model/Staff.java

@@ -151,5 +151,14 @@ public class Staff implements Serializable {
      */
     private BigDecimal balance;
 
+    /**
+     * 人员类型
+     */
+    private String type;
+    /**
+     * openId
+     */
+    private String openId;
+
 
 }

+ 192 - 0
src/main/java/com/usky/dxtop/service/api/WxApi.java

@@ -0,0 +1,192 @@
+package com.usky.dxtop.service.api;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
+import com.usky.dxtop.common.core.redis.RedisCache;
+import com.usky.dxtop.common.exception.CustomException;
+import com.usky.dxtop.common.utils.Assert;
+import com.usky.dxtop.common.utils.http.HttpUtils;
+import com.usky.dxtop.common.utils.sign.Sha1;
+import com.usky.dxtop.common.utils.uuid.UUID;
+import lombok.Data;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * @author yq
+ * @date 2022/2/25 15:10
+ */
+@Data
+@Component
+public class WxApi {
+
+    @Autowired
+    private RedisCache redisCache;
+
+    /**
+     * 获取token的url
+     */
+    private static final String GET_TOKEN = "https://api.weixin.qq.com/cgi-bin/token";
+
+    /**
+     * 发送消息
+     */
+    private static final String SEND_MESSAGE = "https://api.weixin.qq.com/cgi-bin/message/template/send";
+    /**
+     * 登录
+     */
+    private static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";
+    /**
+     * 获取ticket
+     */
+    private static final String GET_TICKET_URL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
+
+
+    public static final String APP_ID = "wxd64360a4b8c50006";
+
+    public static final String SECRET = "b758e45c89162542610509dafd9db7c3";
+    /**
+     * 模版id
+     */
+    private static final String TEMPLATE_ID = "Eps4guetElB_6uzu-AYvvGM4xc9LwO7UnEwxNwn0ZFE";
+    /**
+     * 公众号的key
+     */
+    public static final String ACCESS_TOKEN = "access_token";
+
+    private static final String WX_TICKET_KEY = "wxTicketKey";
+
+    /**
+     * 小程序登录
+     * @param appId
+     * @param wxAppSecret
+     * @param jsCode
+     * @return
+     */
+    public String wxLogin(String appId,String wxAppSecret,String jsCode){
+        TreeMap<String, String> treeMap = new TreeMap<>();
+        treeMap.put("appid", appId);
+        treeMap.put("secret", wxAppSecret);
+        treeMap.put("js_code", jsCode);
+        treeMap.put("grant_type", "authorization_code");
+        String result = HttpUtils.sendGet(WX_LOGIN_URL, joinParam(treeMap),null);
+        JSONObject obj= JSON.parseObject(result);
+        String openId = "";
+        if (null == obj.get("errcode")){
+            openId = obj.get("openid").toString();
+        }else {
+            throw new CustomException(String.format("登录异常:code:%s,message:%s",obj.get("errcode"),obj.get("errmsg")));
+        }
+        return openId;
+    }
+
+
+    public String sendMessageApi(String openId,Object data,String token){
+        String url = String.format("%s%s%s", SEND_MESSAGE, "?access_token=", token);
+        Map<String,Object> map = new HashMap<>();
+        map.put("touser",openId);
+        map.put("template_id",TEMPLATE_ID);
+        map.put("data",data);
+        String result = HttpUtils.sendPost(url, JSONObject.toJSONString(map), null);
+        JSONObject jsonObject = JSONObject.parseObject(result);
+        return jsonObject.toJSONString();
+
+    }
+
+    /**
+     * 获取token
+     * @param appId
+     * @param appSecret
+     * @return
+     */
+    public String getToken(String appId,String appSecret){
+        Object cacheObject = redisCache.getCacheObject(appId+ACCESS_TOKEN);
+        if (!Objects.isNull(cacheObject)){
+            return cacheObject.toString();
+        }
+        TreeMap<String,String> tokenMap = new TreeMap<>();
+        tokenMap.put("grant_type","client_credential");
+        tokenMap.put("appid",appId);
+        tokenMap.put("secret",appSecret);
+        String token = HttpUtils.sendGet(GET_TOKEN, joinParam(tokenMap), null);
+        Assert.check(StringUtils.isNotBlank(token),"获取微信token异常");
+        JSONObject obj= JSON.parseObject(token);
+        if (null != obj.get("errcode")){
+            throw new CustomException(obj.get("errmsg").toString());
+        }
+        String s = obj.get("access_token").toString();
+        redisCache.setCacheObject(appId+ACCESS_TOKEN, s, 7200, TimeUnit.MINUTES);
+        return s;
+    }
+
+    /**
+     * 获取ticket
+     * @param token
+     * @return
+     */
+    public String getTicket(String token){
+        Object cacheObject = redisCache.getCacheObject(WX_TICKET_KEY);
+        if (!Objects.isNull(cacheObject)){
+            return cacheObject.toString();
+        }
+        TreeMap<String,String> ticketMap = new TreeMap<>();
+        ticketMap.put("access_token",token);
+        ticketMap.put("type","jsapi");
+        String ticket = HttpUtils.sendGet(GET_TICKET_URL, joinParam(ticketMap), null);
+        Assert.check(StringUtils.isNotBlank(ticket),"获取时间异常");
+        JSONObject obj= JSON.parseObject(ticket);
+        if (!"0".equals(obj.get("errcode").toString())){
+            throw new CustomException(obj.get("errmsg").toString());
+        }
+        String s = obj.get("ticket").toString();
+        redisCache.setCacheObject(WX_TICKET_KEY, s, 7200, TimeUnit.MINUTES);
+        return s;
+    }
+
+    /**
+     * 获取支付参数
+     * @param url
+     * @return
+     */
+    public TreeMap<String, String> getPayParam(String wxAppId,String secret,String url){
+        TreeMap<String, String> treeMap = new TreeMap<>();
+        treeMap.put("appid", wxAppId);
+        String currentTimeMillis = String.valueOf(System.currentTimeMillis());
+        treeMap.put("timeStamp",currentTimeMillis);
+        String noncestr = UUID.randomUUID().toString(true);
+        treeMap.put("nonceStr", noncestr);
+
+        String ticket = getTicket(getToken(wxAppId,secret));
+        //验签参数
+        TreeMap<String, String> signMap = new TreeMap<>();
+        signMap.put("jsapi_ticket",ticket);
+        signMap.put("noncestr",noncestr);
+        signMap.put("timestamp",currentTimeMillis);
+        signMap.put("url",url);
+        String joinParam = joinParam(signMap);
+        treeMap.put("signature", Sha1.getSha1(joinParam));
+        return treeMap;
+    }
+
+
+
+    public static String joinParam(TreeMap<String, String> params){
+        StringBuilder buf = new StringBuilder();
+        for (Map.Entry<String, String> entry : params.entrySet()) {
+            if (!com.usky.dxtop.common.utils.StringUtils.isBlank(entry.getValue()) && !"sign".equals(entry.getKey())) {
+                buf.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
+            }
+        }
+        String changeBuf = buf.toString();
+        return changeBuf.substring(0, changeBuf.length() - 1);
+    }
+
+
+}

+ 13 - 0
src/main/java/com/usky/dxtop/service/listener/ChargeTransMqListener.java

@@ -1,10 +1,12 @@
 package com.usky.dxtop.service.listener;
 
 import com.alibaba.fastjson.JSONObject;
+import com.usky.dxtop.common.utils.StringUtils;
 import com.usky.dxtop.model.Charge;
 import com.usky.dxtop.model.Staff;
 import com.usky.dxtop.service.ChargeService;
 import com.usky.dxtop.service.StaffService;
+import com.usky.dxtop.service.api.WxApi;
 import com.usky.dxtop.service.config.rabbitmq.ChargeTransConfig;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.amqp.core.Message;
@@ -13,6 +15,8 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
 import java.nio.charset.StandardCharsets;
+import java.util.HashMap;
+import java.util.Map;
 
 /**
  * @author yq
@@ -28,6 +32,8 @@ public class ChargeTransMqListener {
     @Autowired
     private StaffService staffService;
 
+    @Autowired
+    private WxApi wxApi;
     @RabbitListener(queues = ChargeTransConfig.NAME, containerFactory = ChargeTransConfig.LISTENER)
     public void dealDeclareMessage(Message message) {
         try {
@@ -42,6 +48,13 @@ public class ChargeTransMqListener {
             Staff staff = staffService.one(null, null, charge.getCard());
             staff.setBalance(charge.getBalance());
             staffService.updateById(staff);
+            if (StringUtils.isNotBlank(staff.getOpenId())){
+                Map<String, Object> map = new HashMap<>();
+                Map<String, Object> firstMap = new HashMap<>();
+                firstMap.put("value","支付成功");
+                map.put("first",firstMap);
+                wxApi.sendMessageApi(staff.getOpenId(),map,wxApi.getToken(WxApi.APP_ID,WxApi.SECRET));
+            }
         } catch (Exception e) {
             log.info("charge_trans_produce"+"异常信息:" + e.getMessage());
         } finally {

+ 13 - 0
src/main/java/com/usky/dxtop/service/listener/DishTransMqListener.java

@@ -1,10 +1,12 @@
 package com.usky.dxtop.service.listener;
 
 import com.alibaba.fastjson.JSONObject;
+import com.usky.dxtop.common.utils.StringUtils;
 import com.usky.dxtop.model.Dish;
 import com.usky.dxtop.model.Staff;
 import com.usky.dxtop.service.DishService;
 import com.usky.dxtop.service.StaffService;
+import com.usky.dxtop.service.api.WxApi;
 import com.usky.dxtop.service.config.rabbitmq.DishTransConfig;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.amqp.core.Message;
@@ -13,6 +15,8 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
 import java.nio.charset.StandardCharsets;
+import java.util.HashMap;
+import java.util.Map;
 
 /**
  * @author yq
@@ -26,6 +30,8 @@ public class DishTransMqListener {
     private DishService dishService;
     @Autowired
     private StaffService staffService;
+    @Autowired
+    private WxApi wxApi;
     @RabbitListener(queues = DishTransConfig.NAME, containerFactory = DishTransConfig.LISTENER)
     public void dealDeclareMessage(Message message) {
         try {
@@ -41,6 +47,13 @@ public class DishTransMqListener {
             Staff staff = staffService.one(null, null, dish.getCard());
             staff.setBalance(dish.getBalance());
             staffService.updateById(staff);
+            if (StringUtils.isNotBlank(staff.getOpenId())){
+                Map<String, Object> map = new HashMap<>();
+                Map<String, Object> firstMap = new HashMap<>();
+                firstMap.put("value","消费成功");
+                map.put("first",firstMap);
+                wxApi.sendMessageApi(staff.getOpenId(),map,wxApi.getToken(WxApi.APP_ID,WxApi.SECRET));
+            }
         } catch (Exception e) {
             log.info("dish_trade_produce"+"异常信息:" + e.getMessage());
         }

+ 5 - 6
src/test/java/com/usky/dxtop/SmApiTest.java

@@ -1,7 +1,7 @@
 package com.usky.dxtop;
 
-import com.usky.dxtop.model.MsgLog;
 import com.usky.dxtop.service.MsgLogService;
+import com.usky.dxtop.service.job.SmJob;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -19,12 +19,11 @@ public class SmApiTest {
 
     @Autowired
     private MsgLogService msgLogService;
+
+    @Autowired
+    private SmJob smJob;
     @Test
     public void test1(){
-        MsgLog msgLog = new MsgLog();
-        msgLog.setId(System.currentTimeMillis());
-        msgLog.setMsg("222222222222222");
-        msgLog.setBusinessId("2222");
-        msgLogService.addOrUpdate(msgLog);
+        smJob.personApi(null);
     }
 }