Prechádzať zdrojové kódy

Merge remote-tracking branch 'origin/master'

tianyunperfect 3 rokov pred
rodič
commit
2f5626147c

+ 18 - 0
book-dao/src/main/java/com/book/dao/VO/SnsapiBase.java

@@ -0,0 +1,18 @@
+package com.book.dao.VO;
+
+import lombok.Data;
+
+/**
+ * created in 2021/9/2
+ * Project: book-store
+ *
+ * @author win7
+ */
+@Data
+public class SnsapiBase {
+ private String access_token;
+ private int expires_in;
+ private String refresh_token;
+ private String openid;
+ private String scope;
+}

+ 2 - 2
book-dao/src/main/java/com/book/dao/VO/WxPayInfo.java

@@ -12,7 +12,7 @@ import lombok.Data;
 public class WxPayInfo {
   private String userId;
   private String orderId;
-  private String payInfo;
-  private String url;
+  private Object payInfo;
+  private String url = "";
 
 }

+ 1 - 0
book-dao/src/main/java/com/book/dao/VO/WxPayRequest.java

@@ -13,4 +13,5 @@ public class WxPayRequest {
     private Long userId;
     private Integer goodId;
     private String ip;
+    private String openid;
 }

+ 66 - 9
book-push/src/main/java/com/book/push/service/wx/impl/WxThirdPartServiceImpl.java

@@ -1,16 +1,20 @@
 package com.book.push.service.wx.impl;
 
+import com.book.dao.cps.pojo.AdminConfig;
 import com.book.dao.cps.pojo.Platform;
 import com.book.push.config.RedisProperties;
 import com.book.push.config.WxOpenInRedisBookConfigStorage;
 import com.book.push.handler.*;
+import com.book.push.service.dao.AdminConfigService;
 import com.book.push.service.dao.PlatformService;
 import com.book.push.service.redis.RedisService;
 import com.book.push.service.wx.WxThirdPartService;
-import lombok.AllArgsConstructor;
+import com.book.push.utils.JsonUtils;
+import com.book.push.utils.Md5Util;
+import com.book.push.vo.AuthorizerInfo;
+import com.book.push.vo.ComponentInfo;
 import lombok.RequiredArgsConstructor;
 import me.chanjar.weixin.open.api.WxOpenService;
-import me.chanjar.weixin.open.api.impl.WxOpenInRedisConfigStorage;
 import me.chanjar.weixin.open.api.impl.WxOpenServiceImpl;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -20,6 +24,7 @@ import org.springframework.stereotype.Service;
 import redis.clients.jedis.JedisPool;
 
 import javax.annotation.PostConstruct;
+import java.util.List;
 import java.util.Map;
 import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
