Przeglądaj źródła

feat : 代码修改

bilingfeng 2 lat temu
rodzic
commit
6c7ea2e11e

+ 2 - 7
game-module/game-sdk/src/main/java/com/zanxiang/sdk/constant/RedisKeyConstant.java

@@ -43,13 +43,8 @@ public class RedisKeyConstant {
     public static final String ROLE_UPDATE_KEY = RedisKeyConstant.REDIS_PREFIX + "role_update";
 
     /**
-     * 微信ACCESS_TOKEN key
+     * 小程序token
      */
-    public static final String WEIXIN_ACCESS_TOKEN = RedisKeyConstant.REDIS_PREFIX + "access_token_";
-
-    /**
-     * 微信ACCESS_TOKEN key
-     */
-    public static final String WEIXIN_OPEN_ID = RedisKeyConstant.REDIS_PREFIX + "open_id_";
+    public static final String APPLET_ACCESS_TOKEN = RedisKeyConstant.REDIS_PREFIX + "applet_access_token_";
 
 }

+ 2 - 2
game-module/game-sdk/src/main/java/com/zanxiang/sdk/controller/AppletController.java

@@ -39,8 +39,8 @@ public class AppletController {
     @ApiResponses(value = {@ApiResponse(code = 200, message = "成功", response = GameAppletVO.class)})
     public String appletMsg(@PathVariable("appId") String appId, @RequestParam String signature,
                             @RequestParam String timestamp, @RequestParam String nonce,
-                            @RequestParam(required = false) String echostr, @RequestBody String postData) throws Exception {
-        return gameAppletService.appletMsg(appId, signature, timestamp, nonce, echostr, postData);
+                            @RequestBody String postData) throws Exception {
+        return gameAppletService.appletMsg(appId, signature, timestamp, nonce, postData);
     }
 
 }

+ 6 - 0
game-module/game-sdk/src/main/java/com/zanxiang/sdk/controller/PayController.java

