Przeglądaj źródła

feat : 支付宝PC和H5支付代码修改整理

bilingfeng 2 lat temu
rodzic
commit
1199738803

+ 1 - 3
game-module/game-sdk/src/main/java/com/zanxiang/sdk/common/util/HttpUtil.java

@@ -121,9 +121,7 @@ public class HttpUtil {
         http.setReadTimeout(DEF_READ_TIMEOUT);
         http.setUseCaches(false);
         http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
-//        http.setRequestProperty(
-//                "User-Agent",
-//                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36");
+        http.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36");
         http.setSSLSocketFactory(ssf);
         http.setDoOutput(true);
         http.setDoInput(true);

+ 86 - 91
game-module/game-sdk/src/main/java/com/zanxiang/sdk/service/Impl/pay/AliPayServiceImpl.java

@@ -12,6 +12,7 @@ import com.zanxiang.common.domain.ResultMap;
 import com.zanxiang.common.enums.HttpStatusEnum;
 import com.zanxiang.common.enums.OsEnum;
 import com.zanxiang.common.enums.ResEnum;
+import com.zanxiang.common.utils.JsonUtil;
 import com.zanxiang.sdk.common.util.HttpUtil;
 import com.zanxiang.sdk.domain.bo.ProductPayParamBO;
 import com.zanxiang.sdk.service.OrderPayService;
@@ -23,6 +24,7 @@ import org.springframework.stereotype.Service;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
 import java.util.Enumeration;
 import java.util.HashMap;
 import java.util.Map;
@@ -38,17 +40,34 @@ import java.util.regex.Pattern;
 @Service("AliPayService")
 public class AliPayServiceImpl extends PayService implements OrderPayService {
 
+    private Pattern pattern = Pattern.compile("action=\"(.*)\">", Pattern.CASE_INSENSITIVE);
+
+    private Pattern param = Pattern.compile("value=\"(.*)\">", Pattern.CASE_INSENSITIVE);
+
+    private Pattern mobileClientParam = Pattern.compile("\\{\"queryResultUrl\".*?\"}", Pattern.CASE_INSENSITIVE);
+
+    /**
+     * 异步回调地址
+     */
     @Value("${payConfig.alipay.returnUrl}")
     private String returnUrl;
 
+    /**
+     * 同步回调地址
+     */
     @Value("${payConfig.alipay.notifyUrl}")
     private String notifyUrl;
 
+    /**
+     * 支付配置
+     */
+    private Config config;
+
     /**
      * 支付调起
      *
-     * @param product
-     * @return
+     * @param product : 商品参数
+     * @return : 返回调起支付参数
      */
     @Override
     public ResultMap create(ProductPayParamBO product) {
@@ -61,7 +80,7 @@ public class AliPayServiceImpl extends PayService implements OrderPayService {
             case 1:
                 return this.pc(product);
             case 2:
-                return this.mobile2(product);
+                return this.mobile(product);
             case 3:
                 return this.app(product);
             default:
@@ -72,14 +91,14 @@ public class AliPayServiceImpl extends PayService implements OrderPayService {
     /**
      * 异步回调
      *
-     * @param request
-     * @param response
-     * @return
+     * @param request  : 请求参数
+     * @param response : 返回参数
+     * @return : 返回结果
      */
     @Override
     public String notify(HttpServletRequest request, HttpServletResponse response) {
         try {
-            Map<String, String> params = new HashMap<String, String>();
+            Map<String, String> params = new HashMap<>();
             Enumeration<String> parameterNames = request.getParameterNames();
             while (parameterNames.hasMoreElements()) {
                 String parameterName = parameterNames.nextElement();
@@ -108,14 +127,14 @@ public class AliPayServiceImpl extends PayService implements OrderPayService {
     /**
      * 同步回调
      *
-     * @param request
-     * @return
+     * @param request : 请求参数
+     * @return : 返回结果
      */
     @Override
     public ResultMap synNotify(HttpServletRequest request) {
         try {
             //获取支付宝GET过来反馈信息
-            Map<String, String> params = new HashMap<String, String>();
+            Map<String, String> params = new HashMap<>();
             Map<String, String[]> requestParams = request.getParameterMap();
             for (String name : requestParams.keySet()) {
                 String[] values = requestParams.get(name);
@@ -125,7 +144,7 @@ public class AliPayServiceImpl extends PayService implements OrderPayService {
                             : valueStr + values[i] + ",";
                 }
                 //乱码解决,这段代码在出现乱码时使用
-                valueStr = new String(valueStr.getBytes("ISO-8859-1"), Constants.UTF8);
+                valueStr = new String(valueStr.getBytes("ISO-8859-1"), StandardCharsets.UTF_8);
                 params.put(name, valueStr);
             }
             //商户订单号
@@ -154,112 +173,86 @@ public class AliPayServiceImpl extends PayService implements OrderPayService {
     }
 
     /**
-     * 手机支付
+     * h5支付
      *
-     * @param product
-     * @return
+     * @param product : 商品参数
+     * @return : 返回支付调起参数
      */
     private ResultMap mobile(ProductPayParamBO product) {
         try {
-            log.info("mobile端支付生成,请求参数 bo:{}", product);
             AlipayTradeWapPayResponse response = Factory.Payment
                     .Wap().asyncNotify(notifyUrl)
                     .pay(product.getSubject(), product.getOutTradeNo(), product.getTotalFee(), "", this.returnUrl);
-            log.info("mobile端支付生成,result:{}", response);
-            if (ResponseChecker.success(response)) {
-                System.out.println("mobile端支付生成================");
-                System.out.println(response.getBody());
-                return ResultMap.ok(product.getPayDevice(), response.getBody());
-            } else {
-                return ResultMap.ok(ResEnum.FAIL.getMsg());
+            //请求失败
+            if (!ResponseChecker.success(response)) {
+                log.error("支付宝h5支付失败,product : {}, response : {}", JsonUtil.toString(product), JsonUtil.toString(response));
+                return ResultMap.error(ResEnum.FAIL.getMsg());
             }
-        } catch (Exception e) {
-            return ResultMap.error(ResEnum.FAIL.getMsg());
-        }
-    }
-
-    private ResultMap mobile2(ProductPayParamBO product) {
-        try {
-            log.info("mobile端支付生成,请求参数 bo:{}", product);
-            AlipayTradeWapPayResponse response = Factory.Payment
-                    .Wap().asyncNotify(notifyUrl)
-                    .pay(product.getSubject(), product.getOutTradeNo(), product.getTotalFee(), "", this.returnUrl);
-            log.info("mobile端支付生成,result:{}", response);
-            if (ResponseChecker.success(response)) {
-                HashMap<String, String> result = new HashMap<>();
-                String body = response.getBody();
-                result.put("fromData", body);
-                try {
-                    //安卓与ios系统时才单独获取app支付地址
-                    if (product.getDeviceSystem().contains(OsEnum.SYSTEM_ANDROID.getOs()) || product.getDeviceSystem().contains(OsEnum.SYSTEM_IOS.getOs())) {
-                        Pattern pattern = Pattern.compile("action=\"(.*)\">", Pattern.CASE_INSENSITIVE);
-                        Matcher matcher = pattern.matcher(body);
-                        if (matcher.find()) {
-                            String url = matcher.group();
-                            url = url.substring(8, url.length() - 2);
-                            Pattern param = Pattern.compile("value=\"(.*)\">", Pattern.CASE_INSENSITIVE);
-                            Matcher paraMatcher = param.matcher(body);
-                            if (paraMatcher.find()) {
-                                String paramData = paraMatcher.group();
-                                paramData = paramData.substring(7, paramData.length() - 2);
-                                paramData = paramData.replace("&quot;", "\"");
-                                String mobileClientUrl = HttpUtil.postDataUrl(url, "biz_content=" + paramData, null);
-                                System.out.println(mobileClientUrl);
-                                String alipayContentBody = HttpUtil.postData(mobileClientUrl, "");
-                                Pattern mobileClientParam = Pattern.compile("\\{\"queryResultUrl\".*?\"}", Pattern.CASE_INSENSITIVE);
-                                Matcher mobileClientMatcher = mobileClientParam.matcher(alipayContentBody);
-                                System.out.println(mobileClientMatcher);
-                                String deeplink_android = "alipays://platformapi/startApp?appId=20000125&orderSuffix=";
-                                String deeplink_ios = "alipay://alipayclient/?";
-                                if (mobileClientMatcher.find()) {
-                                    //示例:{"queryResultUrl":"/h5/h5RoutePayResultQuery.json?h5_route_token=GZ00rxXoidjHj2airAK8nhYz70MUBsmobilecashierGZ00","invokeAlipayData":{"dataString":"h5_route_token=\"GZ00rxXoidjHj2airAK8nhYz70MUBsmobilecashierGZ00\"&is_h5_route=\"true\""}
-                                    String pageData = mobileClientMatcher.group() + "}";
-                                    JSONObject jsonObject = JSONObject.parseObject(pageData);
-                                    Object invokeAlipayData = jsonObject.get("invokeAlipayData");
-                                    String dataString = JSONObject.parseObject(invokeAlipayData.toString()).get("dataString").toString();
-                                    deeplink_android += URLEncoder.encode(dataString, Constants.UTF8);
-                                    deeplink_ios += URLEncoder.encode(pageData, Constants.UTF8);
-                                    if (product.getDeviceSystem().contains(OsEnum.SYSTEM_ANDROID.getOs())) {
-                                        result.put("appLink", deeplink_android);
-                                    } else {
-                                        result.put("appLink", deeplink_ios);
-                                    }
-                                }
-                            }
+            HashMap<String, String> result = new HashMap<>();
+            String body = response.getBody();
+            result.put("fromData", body);
+            //安卓与ios系统时才单独获取app支付地址
+            if (!product.getDeviceSystem().contains(OsEnum.SYSTEM_ANDROID.getOs()) && !product.getDeviceSystem().contains(OsEnum.SYSTEM_IOS.getOs())) {
+                return ResultMap.ok(product.getPayDevice(), result);
+            }
+            Matcher matcher = pattern.matcher(body);
+            //解析短链
+            if (matcher.find()) {
+                String url = matcher.group();
+                url = url.substring(8, url.length() - 2);
+                Matcher paraMatcher = param.matcher(body);
+                if (paraMatcher.find()) {
+                    String paramData = paraMatcher.group();
+                    paramData = paramData.substring(7, paramData.length() - 2);
+                    paramData = paramData.replace("&quot;", "\"");
+                    String mobileClientUrl = HttpUtil.postDataUrl(url, "biz_content=" + paramData, null);
+                    String aliPayContentBody = HttpUtil.postData(mobileClientUrl, "");
+                    Matcher mobileClientMatcher = mobileClientParam.matcher(aliPayContentBody);
+                    //todo : 这里存在一个写死的appId, 应该是沙箱环境的appId, 上线的时候要切换
+                    String deepLinkAndroid = "alipays://platformapi/startApp?appId=20000125&orderSuffix=";
+                    String deepLinkIos = "alipay://alipayclient/?";
+                    if (mobileClientMatcher.find()) {
+                        String pageData = mobileClientMatcher.group() + "}";
+                        JSONObject jsonObject = JSONObject.parseObject(pageData);
+                        Object invokeAliPayData = jsonObject.get("invokeAlipayData");
+                        String dataString = JSONObject.parseObject(invokeAliPayData.toString()).get("dataString").toString();
+                        deepLinkAndroid += URLEncoder.encode(dataString, Constants.UTF8);
+                        deepLinkIos += URLEncoder.encode(pageData, Constants.UTF8);
+                        if (product.getDeviceSystem().contains(OsEnum.SYSTEM_ANDROID.getOs())) {
+                            result.put("appLink", deepLinkAndroid);
+                        } else {
+                            result.put("appLink", deepLinkIos);
                         }
                     }
-                } catch (Exception e) {
-                    log.error("获取支付包app支付时发生异常,已通过from表单形式调起支付 fromData:{}, e:{}", body, e);
                 }
-                return ResultMap.ok(product.getPayDevice(), result);
             }
-        } catch (
-                Exception e) {
+            return ResultMap.ok(product.getPayDevice(), result);
+        } catch (Exception e) {
+            log.error("支付宝h5支付失败,meg : {}", e.getMessage());
             return ResultMap.error(ResEnum.FAIL.getMsg());
         }
-        return ResultMap.error(ResEnum.FAIL.getMsg());
     }
 
     /**
-     * 电脑支付
+     * pc端电脑支付
      *
-     * @param product
-     * @return
+     * @param product : 商品参数
+     * @return : 返回支付调起参数
      */
     private ResultMap pc(ProductPayParamBO product) {
         try {
-            log.info("pc端支付生成, product : {}", product);
+            log.info("pc端支付生成,请求参数 bo:{}", product);
             AlipayTradePagePayResponse response = Factory.Payment
                     .Page().asyncNotify(notifyUrl)
                     .pay(product.getSubject(), product.getOutTradeNo(), product.getTotalFee(), this.returnUrl);
-            log.info("pc端支付生成, response : {}", response);
+            log.info("pc端支付生成,result:{}", response);
             if (ResponseChecker.success(response)) {
                 return ResultMap.ok(product.getPayDevice(), response.getBody());
             } else {
                 return ResultMap.error(ResEnum.FAIL.getMsg());
             }
         } catch (Exception e) {
-            log.error("pc端支付生成异常, e : {}", e.getMessage());
+            log.error("pc端支付生成异常 e:{}", e.getMessage());
             return ResultMap.error(ResEnum.FAIL.getMsg());
         }
     }
@@ -267,8 +260,8 @@ public class AliPayServiceImpl extends PayService implements OrderPayService {
     /**
      * app支付
      *
-     * @param product
-     * @return
+     * @param product : 商品参数
+     * @return : 返回支付调起参数
      */
     private ResultMap app(ProductPayParamBO product) {
         try {
@@ -281,7 +274,8 @@ public class AliPayServiceImpl extends PayService implements OrderPayService {
                 return ResultMap.error(ResEnum.FAIL.getMsg());
             }
         } catch (Exception e) {
-            log.error("app端支付生成异常, e : {}", e.getMessage());
+            e.printStackTrace();
+            log.error("app端支付生成异常 e:{}", e.getMessage());
             return ResultMap.error(ResEnum.FAIL.getMsg());
         }
     }
@@ -289,11 +283,12 @@ public class AliPayServiceImpl extends PayService implements OrderPayService {
     /**
      * 配置初始化
      *
-     * @param obj config
+     * @param obj : 配置参数
      */
     @Override
     public void configInit(String obj) {
         Config config = JSONObject.parseObject(obj, Config.class);
         Factory.setOptions(config);
+        this.config = config;
     }
 }