@@ -63,6 +68,8 @@ public class WxThirdPartServiceImpl implements WxThirdPartService {
     private RedisService redisService;
     @Autowired
     private JedisPool jedisPool;
+    @Autowired
+    private AdminConfigService adminConfigService;
 
     private WxThirdPartMessageRouter wxThirdPartMessageRouter;
     public static final String PLATFORM_KEY_PREFIX = "platformId_%d";
@@ -70,32 +77,37 @@ public class WxThirdPartServiceImpl implements WxThirdPartService {
 
     @PostConstruct
     public void init() {
-
+        logger.info("------------------------------  WxThirdPartServiceImpl  init ----------------------------------");
         Map<Integer, Platform> integerPlatformMap = platformService.selectAll();
         Set<Integer> platFormIdSet = integerPlatformMap.keySet();
         platFormIdSet.stream().forEach(id -> {
             Platform platform = integerPlatformMap.get(id);
+            logger.info("platform_id:" + id + "-->"+platform.toString());
             WxOpenService wxOpenService = new WxOpenServiceImpl();
-            WxOpenInRedisBookConfigStorage inRedisConfigStorage = new WxOpenInRedisBookConfigStorage(jedisPool, String.format(PLATFORM_KEY_PREFIX, id));
+            WxOpenInRedisBookConfigStorage inRedisConfigStorage = new WxOpenInRedisBookConfigStorage(platform, jedisPool, String.format(PLATFORM_KEY_PREFIX, id));
             inRedisConfigStorage.setComponentAppId(platform.getAppid());
             inRedisConfigStorage.setComponentAppSecret(platform.getSecret());
 
-            //FIXME  这里有错误,请注意修改
-            if (redisService.get(inRedisConfigStorage.getVerifyTicketCacheKey())==null){
+
+            logger.info("从redis 取值 ComponentVerifyTicket ,key = " + inRedisConfigStorage.getVerifyTicketCacheKey());
+            if (redisService.get(inRedisConfigStorage.getVerifyTicketCacheKey()) == null) {
                 logger.error("ComponentVerifyTicket is null in redis for key :" + inRedisConfigStorage.getVerifyTicketCacheKey());
-            }else {
+            } else {
 
                 inRedisConfigStorage.setComponentVerifyTicket(redisService.get(inRedisConfigStorage.getVerifyTicketCacheKey()));
             }
-            if (redisService.get(inRedisConfigStorage.getComponentTokenCacheKey())==null){
+            logger.info("从redis 取值 ComponentToken ,key = " + inRedisConfigStorage.getComponentTokenCacheKey());
+            if (redisService.get(inRedisConfigStorage.getComponentTokenCacheKey()) == null) {
                 logger.error("ComponentToken is null in redis for key :" + inRedisConfigStorage.getComponentTokenCacheKey());
-            }else {
+            } else {
 
                 inRedisConfigStorage.setComponentToken(redisService.get(inRedisConfigStorage.getComponentTokenCacheKey()));
             }
 
+
             inRedisConfigStorage.setComponentAesKey(platform.getAesKey());
             wxOpenService.setWxOpenConfigStorage(inRedisConfigStorage);
+            updateAllAuthorizerAccessToken(inRedisConfigStorage);
             wxOpenServiceMap.put(id, wxOpenService);
         });
 
@@ -142,7 +154,34 @@ public class WxThirdPartServiceImpl implements WxThirdPartService {
 
     }
 
+    private void updateAllAuthorizerAccessToken(WxOpenInRedisBookConfigStorage wxOpenInRedisBookConfigStorage) {
+        logger.info("updateAllAuthorizerAccessToken... ");
+        Platform platform = wxOpenInRedisBookConfigStorage.getPlatform();
+        List<AdminConfig> list = adminConfigService.selectByPlatformId(platform.getId());
+        for (AdminConfig adminConfig : list) {
+            logger.info("adminConfig:" + "-->"+adminConfig.toString());
+
+            String appid = adminConfig.getAppid();
+
+            String json = adminConfig.getJson().toString();
+            AdminConfig.Info info = JsonUtils.getObject(json, AdminConfig.Info.class);
+            AdminConfig.AuthorizationInfo authorization_info = info.getAuthorization_info();
+            String authorizer_refresh_token = authorization_info.getAuthorizer_refresh_token();
+            wxOpenInRedisBookConfigStorage.updateAuthorizerRefreshToken(appid, authorizer_refresh_token);
+            AuthorizerInfo authorizerInfo = new AuthorizerInfo(wxOpenInRedisBookConfigStorage.getComponentAppId(), appid, adminConfig.getRefreshToken());
+            String authorizerTokenCacheKey = wxOpenInRedisBookConfigStorage.getAuthorizerTokenCacheKey(authorizerInfo);
+            String token = redisService.get(authorizerTokenCacheKey);
+            if (token == null) {
+                logger.error("AuthorizerToken is null in redis for key :" + authorizerTokenCacheKey);
+            } else {
+                wxOpenInRedisBookConfigStorage.updateAuthorizerAccessToken(appid, token, redisService.getExpiresTime(authorizerTokenCacheKey).intValue());
+            }
+
+
+        }
+
 
+    }
 
 
     @Override
@@ -154,4 +193,22 @@ public class WxThirdPartServiceImpl implements WxThirdPartService {
     public WxThirdPartMessageRouter getWxThirdPartMessageRouter() {
         return this.wxThirdPartMessageRouter;
     }
+
+    public static void main(String[] args) {
+        ComponentInfo componentInfo = new ComponentInfo("wxa6f2133192bfbcac", "a828e6b5eb87419e50826c60b9a20201"
+                , "ticket@@@kI-lexDGVC9dLKjHuXesqMt8sabH42EJyyRo9ben7uXISTMdDyBkxT-j53rCDZpWOkB2PuYMYiLenH6Y9FloEg");
+        System.out.println(JsonUtils.toJsonString(componentInfo));
+        String s =  WxThirdPartService.COMPONENT_TOKEN_KEY_PREFIX + Md5Util.md5(JsonUtils.toJsonString(componentInfo));
+
+        System.out.println(s);
+
+        //
+
+
+
+        AuthorizerInfo authorizerInfo = new AuthorizerInfo("wxa6f2133192bfbcac","wxe1271417b2ff5b1c","refreshtoken@@@N0INeuo9aWT1PdFNIfSTynUm8eI5gGp9fmg_SAG69p8");
+        System.out.println(JsonUtils.toJsonString(authorizerInfo));
+        String s1 =  WxThirdPartService.COMPONENT_TOKEN_KEY_PREFIX + Md5Util.md5(JsonUtils.toJsonString(authorizerInfo));
+        System.out.println(s1);
+    }
 }

+ 1 - 0
book-server/src/main/java/com/book/server/config/Const.java

@@ -3,6 +3,7 @@ package com.book.server.config;
 public class Const {
     public static final String CacheSplit = "_";
     public static final String EDIT_BOOK_PRE = "edit_book";
+    public static  final  String URL_PAY_CENTER = "http://{appid}.{host}/home.html#/{page}?userId={userId}&payOpenid={openid}";
     public static final Long bookIdMin = 110_0001L;
     public static final Long bookInMax = 110_9999L;
 }

+ 10 - 4
book-server/src/main/java/com/book/server/controller/WxPayController.java

@@ -9,11 +9,9 @@ import com.book.server.common.entity.ResultCode;
 import com.book.server.service.WxPayService;
 import com.book.server.utils.NetworkUtil;
 import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.bind.annotation.*;
 
 import javax.servlet.http.HttpServletRequest;
 import java.io.IOException;
@@ -58,6 +56,7 @@ public class WxPayController extends BaseController {
 
     /**
      * 通知
+     *
      * @param request
      * @return
      */
@@ -68,4 +67,11 @@ public class WxPayController extends BaseController {
 
     }
 
+    @GetMapping("/page")
+    public String chargePage(@RequestParam("userId") String userId, @RequestParam("code") String code,@RequestParam("state") String page) {
+
+
+        return wxPayService.chargePage(userId, code,page);
+    }
+
 }

+ 2 - 0
book-server/src/main/java/com/book/server/service/WxPayService.java

@@ -21,4 +21,6 @@ public interface WxPayService {
 
     String PayNotify(HttpServletRequest request);
 
+
+    String chargePage(String userId, String code,String page);
 }

+ 94 - 22
book-server/src/main/java/com/book/server/service/impl/WxPayServiceImpl.java

@@ -1,20 +1,26 @@
 package com.book.server.service.impl;
 
+import com.book.dao.VO.PalmpayResponse;
+import com.book.dao.VO.SnsapiBase;
 import com.book.dao.VO.WxPayInfo;
 import com.book.dao.VO.WxPayRequest;
 import com.book.dao.cps.entity.Goods;
 import com.book.dao.cps.mapper.*;
 import com.book.dao.cps.pojo.*;
 import com.book.dao.utils.DateUtils;
+import com.book.server.config.Const;
 import com.book.server.service.BookService;
 import com.book.server.service.UserService;
 import com.book.server.service.WxPayService;
-import com.book.server.utils.DataUtil;
-import com.book.server.utils.Md5Util;
+import com.book.server.utils.*;
+import com.sun.deploy.net.URLEncoder;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.http.client.utils.URLEncodedUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 
 import javax.servlet.http.HttpServletRequest;
+import java.io.UnsupportedEncodingException;
 import java.math.BigDecimal;
 import java.util.*;
 import java.util.concurrent.TimeUnit;
@@ -69,6 +75,7 @@ public class WxPayServiceImpl implements WxPayService {
         Integer wxpayId = adminConfig.getWxpayId();
         Wxpay wxpay = wxpayMapper.selectByPrimaryKey(wxpayId);
         String appid = wxpay.getAppid();
+        String secret = wxpay.getSecret();
         String host = wxpay.getPayHost();
         String palmpayAppid = wxpay.getQuartetAppId();
         String palmpayMchid = wxpay.getQuartetMerchantId();
@@ -79,7 +86,7 @@ public class WxPayServiceImpl implements WxPayService {
         Integer ophostId = adminConfig.getOphostId();
         Ophost ophost = ophostMapper.selectByPrimaryKey(ophostId);
         Config url_pay = configMapper.selectByName("url_pay");
-        String url = url_pay.getValue();
+        String url = "http://" + url_pay.getValue();
         AdminExtend adminExtend = adminExtendMapper.selectByPrimaryKey(channelId);
         //todo 入库
         long orderid = TimeUnit.NANOSECONDS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS) + wxPayRequest.getUserId();
@@ -129,9 +136,6 @@ public class WxPayServiceImpl implements WxPayService {
         map.put("notifyUrl", url + "/api/wxpay/notify");
         map.put("ip", wxPayRequest.getIp());
 
-        // todo 修改
-      /*  map.put("subAppid", adminConfig.getAppid());
-        map.put("openid", userByUserId.getOpenid());*/
         map.put("api", "1");
 
 
@@ -143,24 +147,43 @@ public class WxPayServiceImpl implements WxPayService {
 
         String form = DataUtil.maptoform(map) + "";
         System.out.println("请求:" + PALMPAY_URL + "?" + form);
-    /*    String result = HTTPSUtil.sendGetByHttps(PALMPAY_URL, map);
-        System.out.println("响应:" + result);
-        PalmpayResponse object = JsonUtils.getObject(result, PalmpayResponse.class);
-        if (object == null) {
-            return null;
-        }
-        if (!"0".equals(object.getErrcode())) {
-            return null;
-        }
-        PalmpayResponse.Result r = object.getResult();
-        order.setPdorderid(r.getPdorderid());
-        order.setPayJson(r.getPay_info());*/
-
-        ordersMapper.insert(order);
         WxPayInfo wxPayInfo = new WxPayInfo();
         wxPayInfo.setUserId(userByUserId.getId() + "");
-        wxPayInfo.setUrl(PALMPAY_URL + "?" + form);
         wxPayInfo.setOrderId(order.getOutTradeNo());
+        if (StringUtils.isNotEmpty(wxpay.getAppid()) && StringUtils.isNotEmpty(wxPayRequest.getOpenid())){
+            map.put("subAppid", wxpay.getAppid());
+            map.put("openid", wxPayRequest.getOpenid());
+
+            String result = HTTPSUtil.sendGetByHttps(PALMPAY_URL, map);
+            System.out.println("响应:" + result);
+            PalmpayResponse object = JsonUtils.getObject(result, PalmpayResponse.class);
+            if (object == null) {
+                return null;
+            }
+            if (!"0".equals(object.getErrcode())) {
+                return null;
+            }
+            PalmpayResponse.Result r = object.getResult();
+            order.setPdorderid(r.getPdorderid());
+            String pay_info = r.getPay_info();
+            order.setPayJson(pay_info);
+
+            Map<String, Object> map1 = JsonUtils.getMap(pay_info);
+            wxPayInfo.setPayInfo(map1);
+
+        }else {
+            wxPayInfo.setUrl(PALMPAY_URL + "?" + form);
+        }
+
+
+
+
+
+
+        ordersMapper.insert(order);
+
+
+
         return wxPayInfo;
     }
 
@@ -205,13 +228,50 @@ public class WxPayServiceImpl implements WxPayService {
             }
 
 
+        }
 
 
+        return "success";
+    }
 
+    @Override
+    public String chargePage(String userId, String code,String page) {
+        User userByUserId = userService.getUserByUserId(Long.parseLong(userId));
+        Integer channelId = userByUserId.getChannelId();
+        AdminConfig adminConfig = adminConfigMapper.selectByPrimaryKey(channelId);
+        Integer wxpayId = adminConfig.getWxpayId();
+        Wxpay wxpay = wxpayMapper.selectByPrimaryKey(wxpayId);
+        String appid = wxpay.getAppid();
+        String secret = wxpay.getSecret();
+        if (StringUtils.isEmpty(code)) {
+            String redirectUrl = "http://" + wxpay.getPayHost() + "/api/wxpay/page?userId=" + userId;
+            String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_base&state=%s#wechat_redirect";
+            try {
+                url = String.format(url, appid, URLEncoder.encode(redirectUrl, "UTF-8"), page);
+            } catch (UnsupportedEncodingException e) {
+                e.printStackTrace();
+            }
+
+
+            return "redirect:" + url;
+        } else {
+
+            String openidUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
+            String format = String.format(openidUrl, appid, secret, code);
+            String s = HttpUtils.sendGet(format);
+            SnsapiBase object = JsonUtils.getObject(s, SnsapiBase.class);
+            String openid = object.getOpenid();
+            Integer ophostId = adminConfig.getOphostId();
+            Ophost ophost = ophostMapper.selectByPrimaryKey(ophostId);
+            String url = Const.URL_PAY_CENTER.replace("{appid}",appid)
+                    .replace("{host}",ophost.getHost())
+                    .replace("{page}",page)
+                    .replace("userId",userId)
+                    .replace("{openid}",openid);
+            return "redirect:" + url;
         }
 
 
-        return "success";
     }
 
 
@@ -231,4 +291,16 @@ public class WxPayServiceImpl implements WxPayService {
         String sign = Md5Util.md5(builder.toString());
         return sign.equals(src.get("sign"));
     }
+
+    public static void main(String[] args) {
+        String result = "{\"result\":{\"sign\":\"edda60a1e29f6ed539c0203921548cdb\",\"signType\":\"MD5\",\"money\":1000,\"appid\":\"4110\",\"charset\":\"UTF-8\",\"pay_info\":\"{\\\"appId\\\":\\\"wx4cb1f52885afcb03\\\",\\\"timeStamp\\\":\\\"1630571756\\\",\\\"nonceStr\\\":\\\"8cbff937d4fc4d1cb9e3944febcbb93d\\\",\\\"package\\\":\\\"prepay_id=wx02163556206106625d6f65c721e05b0000\\\",\\\"signType\\\":\\\"RSA\\\",\\\"paySign\\\":\\\"MokP0HszOcPwgu3JaHoBWVNtDhD4GNo44O0jZDr0/9jDtkBcxNn+gXELjk9e66+tqxW9cq0cesCPD7qhkOmQBheBnb+CB/cFCO+6IbDpekfVfzYIlH5kq2EgSKX5a3xEPG9ykR6IK0uBgCTkui5vFeusm24eibhix7xkeYwUPiYFnKm7pgaIjFZuTFKa9Vdm3a56Il3TaU8bjRz4b/iUlTJo+DKvxehjx4RuNG5h/SeN84ysKm39VCB0XHP2v9LkScLJC/4g706pySbqXZyoVPrerzCb+RiX4C1ZWDKSy9ri3LKNxr+Pm8L90M7njvWyq0u+8u+/vTZO1EGGbb7WDQ==\\\"}\",\"outTradeNo\":\"4110test1630571752721\",\"mchId\":\"2142013001\",\"pdorderid\":\"1127504471476173824\",\"version\":\"3.0\"},\"err\":\"success\",\"errcode\":\"0\"}";
+        PalmpayResponse object = JsonUtils.getObject(result, PalmpayResponse.class);
+        PalmpayResponse.Result r = object.getResult();
+        String pay_info = r.getPay_info();
+
+        Map<String, Object> map1 = JsonUtils.getMap(pay_info);
+        WxPayInfo wxPayInfo = new WxPayInfo();
+        wxPayInfo.setPayInfo(map1);
+        System.out.println(JsonUtils.toJsonStr(wxPayInfo));
+    }
 }