@@ -35,6 +35,12 @@ public class PayController {
     @Resource
     private OrderPayService orderPayService;
 
+    @ApiOperation(value = "获取小游戏支付方式")
+    @PostMapping(value = "/device/applet")
+    public ResultVO<Integer> getAppletPayDevice(@ValidLogin UserData userData) {
+        return ResultVO.ok(orderPayService.getAppletPayDevice(userData));
+    }
+
     @ApiOperation(value = "支付参数生成")
     @PostMapping(value = "/create")
     public ResultMap create(@Validated @RequestBody ProductPayParam product, @ValidLogin UserData userData) {

+ 42 - 0
game-module/game-sdk/src/main/java/com/zanxiang/sdk/domain/dto/AppletMsgDTO.java

@@ -0,0 +1,42 @@
+package com.zanxiang.sdk.domain.dto;
+
+import lombok.Data;
+
+/**
+ * @author : lingfeng
+ * @time : 2023-01-05
+ * @description : 小程序消息
+ */
+@Data
+public class AppletMsgDTO {
+
+    /**
+     * 开发者微信号
+     */
+    private String ToUserName;
+
+    /**
+     * 发送方帐号(一个OpenID)
+     */
+    private String FromUserName;
+
+    /**
+     * 消息创建时间 (整型)
+     */
+    private String CreateTime;
+
+    /**
+     * 消息类型,文本为text
+     */
+    private String MsgType;
+
+    /**
+     * 文本消息内容
+     */
+    private String Content;
+
+    /**
+     * 消息id,64位整型
+     */
+    private Long MsgId;
+}

+ 1 - 2
game-module/game-sdk/src/main/java/com/zanxiang/sdk/service/GameAppletService.java

@@ -33,11 +33,10 @@ public interface GameAppletService extends IService<GameApplet> {
      * @param signature 签名
      * @param timestamp 时间戳
      * @param nonce     现时标志
-     * @param echoStr   回声str
      * @return {@link String}
      * @throws Exception 异常
      */
-    String appletMsg(String appId, String signature, String timestamp, String nonce, String echoStr, String postData) throws Exception;
+    String appletMsg(String appId, String signature, String timestamp, String nonce, String postData) throws Exception;
 
     /**
      * 通过游戏id和app id

+ 73 - 37
game-module/game-sdk/src/main/java/com/zanxiang/sdk/service/Impl/GameAppletServiceImpl.java

@@ -3,17 +3,31 @@ package com.zanxiang.sdk.service.Impl;
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
 import com.zanxiang.common.exception.BaseException;
+import com.zanxiang.module.util.JsonUtil;
 import com.zanxiang.module.util.bean.BeanUtil;
 import com.zanxiang.mybatis.entity.GameApplet;
+import com.zanxiang.mybatis.entity.Order;
+import com.zanxiang.mybatis.entity.User;
 import com.zanxiang.mybatis.mapper.GameAppletMapper;
+import com.zanxiang.sdk.domain.dto.AppletMsgDTO;
 import com.zanxiang.sdk.domain.dto.GameAppletDTO;
 import com.zanxiang.sdk.domain.params.UserData;
 import com.zanxiang.sdk.domain.vo.GameAppletVO;
 import com.zanxiang.sdk.service.GameAppletService;
+import com.zanxiang.sdk.service.OrderService;
+import com.zanxiang.sdk.service.UserService;
+import com.zanxiang.sdk.service.api.WxApiService;
 import com.zanxiang.sdk.util.SignUtil;
 import lombok.extern.slf4j.Slf4j;
+import org.apache.logging.log4j.util.Strings;
+import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
+import org.springframework.web.client.RestTemplate;
+import org.springframework.web.util.UriComponentsBuilder;
 
+import java.net.URI;
+import java.util.HashMap;
+import java.util.Map;
 import java.util.Objects;
 
 /**
@@ -25,17 +39,18 @@ import java.util.Objects;
 @Service
 public class GameAppletServiceImpl extends ServiceImpl<GameAppletMapper, GameApplet> implements GameAppletService {
 
-    /**
-     * 小游戏消息推送
-     *
-     * @param appId     应用程序id
-     * @param signature 签名
-     * @param timestamp 时间戳
-     * @param nonce     现时标志
-     * @param echoStr   回声str
-     * @return {@link String}
-     * @throws Exception 异常
-     */
+    @Autowired
+    private UserService userService;
+
+    @Autowired
+    private OrderService orderService;
+
+    @Autowired
+    private WxApiService wxApiService;
+
+    @Autowired
+    private RestTemplate restTemplate;
+
     @Override
     public String appletMsgCheck(String appId, String signature, String timestamp, String nonce, String echoStr) throws Exception {
         log.error("验证参数, appId : {}, signature : {}, timestamp : {}, nonce : {}, echoStr : {}", appId, signature, timestamp, nonce, echoStr);
@@ -52,21 +67,13 @@ public class GameAppletServiceImpl extends ServiceImpl<GameAppletMapper, GameApp
         return echoStr;
     }
 
-    /**
-     * 小游戏消息推送
-     *
-     * @param appId     应用程序id
-     * @param signature 签名
-     * @param timestamp 时间戳
-     * @param nonce     现时标志
-     * @param echoStr   回声str
-     * @return {@link String}
-     * @throws Exception 异常
-     */
     @Override
-    public String appletMsg(String appId, String signature, String timestamp, String nonce, String echoStr, String postData) throws Exception {
-        log.error("接收到事件消息, appId : {}, signature : {}, timestamp : {}, nonce : {}, echoStr : {}, postData : {}",
-                appId, signature, timestamp, nonce, echoStr, postData);
+    public String appletMsg(String appId, String signature, String timestamp, String nonce, String postData) throws Exception {
+        log.error("接收到事件消息, appId : {}, signature : {}, timestamp : {}, nonce : {}, postData : {}",
+                appId, signature, timestamp, nonce, postData);
+        if (Strings.isBlank(postData)) {
+            return "success";
+        }
         GameApplet gameApplet = super.getOne(new LambdaQueryWrapper<GameApplet>()
                 .eq(GameApplet::getAppId, appId));
         if (gameApplet == null) {
@@ -77,15 +84,50 @@ public class GameAppletServiceImpl extends ServiceImpl<GameAppletMapper, GameApp
         if (!Objects.equals(mySignature, signature)) {
             return "success";
         }
+        AppletMsgDTO appletMsgDTO = JsonUtil.toObj(postData, AppletMsgDTO.class);
+        //查询用户信息
+        User user = userService.getOne(new LambdaQueryWrapper<User>()
+                .eq(User::getGameId, gameApplet.getGameId())
+                .eq(User::getOpenId, appletMsgDTO.getFromUserName()));
+        if (user == null) {
+            return "success";
+        }
+        //查询用户最新订单
+        Order order = orderService.getOne(new LambdaQueryWrapper<Order>()
+                .eq(Order::getUserId, user.getId())
+                .orderByDesc(Order::getCreateTime)
+                .last("limit 1"));
+        if (order == null) {
+            return "success";
+        }
+        this.sendCustomMessage(gameApplet, user, order);
         return "success";
     }
 
-    /**
-     * 通过游戏id查询
-     *
-     * @param gameId 游戏id
-     * @return {@link GameAppletDTO}
-     */
+    private void sendCustomMessage(GameApplet gameApplet, User user, Order order) {
+        //获取接口token
+        String accessToken = wxApiService.getAccessToken(gameApplet.getAppId(), gameApplet.getAppSecret());
+        URI uri = UriComponentsBuilder.fromHttpUrl("https://api.weixin.qq.com/cgi-bin/message/custom/business/send")
+                .queryParam("access_token", accessToken)
+                .build().toUri();
+        Map<String, Object> paramMap = new HashMap<>(4);
+        paramMap.put("touser", user.getOpenId());
+        paramMap.put("msgtype", "link");
+
+        Map<String, Object> linkMap = new HashMap<>(4);
+        linkMap.put("title", "点我充值");
+        linkMap.put("description", "点我充值" + order.getAmount() + "元,用于购买" + order.getAmount() + "元档充值");
+        linkMap.put("url", "http://gg.84game.cn/wechatPay/index.html?userId=" + user.getId() + "&orderId=" + order.getId());
+        //linkMap.put("thumb_url", "图片地址");
+
+        paramMap.put("link", linkMap);
+
+        log.error("客服消息发送参数, paramMap : {}", JsonUtil.toString(paramMap));
+        // 发送请求
+        String result = restTemplate.postForObject(uri, paramMap, String.class);
+        log.error("客服消息发送结果, result : {}", result);
+    }
+
     @Override
     public GameAppletDTO getByGameId(Long gameId) {
         GameApplet gameApplet = super.getOne(new LambdaQueryWrapper<GameApplet>()
@@ -96,12 +138,6 @@ public class GameAppletServiceImpl extends ServiceImpl<GameAppletMapper, GameApp
         return BeanUtil.copy(gameApplet, GameAppletDTO.class);
     }
 
-    /**
-     * 微信小游戏初始化获取信息
-     *
-     * @param userData : 用户信息
-     * @return {@link GameAppletVO}
-     */
     @Override
     public GameAppletVO gameAppletInit(UserData userData) {
         GameApplet gameApplet = super.getOne(new LambdaQueryWrapper<GameApplet>()

+ 5 - 0
game-module/game-sdk/src/main/java/com/zanxiang/sdk/service/Impl/OrderPayServiceImpl.java

@@ -38,6 +38,11 @@ public class OrderPayServiceImpl implements OrderPayService {
     @Autowired
     public GamePayWayService gamePayWayService;
 
+    @Override
+    public Integer getAppletPayDevice(UserData userData) {
+        return 2;
+    }
+
     @Override
     public ResultMap payCreate(ProductPayParam product, UserData userData) {
         //创建订单

+ 8 - 0
game-module/game-sdk/src/main/java/com/zanxiang/sdk/service/OrderPayService.java

@@ -14,6 +14,14 @@ import java.io.IOException;
  */
 public interface OrderPayService {
 
+    /**
+     * 获取小游戏支付方式
+     *
+     * @param userData 用户数据
+     * @return {@link Integer}
+     */
+    Integer getAppletPayDevice(UserData userData);
+
     /**
      * 订单支付
      *

+ 35 - 0
game-module/game-sdk/src/main/java/com/zanxiang/sdk/service/api/WxApiService.java

@@ -1,8 +1,11 @@
 package com.zanxiang.sdk.service.api;
 
+import com.zanxiang.common.enums.ExpireTimeEnum;
 import com.zanxiang.common.exception.BaseException;
 import com.zanxiang.common.utils.URIUtil;
 import com.zanxiang.module.util.JsonUtil;
+import com.zanxiang.sdk.constant.RedisKeyConstant;
+import com.zanxiang.sdk.util.RedisUtil;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.logging.log4j.util.Strings;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -24,6 +27,9 @@ public class WxApiService {
     @Autowired
     private RestTemplate restTemplate;
 
+    @Autowired
+    private RedisUtil<String> redisUtil;
+
     /**
      * 获取用户应用openId
      *
@@ -49,4 +55,33 @@ public class WxApiService {
         }
         return userMap.get("openid");
     }
+
+    /**
+     * 获取访问令牌
+     *
+     * @param appId  应用程序id
+     * @param secret 秘密
+     * @return {@link String}
+     */
+    public String getAccessToken(String appId, String secret) {
+        String key = RedisKeyConstant.APPLET_ACCESS_TOKEN + appId;
+        String cache = redisUtil.getCache(key);
+        if (Strings.isNotBlank(cache)) {
+            return cache;
+        }
+        Map<String, String> paramMap = new HashMap<>(4);
+        paramMap.put("appid", appId);
+        paramMap.put("secret", secret);
+        paramMap.put("grant_type", "client_credential");
+        // 发送请求
+        String url = URIUtil.fillUrlParams("https://api.weixin.qq.com/cgi-bin/token", paramMap, Boolean.FALSE);
+        String sr = restTemplate.getForObject(url, String.class);
+        // 解析相应内容(转换成json对象)
+        Map<String, String> userMap = JsonUtil.toMap(sr, Map.class, String.class);
+        if (userMap == null || Strings.isBlank(userMap.get("access_token"))) {
+            throw new BaseException("获取应用token失败");
+        }
+        redisUtil.setCache(key, userMap.get("access_token"), ExpireTimeEnum.ONE_HOUR.getTime());
+        return userMap.get("access_token");
+    }
 }