Forráskód Böngészése

调整微信版本和改变项目目录

赵冬冬 4 éve
szülő
commit
0e2b726d13
19 módosított fájl, 612 hozzáadás és 346 törlés
  1. 1 5
      carbon-h5/carbon-h5-service/pom.xml
  2. 13 16
      carbon-h5/carbon-h5-service/src/main/java/com/hcloud/microserver/h5/biz/WechatManagerComponent.java
  3. 30 30
      carbon-h5/carbon-h5-service/src/main/java/com/hcloud/microserver/h5/common/NormalController.java
  4. 0 143
      carbon-h5/carbon-h5-service/src/main/java/com/hcloud/microserver/h5/config/WxMpConfiguration.java
  5. 1 1
      carbon-h5/carbon-h5-service/src/main/java/com/hcloud/microserver/h5/config/redis/RedissonConfig.java
  6. 3 4
      carbon-h5/carbon-h5-service/src/main/java/com/hcloud/microserver/h5/config/wx/WxMaConfiguration.java
  7. 42 0
      carbon-h5/carbon-h5-service/src/main/java/com/hcloud/microserver/h5/config/wx/WxMpConfiguration.java
  8. 2 1
      carbon-h5/carbon-h5-service/src/main/java/com/hcloud/microserver/h5/config/wx/WxMpProperties.java
  9. 1 1
      carbon-h5/carbon-h5-service/src/main/java/com/hcloud/microserver/h5/config/wx/WxPayConfiguration.java
  10. 1 1
      carbon-h5/carbon-h5-service/src/main/java/com/hcloud/microserver/h5/config/wx/WxPayProperties.java
  11. 229 0
      carbon-h5/carbon-h5-service/src/main/java/com/hcloud/microserver/h5/controller/web/WechatAppPayController.java
  12. 130 132
      carbon-h5/carbon-h5-service/src/main/java/com/hcloud/microserver/h5/controller/web/WechatManagerController.java
  13. 2 1
      carbon-h5/carbon-h5-service/src/main/java/com/hcloud/microserver/h5/dao/CustomerCarbonValMapper.java
  14. 2 0
      carbon-h5/carbon-h5-service/src/main/java/com/hcloud/microserver/h5/dao/GoodsOrderInfoMapper.java
  15. 14 0
      carbon-h5/carbon-h5-service/src/main/java/com/hcloud/microserver/h5/entity/WxPayFrom.java
  16. 21 0
      carbon-h5/carbon-h5-service/src/main/java/com/hcloud/microserver/h5/events/CustomerCarbonValEvent.java
  17. 61 0
      carbon-h5/carbon-h5-service/src/main/java/com/hcloud/microserver/h5/listens/CustomerCarbonValListener.java
  18. 15 2
      carbon-h5/carbon-h5-service/src/main/java/com/hcloud/microserver/h5/service/OrderInfoService.java
  19. 44 9
      carbon-h5/carbon-h5-service/src/main/java/com/hcloud/microserver/h5/service/impl/OrderInfoServiceImpl.java

+ 1 - 5
carbon-h5/carbon-h5-service/pom.xml

@@ -14,7 +14,7 @@
     <version>0.0.1-SNAPSHOT</version>
     <name>carbon-h5-service</name>
     <properties>
-        <binarywang.weixin.version>3.9.0</binarywang.weixin.version>
+        <binarywang.weixin.version>3.1.0</binarywang.weixin.version>
     </properties>
     <dependencies>
         <dependency>
@@ -124,10 +124,6 @@
             <version>${binarywang.weixin.version}</version>
         </dependency>
 
-
-
-
-
         <dependency>
             <artifactId>carbon-h5-common</artifactId>
             <groupId>com.hcloud.microserver</groupId>

+ 13 - 16
carbon-h5/carbon-h5-service/src/main/java/com/hcloud/microserver/h5/biz/WechatManagerComponent.java

@@ -1,6 +1,5 @@
 package com.hcloud.microserver.h5.biz;
 
-import com.hcloud.microserver.h5.config.WxMpConfiguration;
 import com.hcloud.microserver.h5.service.CustomerInfoService;
 import com.hcloud.microserver.commoncore.base.Token;
 import com.hcloud.microserver.commoncore.constant.GlobleConstant;
@@ -10,8 +9,6 @@ import com.hcloud.microserver.commoncore.util.TokenUtil;
 import com.hcloud.microserver.commoncore.util.TracedCodeUtils;
 import com.hcloud.microserver.facade.carbon.forms.CustomerInfoForm;
 import lombok.extern.slf4j.Slf4j;
-import me.chanjar.weixin.common.error.WxErrorException;
-import me.chanjar.weixin.mp.api.WxMpService;
 import me.chanjar.weixin.mp.bean.result.WxMpUser;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
@@ -211,18 +208,18 @@ public class WechatManagerComponent{
     }
 
 
-    /**
-     * 获取访问微信接口的API TOKEN
-     * @throws WxErrorException
-     */
-    public String getApiToken() throws WxErrorException {
-        final WxMpService wxMpService = WxMpConfiguration.getMpServices().get(appid);
-        String apiToken = (String) redisUtils.getValue(GlobleConstant.WECHAT_API_TOKEN);
-        if(Objects.isNull(apiToken) || "".equals(apiToken)){
-            apiToken = wxMpService.getAccessToken(true);
-            redisUtils.setValue(GlobleConstant.WECHAT_API_TOKEN,apiToken,7200,TimeUnit.SECONDS);
-        }
-        return apiToken;
-    }
+//    /**
+//     * 获取访问微信接口的API TOKEN
+//     * @throws WxErrorException
+//     */
+//    public String getApiToken() throws WxErrorException {
+//        final WxMpService wxMpService = WxMpConfiguration.getMpServices().get(appid);
+//        String apiToken = (String) redisUtils.getValue(GlobleConstant.WECHAT_API_TOKEN);
+//        if(Objects.isNull(apiToken) || "".equals(apiToken)){
+//            apiToken = wxMpService.getAccessToken(true);
+//            redisUtils.setValue(GlobleConstant.WECHAT_API_TOKEN,apiToken,7200,TimeUnit.SECONDS);
+//        }
+//        return apiToken;
+//    }
 
 }

+ 30 - 30
carbon-h5/carbon-h5-service/src/main/java/com/hcloud/microserver/h5/common/NormalController.java

@@ -65,36 +65,36 @@ public class NormalController extends CarbonBaseController {
         return responseSuccess(resultVO);
     }
 
-    @ApiOperation(value = "上传文件(微信浏览器专用)",notes = "上传文件(微信浏览器专用)")
-    @ApiImplicitParams({
-            @ApiImplicitParam(name = "imageSign",value = "微信图片密文",dataType = "String",paramType = "query")
-    })
-    @ApiResponse(code = 0,message = "操作成功")
-    @AuthCarbonValidate
-    @GetMapping("/uploadWeChatImg")
-    public ResponseBase uploadFilesForWeChat(@RequestParam("imageSign") String signImageStr){
-        StringBuffer stb = new StringBuffer(DOWNLOAD_IMAGES_FOR_WX);
-        try {
-            String token = weChatManager.getApiToken();
-            stb.append("access_token=");
-            stb.append(token);
-            stb.append("&media_id=");
-            stb.append(signImageStr);
-            log.info("0t55HYhg1JEXqV_YJ0ox6f8uq0zu1SmU9rF0kzzMgq8KuGIXkrT8ot5KAOWttVId");
-            log.info("curl===================>{}",stb.toString());
-            String curl = stb.toString();
-            String path = UPLOAD_FILE_PATH+TARGET_IMAGE_DIC_NAME;
-            String imageType = EasyHttpUtils.LoadInstance().getUrlToImg(curl,signImageStr,path);
-            if(null!=imageType && !"".equals(imageType)){
-                String imageUrl =TARGET_IMAGE_DIC_NAME+signImageStr+"."+imageType;
-                return responseSuccess(success(imageUrl));
-            }
-        } catch (Exception e) {
-            log.info("wx get accessToken error please call programmer!!!!");
-            e.printStackTrace();
-        }
-        return responseError(failure());
-    }
+//    @ApiOperation(value = "上传文件(微信浏览器专用)",notes = "上传文件(微信浏览器专用)")
+//    @ApiImplicitParams({
+//            @ApiImplicitParam(name = "imageSign",value = "微信图片密文",dataType = "String",paramType = "query")
+//    })
+//    @ApiResponse(code = 0,message = "操作成功")
+//    @AuthCarbonValidate
+//    @GetMapping("/uploadWeChatImg")
+//    public ResponseBase uploadFilesForWeChat(@RequestParam("imageSign") String signImageStr){
+//        StringBuffer stb = new StringBuffer(DOWNLOAD_IMAGES_FOR_WX);
+//        try {
+//            String token = weChatManager.getApiToken();
+//            stb.append("access_token=");
+//            stb.append(token);
+//            stb.append("&media_id=");
+//            stb.append(signImageStr);
+//            log.info("0t55HYhg1JEXqV_YJ0ox6f8uq0zu1SmU9rF0kzzMgq8KuGIXkrT8ot5KAOWttVId");
+//            log.info("curl===================>{}",stb.toString());
+//            String curl = stb.toString();
+//            String path = UPLOAD_FILE_PATH+TARGET_IMAGE_DIC_NAME;
+//            String imageType = EasyHttpUtils.LoadInstance().getUrlToImg(curl,signImageStr,path);
+//            if(null!=imageType && !"".equals(imageType)){
+//                String imageUrl =TARGET_IMAGE_DIC_NAME+signImageStr+"."+imageType;
+//                return responseSuccess(success(imageUrl));
+//            }
+//        } catch (Exception e) {
+//            log.info("wx get accessToken error please call programmer!!!!");
+//            e.printStackTrace();
+//        }
+//        return responseError(failure());
+//    }
 
 
     @ApiOperation(value = "绑定手机发送短信",notes = "绑定用户手机号")

+ 0 - 143
carbon-h5/carbon-h5-service/src/main/java/com/hcloud/microserver/h5/config/WxMpConfiguration.java

@@ -1,143 +0,0 @@
-package com.hcloud.microserver.h5.config;
-
-
-import com.google.common.collect.Maps;
-import com.hcloud.microserver.commoncore.handler.*;
-import lombok.extern.slf4j.Slf4j;
-import me.chanjar.weixin.mp.api.WxMpMessageRouter;
-import me.chanjar.weixin.mp.api.WxMpService;
-import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
-import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
-import me.chanjar.weixin.mp.constant.WxMpEventConstants;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-
-import java.util.Map;
-
-import static me.chanjar.weixin.common.api.WxConsts.*;
-
-/**
- * wechat mp configuration
- *
- * @author Binary Wang(https://github.com/binarywang)
- */
-@Slf4j
-@Configuration
-public class WxMpConfiguration {
-    private LogHandler logHandler;
-    private NullHandler nullHandler;
-    private KfSessionHandler kfSessionHandler;
-    private StoreCheckNotifyHandler storeCheckNotifyHandler;
-    private LocationHandler locationHandler;
-    private MenuHandler menuHandler;
-    private MsgHandler msgHandler;
-    private UnsubscribeHandler unsubscribeHandler;
-    private SubscribeHandler subscribeHandler;
-
-    @Autowired
-    private WxMpProperties properties;
-
-    private static Map<String, WxMpMessageRouter> routers = Maps.newHashMap();
-    private static Map<String, WxMpService> mpServices = Maps.newHashMap();
-
-    @Autowired
-    public WxMpConfiguration(LogHandler logHandler, NullHandler nullHandler, KfSessionHandler kfSessionHandler,
-                             StoreCheckNotifyHandler storeCheckNotifyHandler, LocationHandler locationHandler,
-                             MenuHandler menuHandler, MsgHandler msgHandler, UnsubscribeHandler unsubscribeHandler,
-                             SubscribeHandler subscribeHandler, WxMpProperties properties) {
-        this.logHandler = logHandler;
-        this.nullHandler = nullHandler;
-        this.kfSessionHandler = kfSessionHandler;
-        this.storeCheckNotifyHandler = storeCheckNotifyHandler;
-        this.locationHandler = locationHandler;
-        this.menuHandler = menuHandler;
-        this.msgHandler = msgHandler;
-        this.unsubscribeHandler = unsubscribeHandler;
-        this.subscribeHandler = subscribeHandler;
-        this.properties = properties;
-    }
-
-    public static Map<String, WxMpMessageRouter> getRouters() {
-        return routers;
-    }
-
-    public static Map<String, WxMpService> getMpServices() {
-        return mpServices;
-    }
-
-    @Bean
-    public Object services() {
-        WxMpDefaultConfigImpl configStorage = new WxMpDefaultConfigImpl();
-        configStorage.setAppId(properties.getAppId());
-        configStorage.setSecret(properties.getSecret());
-        configStorage.setToken(properties.getToken());
-        configStorage.setAesKey(properties.getAesKey());
-        WxMpService service = new WxMpServiceImpl();
-        service.setWxMpConfigStorage(configStorage);
-        routers.put(properties.getAppId(), this.newRouter(service));
-        mpServices.put(configStorage.getAppId(), service);
-        return Boolean.TRUE;
-    }
-
-    private WxMpMessageRouter newRouter(WxMpService wxMpService) {
-        final WxMpMessageRouter newRouter = new WxMpMessageRouter(wxMpService);
-
-        // 记录所有事件的日志 (异步执行)
-        newRouter.rule().handler(this.logHandler).next();
-
-        // 接收客服会话管理事件
-        newRouter.rule().async(false).msgType(XmlMsgType.EVENT)
-                .event(WxMpEventConstants.CustomerService.KF_CREATE_SESSION)
-                .handler(this.kfSessionHandler).end();
-        newRouter.rule().async(false).msgType(XmlMsgType.EVENT)
-                .event(WxMpEventConstants.CustomerService.KF_CLOSE_SESSION)
-                .handler(this.kfSessionHandler)
-                .end();
-        newRouter.rule().async(false).msgType(XmlMsgType.EVENT)
-                .event(WxMpEventConstants.CustomerService.KF_SWITCH_SESSION)
-                .handler(this.kfSessionHandler).end();
-
-        // 门店审核事件
-        newRouter.rule().async(false).msgType(XmlMsgType.EVENT)
-                .event(WxMpEventConstants.POI_CHECK_NOTIFY)
-                .handler(this.storeCheckNotifyHandler).end();
-
-        // 自定义菜单事件
-        newRouter.rule().async(false).msgType(XmlMsgType.EVENT)
-                .event(MenuButtonType.CLICK).handler(this.menuHandler).end();
-
-        // 点击菜单连接事件
-        newRouter.rule().async(false).msgType(XmlMsgType.EVENT)
-                .event(MenuButtonType.VIEW).handler(this.nullHandler).end();
-
-        // 关注事件
-        newRouter.rule().async(false).msgType(XmlMsgType.EVENT)
-                .event(EventType.SUBSCRIBE).handler(this.subscribeHandler)
-                .end();
-
-        // 取消关注事件
-        newRouter.rule().async(false).msgType(XmlMsgType.EVENT)
-                .event(EventType.UNSUBSCRIBE)
-                .handler(this.unsubscribeHandler).end();
-
-        // 上报地理位置事件
-        newRouter.rule().async(false).msgType(XmlMsgType.EVENT)
-                .event(EventType.LOCATION).handler(this.locationHandler)
-                .end();
-
-        // 接收地理位置消息
-        newRouter.rule().async(false).msgType(XmlMsgType.LOCATION)
-                .handler(this.locationHandler).end();
-
-        // 扫码事件
-        newRouter.rule().async(false).msgType(XmlMsgType.EVENT)
-                .event(EventType.SCAN).handler(this.nullHandler).end();
-
-        // 默认
-        newRouter.rule().async(false).handler(this.msgHandler).end();
-
-        return newRouter;
-    }
-
-}

+ 1 - 1
carbon-h5/carbon-h5-service/src/main/java/com/hcloud/microserver/h5/config/RedissonConfig.java → carbon-h5/carbon-h5-service/src/main/java/com/hcloud/microserver/h5/config/redis/RedissonConfig.java

@@ -1,4 +1,4 @@
-package com.hcloud.microserver.h5.config;
+package com.hcloud.microserver.h5.config.redis;
 
 import org.redisson.Redisson;
 import org.redisson.api.RedissonClient;

+ 3 - 4
carbon-h5/carbon-h5-service/src/main/java/com/hcloud/microserver/h5/config/WxMaConfiguration.java → carbon-h5/carbon-h5-service/src/main/java/com/hcloud/microserver/h5/config/wx/WxMaConfiguration.java

@@ -1,8 +1,8 @@
-package com.hcloud.microserver.h5.config;
+package com.hcloud.microserver.h5.config.wx;
 
 import cn.binarywang.wx.miniapp.api.WxMaService;
 import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
-import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
+import cn.binarywang.wx.miniapp.config.WxMaInMemoryConfig;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
 import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
@@ -27,11 +27,10 @@ public class WxMaConfiguration {
     private String secret;
 
 
-
     @Bean
     @ConditionalOnMissingBean
     public WxMaService wxMaService() {
-        WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
+        WxMaInMemoryConfig config = new WxMaInMemoryConfig();
         config.setAppid(appId);
         config.setSecret(secret);
         WxMaService wxMaService = new WxMaServiceImpl();

+ 42 - 0
carbon-h5/carbon-h5-service/src/main/java/com/hcloud/microserver/h5/config/wx/WxMpConfiguration.java

@@ -0,0 +1,42 @@
+package com.hcloud.microserver.h5.config.wx;
+
+
+
+import lombok.extern.slf4j.Slf4j;
+import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
+import me.chanjar.weixin.mp.api.WxMpService;
+import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+@Slf4j
+@Configuration
+@ConditionalOnClass(WxMpService.class)
+@EnableConfigurationProperties(WxMpProperties.class)
+public class WxMpConfiguration {
+
+    private WxMpProperties properties;
+
+    @Autowired
+    public WxMpConfiguration(WxMpProperties properties) {
+        this.properties = properties;
+    }
+
+    @Bean
+    @ConditionalOnMissingBean
+    public WxMpService wxMpService() {
+        WxMpInMemoryConfigStorage configStorage = new WxMpInMemoryConfigStorage();
+        configStorage.setAppId(StringUtils.trimToNull(this.properties.getAppId()));
+        configStorage.setSecret(StringUtils.trimToNull(this.properties.getSecret()));
+        configStorage.setToken(StringUtils.trimToNull(this.properties.getToken()));
+        configStorage.setAesKey(StringUtils.trimToNull(this.properties.getAesKey()));
+        WxMpService wxMpService = new WxMpServiceImpl();
+        wxMpService.setWxMpConfigStorage(configStorage);
+        return wxMpService;
+    }
+}

+ 2 - 1
carbon-h5/carbon-h5-service/src/main/java/com/hcloud/microserver/h5/config/WxMpProperties.java → carbon-h5/carbon-h5-service/src/main/java/com/hcloud/microserver/h5/config/wx/WxMpProperties.java

@@ -1,4 +1,5 @@
-package com.hcloud.microserver.h5.config;
+package com.hcloud.microserver.h5.config.wx;
+
 
 
 import com.hcloud.microserver.commoncore.util.JsonUtils;

+ 1 - 1
carbon-h5/carbon-h5-service/src/main/java/com/hcloud/microserver/h5/config/WxPayConfiguration.java → carbon-h5/carbon-h5-service/src/main/java/com/hcloud/microserver/h5/config/wx/WxPayConfiguration.java

@@ -1,4 +1,4 @@
-package com.hcloud.microserver.h5.config;
+package com.hcloud.microserver.h5.config.wx;
 
 import com.github.binarywang.wxpay.config.WxPayConfig;
 import com.github.binarywang.wxpay.service.WxPayService;

+ 1 - 1
carbon-h5/carbon-h5-service/src/main/java/com/hcloud/microserver/h5/config/WxPayProperties.java → carbon-h5/carbon-h5-service/src/main/java/com/hcloud/microserver/h5/config/wx/WxPayProperties.java

@@ -1,4 +1,4 @@
-package com.hcloud.microserver.h5.config;
+package com.hcloud.microserver.h5.config.wx;
 
 import org.apache.commons.lang3.builder.ToStringBuilder;
 import org.apache.commons.lang3.builder.ToStringStyle;

+ 229 - 0
carbon-h5/carbon-h5-service/src/main/java/com/hcloud/microserver/h5/controller/web/WechatAppPayController.java

@@ -0,0 +1,229 @@
+package com.hcloud.microserver.h5.controller.web;
+
+import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
+import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
+import com.github.binarywang.wxpay.constant.WxPayConstants;
+import com.github.binarywang.wxpay.exception.WxPayException;
+import com.github.binarywang.wxpay.service.WxPayService;
+import com.hcloud.microserver.commoncore.annotation.AuthCarbonValidate;
+import com.hcloud.microserver.commoncore.base.BaseController;
+import com.hcloud.microserver.commoncore.base.ResponseBase;
+import com.hcloud.microserver.commoncore.util.GeneratorIdUtils;
+import com.hcloud.microserver.commoncore.util.UUIDUtils;
+import com.hcloud.microserver.facade.carbon.entity.GoodsOrderInfo;
+import com.hcloud.microserver.h5.entity.WxPayFrom;
+import com.hcloud.microserver.h5.service.OrderInfoService;
+import io.swagger.annotations.*;
+import lombok.extern.slf4j.Slf4j;
+import me.chanjar.weixin.common.bean.WxJsapiSignature;
+import me.chanjar.weixin.common.error.WxErrorException;
+import me.chanjar.weixin.mp.api.WxMpService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.*;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PrintWriter;
+import java.math.BigDecimal;
+
+@Slf4j
+@Controller
+@RequestMapping("/wechat/pay")
+public class WechatAppPayController extends BaseController {
+
+
+    @Autowired
+    private WxMpService wxMpService;
+
+    @Autowired
+    private WxPayService wxPayService;
+
+    @Autowired
+    private OrderInfoService orderInfoService;
+
+
+    @Value("${wx.auth.wxpaycallbackurl}")
+    private String wxpayCallbackUrl;
+
+    @ApiOperation(value = "微信支付接口(二次支付)", notes = "微信支付接口请勿随意调用(二次支付)")
+    @ApiImplicitParams({
+            @ApiImplicitParam(name = "orderId", value = "订单编号", dataType = "String", paramType = "query"),
+            @ApiImplicitParam(name = "tradeType", value = "交易方式(NATIVE,APP,JSAPI,MWEB)", dataType = "String", paramType = "query")
+    })
+    @ApiResponse(code = 500, message = "请求的配置参数有问题")
+    @AuthCarbonValidate
+    @PostMapping("/pay")
+    public ResponseBase pay(@RequestBody WxPayFrom wxPayFrom, HttpServletRequest request) {
+        String orderId = wxPayFrom.getOrderId();
+        String openid = wxPayFrom.getOpenid();
+        String tradeType = wxPayFrom.getTradeType();
+        GoodsOrderInfo goodsOrderInfo = orderInfoService.selectByPrimaryKey(orderId);
+        Integer status = goodsOrderInfo.getOrderStatus();
+        //查询订单是否支付
+        if (status != 1) {
+            throw new RuntimeException("订单已支付");
+        }
+        WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
+        //随机字符串
+        String s = UUIDUtils.randomUUID();
+
+        orderRequest.setNonceStr(s);
+        //商品描述
+        orderRequest.setBody("购碳扶贫");
+        //商户订单号(支付编号)
+        GeneratorIdUtils generatorIdUtils = new GeneratorIdUtils();
+        String orderNum = generatorIdUtils.nextId();
+        log.info("orderNum:" + orderNum);
+        //设置商户订单号
+        orderRequest.setOutTradeNo(orderNum);
+        //设置金额
+        //data.getTotalPrice();
+        BigDecimal money = goodsOrderInfo.getOrderAmount();
+        //元转成分
+        money = money.multiply(new BigDecimal(100));
+        int i = money.intValue();
+        if ("test".equals(tradeType)) {
+            //测试环境一分钱
+            orderRequest.setTotalFee(1);
+        } else {
+            orderRequest.setTotalFee(i);
+        }
+        //终端ip
+        String ipAddress = getIpAddress(request);
+        orderRequest.setSpbillCreateIp(ipAddress);
+        // 通知地址 支付成功后回调地址
+        log.info("wxpayCallbackUrl=================>{}", wxpayCallbackUrl);
+        orderRequest.setNotifyUrl(wxpayCallbackUrl);
+        //交易类型
+        orderRequest.setTradeType(WxPayConstants.TradeType.JSAPI);
+        //用户标识 获取用户openid
+        orderRequest.setOpenid(openid);
+        // 这个可能是偏向原生一点的统一下单,返回的参数有很多没用的 或者null值 建议使用 createOrder下单
+        Object unOrder = null;
+        try {
+            unOrder = wxPayService.createOrder(orderRequest);
+        } catch (WxPayException e) {
+            //e.printStackTrace();
+            log.error(e.getMessage());
+            //签名完成新增支付订单
+            return resultVOSuccess("微信支付失败");
+        }
+        //更新本地订单支付id
+        //orderClient.update(data);
+        orderInfoService.update(goodsOrderInfo, orderNum);
+        //签名完成新增支付订单
+        return resultVOSuccess(unOrder);
+    }
+
+
+    @ApiOperation(value = "微信支付结果回调", notes = "微信支付结果回调请勿直接调用")
+    @ApiResponse(code = 500, message = "请求的配置参数有问题")
+    @AuthCarbonValidate
+    @PostMapping("/payResultNotified")
+    public void payOrderResultNotify(HttpServletRequest request, HttpServletResponse response) throws IOException {
+        log.info("微信支付返回通知函数开始---------------------");
+
+        InputStream inStream = request.getInputStream();
+        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
+        byte[] buffer = new byte[1024];
+        int len = 0;
+        while ((len = inStream.read(buffer)) != -1) {
+            outSteam.write(buffer, 0, len);
+        }
+        outSteam.close();
+        inStream.close();
+        String result = new String(outSteam.toByteArray(), "utf-8");
+        boolean isPayOk = false;
+        WxPayOrderNotifyResult wxPayOrderNotifyResult = null;
+        // 此处调用订单查询接口验证是否交易成功
+        try {
+            wxPayOrderNotifyResult = wxPayService.parseOrderNotifyResult(result);
+            if ("SUCCESS".equals(wxPayOrderNotifyResult.getResultCode())) {
+                isPayOk = true;
+            }
+            log.info("解析数据:" + wxPayOrderNotifyResult.toString());
+        } catch (WxPayException e) {
+            e.printStackTrace();
+        }
+        String noticeStr = "";
+        // 支付成功,商户处理后同步返回给微信参数
+        PrintWriter writer = response.getWriter();
+        if (isPayOk) {
+            //建议在这里处理付款完成的业务(虽然前端也可以处理后续业务,但是前端处理并不安全,例如:客户突然关闭浏览器了等情况,付款成功后续的业务将中断)
+            //支付订单支付编号
+            System.out.println("===============付款成功,业务开始处理==============");
+            String orderNum = wxPayOrderNotifyResult.getOutTradeNo();
+            log.info("orderNum:" + orderNum);
+            //将订单更新为支付
+            // 更新订单信息(含商品订单,支付订单信息)
+            int i = orderInfoService.updateFullOrderInfo(orderNum, 2);
+            /**
+             * 自己的业务
+             */
+            System.out.println("===============付款成功,业务处理完毕==============");
+            // 通知微信已经收到消息,不要再给我发消息了,否则微信会8连击调用本接口
+            noticeStr = setXML("SUCCESS", "OK");
+            log.info("收到通知返回给微信api信息:-----------" + noticeStr);
+            writer.write(noticeStr);
+            writer.flush();
+        } else {
+            // 支付失败, 记录流水失败
+            noticeStr = setXML("FAIL", "");
+            writer.write(noticeStr);
+            writer.flush();
+            System.out.println("===============支付失败==============");
+        }
+    }
+
+    public static String setXML(String return_code, String return_msg) {
+        return "<xml><return_code><![CDATA[" + return_code + "]]></return_code><return_msg><![CDATA[" + return_msg + "]]></return_msg></xml>";
+    }
+
+    public static String getIpAddress(HttpServletRequest request) {
+        String ip = request.getHeader("x-forwarded-for");
+        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
+            ip = request.getHeader("Proxy-Client-IP");
+        }
+        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
+            ip = request.getHeader("WL-Proxy-Client-IP");
+        }
+        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
+            ip = request.getHeader("HTTP_CLIENT_IP");
+        }
+        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
+            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
+        }
+        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
+            ip = request.getRemoteAddr();
+        }
+        String[] split = ip.split(",");
+        ip = split[0];
+        return ip;
+    }
+
+
+    @ApiOperation(value = "微信js签名接口", notes = "微信js签名接口")
+    @ApiResponses({
+            @ApiResponse(code = 0, message = "成功")
+    })
+    @AuthCarbonValidate
+    @GetMapping("getJsapiTicket")
+    public ResponseBase getJsapiTicket(String url) {
+        WxJsapiSignature jsapiSignature = null;
+        try {
+            jsapiSignature = wxMpService.createJsapiSignature(url);
+
+        } catch (WxErrorException e) {
+            e.printStackTrace();
+            System.err.print(e.getError());
+        }
+        return resultVOSuccess(jsapiSignature);
+    }
+}
+
+

+ 130 - 132
carbon-h5/carbon-h5-service/src/main/java/com/hcloud/microserver/h5/controller/web/WechatManagerController.java

@@ -5,12 +5,6 @@ import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
 import com.github.binarywang.wxpay.constant.WxPayConstants;
 import com.github.binarywang.wxpay.exception.WxPayException;
 import com.github.binarywang.wxpay.service.WxPayService;
-import com.hcloud.microserver.h5.biz.WechatManagerComponent;
-import com.hcloud.microserver.h5.common.BaseInfoDO;
-import com.hcloud.microserver.h5.common.CarbonBaseController;
-import com.hcloud.microserver.h5.config.WxMpConfiguration;
-import com.hcloud.microserver.h5.service.OrderInfoService;
-import com.hcloud.microserver.h5.service.OrderPayService;
 import com.hcloud.microserver.commoncore.annotation.AuthCarbonValidate;
 import com.hcloud.microserver.commoncore.base.ResponseBase;
 import com.hcloud.microserver.commoncore.base.ResultVO;
@@ -23,6 +17,11 @@ import com.hcloud.microserver.commoncore.util.UUIDUtils;
 import com.hcloud.microserver.facade.carbon.forms.CustomerInfoForm;
 import com.hcloud.microserver.facade.carbon.forms.GoodsOrderInfoForm;
 import com.hcloud.microserver.facade.carbon.forms.GoodsPayOrderForm;
+import com.hcloud.microserver.h5.biz.WechatManagerComponent;
+import com.hcloud.microserver.h5.common.BaseInfoDO;
+import com.hcloud.microserver.h5.common.CarbonBaseController;
+import com.hcloud.microserver.h5.service.OrderInfoService;
+import com.hcloud.microserver.h5.service.OrderPayService;
 import io.swagger.annotations.*;
 import lombok.extern.slf4j.Slf4j;
 import me.chanjar.weixin.common.bean.WxJsapiSignature;
@@ -30,7 +29,6 @@ import me.chanjar.weixin.common.error.WxErrorException;
 import me.chanjar.weixin.common.util.http.URIUtil;
 import me.chanjar.weixin.mp.api.WxMpService;
 import me.chanjar.weixin.mp.api.WxMpUserService;
-import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
 import me.chanjar.weixin.mp.bean.result.WxMpUser;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
@@ -55,15 +53,15 @@ import java.util.concurrent.TimeUnit;
 @Api(description = "H5微信api服务")
 public class WechatManagerController extends CarbonBaseController {
 
-    private static final String WECHAT_AUTH_SCOPE="snsapi_userinfo";
+    private static final String WECHAT_AUTH_SCOPE = "snsapi_userinfo";
 
-    private static final String WECHAT_AUTH_BASE_SCOPE="snsapi_base";
+    private static final String WECHAT_AUTH_BASE_SCOPE = "snsapi_base";
 
-    private static final String WECHAT_USER_INFO="wechatUserInfo";
+    private static final String WECHAT_USER_INFO = "wechatUserInfo";
 
-    private static final  String WECHAT_PAY_FLAG_TEST="test";
+    private static final String WECHAT_PAY_FLAG_TEST = "test";
 
-    private static final String WECHAT_INFO_PREFIX="weChatInfoPrefix_";
+    private static final String WECHAT_INFO_PREFIX = "weChatInfoPrefix_";
 
     @Value("${wx.mp.appId}")
     private String appid;
@@ -95,82 +93,79 @@ public class WechatManagerController extends CarbonBaseController {
     private WxPayService wxPayService;
 
     @Autowired
-    private OrderInfoService orderClient;
+    private OrderInfoService orderInfoService;
 
     @Autowired
-    private OrderPayService orderPayClient;
+    private OrderPayService orderPayService;
 
     @Autowired
     private RedisUtils redisUtils;
 
-    @ApiOperation(value = "微信登录",notes = "微信登录")
+    @ApiOperation(value = "微信登录", notes = "微信登录")
     @ApiImplicitParams({
-            @ApiImplicitParam(name = "furl",value = "授权成功后的", dataType = "String",paramType = "query"),
-            @ApiImplicitParam(name = "authScope",value = "授权范围", dataType = "Integer",paramType = "query"),
-            @ApiImplicitParam(name = "token",value = "当前用户token", dataType = "String",paramType = "query")
+            @ApiImplicitParam(name = "furl", value = "授权成功后的", dataType = "String", paramType = "query"),
+            @ApiImplicitParam(name = "authScope", value = "授权范围", dataType = "Integer", paramType = "query"),
+            @ApiImplicitParam(name = "token", value = "当前用户token", dataType = "String", paramType = "query")
     })
-    @ApiResponse(code =0,message = "查询成功")
+    @ApiResponse(code = 0, message = "查询成功")
     @GetMapping("/login")
-   @AuthCarbonValidate
+    @AuthCarbonValidate
     public void login(@RequestParam("furl") String furl,
                       Integer authScope,
-                      String token){
-        if(null!=furl && !"".equals(weChatForwardUrl)){
+                      String token) {
+        if (null != furl && !"".equals(weChatForwardUrl)) {
             weChatForwardUrl = furl;
         }
-        if(Objects.nonNull(token)){
+        if (Objects.nonNull(token)) {
             BaseInfoDO baseInfoDO = this.initiSaveObject(token);
-            if(Objects.nonNull(baseInfoDO)){
+            if (Objects.nonNull(baseInfoDO)) {
                 //登录失效跳转登录首页
-                currentCustomerId=baseInfoDO.getCustomerId();
-                }
+                currentCustomerId = baseInfoDO.getCustomerId();
+            }
             globalToken = token;
 
         }
-        log.info("currentCustomerId is ================>{}",currentCustomerId);
-        final WxMpService wxMpService = WxMpConfiguration.getMpServices().get(appid);
+        log.info("currentCustomerId is ================>{}", currentCustomerId);
         String authUrls = "";
-        if(authScope==2){
-            authUrls= wxMpService.getOAuth2Service().buildAuthorizationUrl(weChatBaseUrl,WECHAT_AUTH_BASE_SCOPE, URIUtil.encodeURIComponent(weChatForwardUrl));
-        }else{
-            authUrls= wxMpService.getOAuth2Service().buildAuthorizationUrl(wechatRedirectUrl,WECHAT_AUTH_SCOPE, URIUtil.encodeURIComponent(weChatForwardUrl));
+        if (authScope == 2) {
+            authUrls = wxMpService.oauth2buildAuthorizationUrl(weChatBaseUrl, WECHAT_AUTH_BASE_SCOPE, URIUtil.encodeURIComponent(weChatForwardUrl));
+        } else {
+            authUrls = wxMpService.oauth2buildAuthorizationUrl(wechatRedirectUrl, WECHAT_AUTH_SCOPE, URIUtil.encodeURIComponent(weChatForwardUrl));
         }
         try {
-            log.info("authUrls===============>{}",authUrls);
+            log.info("authUrls===============>{}", authUrls);
             this.getResponseObject().sendRedirect(authUrls);
         } catch (Exception e) {
             e.printStackTrace();
-            log.error("请求微信权限地址错误请检查配置参数,配置的url:{}",authUrls);
+            log.error("请求微信权限地址错误请检查配置参数,配置的url:{}", authUrls);
         }
     }
 
-    @ApiOperation(value = "获取微信用户基本信息",notes = "微信静默授权接口请勿随意调用")
-    @ApiResponse(code =500,message = "请求的配置参数有问题")
+    @ApiOperation(value = "获取微信用户基本信息", notes = "微信静默授权接口请勿随意调用")
+    @ApiResponse(code = 500, message = "请求的配置参数有问题")
     @GetMapping("/baseLogin")
     @AuthCarbonValidate
-    public void baseLogin(@RequestParam("code") String code){
-        log.info("currentCustomerId======================>{}",currentCustomerId);
-        log.info("global token==========================>{}",globalToken);
-        if(null!=code && !"".equals(code)){
-            log.info("微信权限认证code是====================>{}",code);
-            final WxMpService wxMpService = WxMpConfiguration.getMpServices().get(appid);
+    public void baseLogin(@RequestParam("code") String code) {
+        log.info("currentCustomerId======================>{}", currentCustomerId);
+        log.info("global token==========================>{}", globalToken);
+        if (null != code && !"".equals(code)) {
+            log.info("微信权限认证code是====================>{}", code);
             try {
-
-                WxMpOAuth2AccessToken accessToken = wxMpService.getOAuth2Service().getAccessToken(code);
+                String accessToken = wxMpService.getAccessToken();
 //                WxMpOAuth2AccessToken accessToken = wxMpService.oauth2getAccessToken(code);
-                if(accessToken!=null ){
-                    log.info("accessToken object is:{}",accessToken);
+                if (accessToken != null) {
+                    log.info("accessToken object is:{}", accessToken);
                     WxMpUserService userService = wxMpService.getUserService();
-                    WxMpUser wxMpUser = userService.userInfo(accessToken.getAccessToken());
+                    WxMpUser wxMpUser = userService.userInfo(accessToken);
 //                    WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(accessToken,"");
-                    log.info("wxMpUser object is:{}",wxMpUser);
-                    if(null!=currentCustomerId && !"".equals(currentCustomerId)){
+                    log.info("wxMpUser object is:{}", wxMpUser);
+                    if (null != currentCustomerId && !"".equals(currentCustomerId)) {
                         //微信授权信息写入登录缓存用户微信支付
                         Map resultMap = (Map) redisUtils.getValue(globalToken);
-                        if(Objects.nonNull(resultMap)){
-                            resultMap.put(GlobleConstant.WECHAT_INFO_PREFIX,wxMpUser);
+                        if (Objects.nonNull(resultMap)) {
+                            resultMap.put(GlobleConstant.WECHAT_INFO_PREFIX, wxMpUser);
                         }
-                        redisUtils.setValue(globalToken,resultMap, GlobleConstant.TOKEN_EXPIRES_SECOND,TimeUnit.SECONDS);
+                        redisUtils.setValue(globalToken, resultMap, GlobleConstant.TOKEN_EXPIRES_SECOND, TimeUnit.SECONDS);
                     }
                     this.getResponseObject().sendRedirect(weChatForwardUrl);
                 }
@@ -181,31 +176,30 @@ public class WechatManagerController extends CarbonBaseController {
         }
     }
 
-    @ApiOperation(value = "获取微信用户信息",notes = "微信回调接口请勿直接请求")
-    @ApiResponse(code =500,message = "请求的配置参数有问题")
+    @ApiOperation(value = "获取微信用户信息", notes = "微信回调接口请勿直接请求")
+    @ApiResponse(code = 500, message = "请求的配置参数有问题")
     @GetMapping("/doLogin")
     @AuthCarbonValidate
-    public void doLogin(@RequestParam("code") String code){
-        if(null!=code && !"".equals(code)){
-            log.info("微信权限认证code是====================>{}",code);
-           final WxMpService wxMpService = WxMpConfiguration.getMpServices().get(appid);
+    public void doLogin(@RequestParam("code") String code) {
+        if (null != code && !"".equals(code)) {
+            log.info("微信权限认证code是====================>{}", code);
             try {
-                WxMpOAuth2AccessToken accessToken = wxMpService.getOAuth2Service().getAccessToken(code);
+                String accessToken = wxMpService.getAccessToken();
 //                WxMpOAuth2AccessToken accessToken = wxMpService.oauth2getAccessToken(code);
-                if(accessToken!=null ){
-                  log.info("accessToken object is:{}",accessToken);
+                if (accessToken != null) {
+                    log.info("accessToken object is:{}", accessToken);
                     WxMpUserService userService = wxMpService.getUserService();
-                    WxMpUser wxMpUser = userService.userInfo(accessToken.getAccessToken());
+                    WxMpUser wxMpUser = userService.userInfo(accessToken);
 //                  WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(accessToken,"");
-                  log.info("wxMpUser object is:{}",wxMpUser);
-                  Map map = weChatManager.getWechatAccessToken(wxMpUser);
-                  if(null!=map && map.size()>0){
-                      String  token = (String) map.get(GlobleConstant.ACCESS_TOKEN);
-                      log.info("redirectUrl======================>{}",weChatForwardUrl+"?accessToken="+token);
-                      this.getResponseObject().sendRedirect(weChatForwardUrl+"?accessToken="+token);
-                  }else {
-                      this.getResponseObject().sendRedirect(weChatForwardUrl);
-                  }
+                    log.info("wxMpUser object is:{}", wxMpUser);
+                    Map map = weChatManager.getWechatAccessToken(wxMpUser);
+                    if (null != map && map.size() > 0) {
+                        String token = (String) map.get(GlobleConstant.ACCESS_TOKEN);
+                        log.info("redirectUrl======================>{}", weChatForwardUrl + "?accessToken=" + token);
+                        this.getResponseObject().sendRedirect(weChatForwardUrl + "?accessToken=" + token);
+                    } else {
+                        this.getResponseObject().sendRedirect(weChatForwardUrl);
+                    }
                 }
             } catch (Exception e) {
                 log.error("微信参数错误,请查看参数配置谢谢");
@@ -214,40 +208,40 @@ public class WechatManagerController extends CarbonBaseController {
         }
     }
 
-    @ApiOperation(value = "退出登录",notes = "退出登录,删除缓存信息")
-    @ApiResponse(code =500,message = "请求的配置参数有问题")
+    @ApiOperation(value = "退出登录", notes = "退出登录,删除缓存信息")
+    @ApiResponse(code = 500, message = "请求的配置参数有问题")
     @GetMapping("/logout")
     @AuthCarbonValidate
-    public ResponseBase logout(){
+    public ResponseBase logout() {
         BaseInfoDO baseInfoDO = this.initiSaveObject();
-        if(baseInfoDO==null){responseError(new ResultVO(ResultEnum.TOKEN_EXPIRED));}
+        if (baseInfoDO == null) {
+            responseError(new ResultVO(ResultEnum.TOKEN_EXPIRED));
+        }
         String accessToken = this.getRequestObject().getHeader(ACCESS_TOKEN);
         redisUtils.deleteKey(accessToken);
         return responseSuccess(new ResultVO(ResultEnum.SUCCESS));
     }
 
 
-
-
-    @ApiOperation(value = "微信支付接口(二次支付)",notes = "微信支付接口请勿随意调用(二次支付)")
+    @ApiOperation(value = "微信支付接口(二次支付)", notes = "微信支付接口请勿随意调用(二次支付)")
     @ApiImplicitParams({
-            @ApiImplicitParam(name = "orderId",value = "订单编号", dataType = "String",paramType = "query"),
-            @ApiImplicitParam(name = "tradeType",value = "交易方式(NATIVE,APP,JSAPI,MWEB)", dataType = "String",paramType = "query")
+            @ApiImplicitParam(name = "orderId", value = "订单编号", dataType = "String", paramType = "query"),
+            @ApiImplicitParam(name = "tradeType", value = "交易方式(NATIVE,APP,JSAPI,MWEB)", dataType = "String", paramType = "query")
     })
-    @ApiResponse(code =500,message = "请求的配置参数有问题")
+    @ApiResponse(code = 500, message = "请求的配置参数有问题")
     @AuthCarbonValidate
     @GetMapping("/pay")
     public ResponseBase pay(@RequestParam("orderId") String orderId,
-                            @RequestParam("tradeType") String tradeType){
+                            @RequestParam("tradeType") String tradeType) {
         try {
             BaseInfoDO baseInfoDO = this.initiSaveObject();
             WxMpUser wxMpUser = this.initiWwChatInfo();
-            if(Objects.isNull(baseInfoDO)){
+            if (Objects.isNull(baseInfoDO)) {
                 return responseError(new ResultVO(ResultEnum.TOKEN_EXPIRED));
             }
             //验证商品订单是否已经支付
-            GoodsOrderInfoForm orderInfoById = orderClient.getOrderInfoById(orderId);
-            if(orderInfoById==null){
+            GoodsOrderInfoForm orderInfoById = orderInfoService.getOrderInfoById(orderId);
+            if (orderInfoById == null) {
                 return responseEnum(ResultEnum.ORDER_PAY_DUPLICATE);
             }
 //            Map orderInfoMap = (Map) resultVO.getData();
@@ -255,38 +249,40 @@ public class WechatManagerController extends CarbonBaseController {
 //            Double payMoney = (Double) orderInfoMap.get("orderAmount");
 //            Double orderCarbonAmount = (Double) orderInfoMap.get("orderCarbonAmount");
 //            JavaBeanUtils.mapToEntity(orderInfoMap, GoodsOrderInfoForm.class);
-            GoodsOrderInfoForm orderInfoForm =  orderInfoById;
+            GoodsOrderInfoForm orderInfoForm = orderInfoById;
             Double payMoney = Double.valueOf(orderInfoById.getOrderAmount().toString());
             Double orderCarbonAmount = Double.valueOf(orderInfoById.getOrderCarbonAmount().toString());
-            log.info("orderInfo===================>{}",orderInfoForm);
-            if(orderInfoForm.getOrderStatus()!=1){
+            log.info("orderInfo===================>{}", orderInfoForm);
+            if (orderInfoForm.getOrderStatus() != 1) {
                 return responseError(new ResultVO(ResultEnum.ORDER_PAY_COMPLETE));
             }
             CustomerInfoForm customerInfoForm = weChatManager.getCustomerInfoByCustomerId(orderInfoForm.getFkCustomerGuid());
-            log.info("customerInfo=======================>{}",customerInfoForm);
+            log.info("customerInfo=======================>{}", customerInfoForm);
             //生成支付订单,并返回支付订单编号
             BigDecimal orderAmount = BigDecimal.valueOf(payMoney);
             orderInfoForm.setOrderAmount(orderAmount);
             String payNo = this.insertPayOrderInfo(orderInfoForm);
-            if(payNo==null){return responseError(new ResultVO(308,"支付订单生成失败"));}
-            log.info("pay order no=======================>{}",payNo);
+            if (payNo == null) {
+                return responseError(new ResultVO(308, "支付订单生成失败"));
+            }
+            log.info("pay order no=======================>{}", payNo);
             //调用微信统一下单接口
-            log.info("money=====================>{}",payMoney);
+            log.info("money=====================>{}", payMoney);
             Object unOrder = null;
-            if(WxPayConstants.TradeType.JSAPI.equals(tradeType)){
-                unOrder = this.wxUnifiedOrder(payNo,orderAmount,tradeType,wxMpUser.getOpenId());
-            }else{
-                unOrder = this.wxUnifiedOrder(payNo,orderAmount,tradeType,null);
+            if (WxPayConstants.TradeType.JSAPI.equals(tradeType)) {
+                unOrder = this.wxUnifiedOrder(payNo, orderAmount, tradeType, wxMpUser.getOpenId());
+            } else {
+                unOrder = this.wxUnifiedOrder(payNo, orderAmount, tradeType, null);
             }
-            log.info("pay order result======================>{}",unOrder);
+            log.info("pay order result======================>{}", unOrder);
             //支付倒计时
-            GoodsPayOrderForm payOrderForm = orderPayClient.getPayOrderByNo(payNo);
-//            ResultVO payOrderVo = orderPayClient.getPayOrderInfoByPayNo(payNo);
+            GoodsPayOrderForm payOrderForm = orderPayService.getPayOrderByNo(payNo);
+//            ResultVO payOrderVo = orderPayService.getPayOrderInfoByPayNo(payNo);
 //            Map payOrderMap = (Map) payOrderVo.getData();
 //            log.info("payOrderMap=================>{}",payOrderMap);
 //            GoodsPayOrderForm payOrderForm = JavaBeanUtils.mapToEntity(payOrderMap, GoodsPayOrderForm.class);
-            String orderKey ="ord:"+payOrderForm.getOrderNo();
-            redisUtils.setValue(orderKey,payOrderForm,900,TimeUnit.SECONDS);
+            String orderKey = "ord:" + payOrderForm.getOrderNo();
+            redisUtils.setValue(orderKey, payOrderForm, 900, TimeUnit.SECONDS);
             return responseSuccess(success(unOrder));
         } catch (Exception ex) {
             ex.printStackTrace();
@@ -294,11 +290,11 @@ public class WechatManagerController extends CarbonBaseController {
         }
     }
 
-    @ApiOperation(value = "微信支付结果回调",notes = "微信支付结果回调请勿直接调用")
-    @ApiResponse(code =500,message = "请求的配置参数有问题")
+    @ApiOperation(value = "微信支付结果回调", notes = "微信支付结果回调请勿直接调用")
+    @ApiResponse(code = 500, message = "请求的配置参数有问题")
     @AuthCarbonValidate
     @PostMapping("/payResultNotified")
-    public String payOrderResultNotify(HttpServletRequest request){
+    public String payOrderResultNotify(HttpServletRequest request) {
         String xmlResult = HttpKit.readData(request);
         boolean isPayOk = false;
         WxPayOrderNotifyResult wxPayOrderNotifyResult = null;
@@ -307,26 +303,26 @@ public class WechatManagerController extends CarbonBaseController {
             if (WxPayConstants.ResultCode.SUCCESS.equals(wxPayOrderNotifyResult.getResultCode())) {
                 isPayOk = true;
             }
-            log.info("WxPayOrderNotifyResult is ===================>{}",wxPayOrderNotifyResult);
-            if(isPayOk){
+            log.info("WxPayOrderNotifyResult is ===================>{}", wxPayOrderNotifyResult);
+            if (isPayOk) {
                 String payNo = wxPayOrderNotifyResult.getOutTradeNo();
                 // 更新订单信息(含商品订单,支付订单信息)
-                int i = orderClient.updateFullOrderInfo(payNo, 2);
-//                ResultVO resultVO = orderClient.updateOrderInfoAndPayOrderInfo(payNo);
-                if(i<1){
+                int i = orderInfoService.updateFullOrderInfo(payNo, 2);
+//                ResultVO resultVO = orderInfoService.updateOrderInfoAndPayOrderInfo(payNo);
+                if (i < 1) {
                     log.error("更新订单信息失败,请联系开发人员");
                     return setXML("FAIL", "");
                 }
                 //删除已支付成功的支付订单缓存信息
-                GoodsPayOrderForm goodsPayOrderForm = orderPayClient.getPayOrderByNo(payNo);
+                GoodsPayOrderForm goodsPayOrderForm = orderPayService.getPayOrderByNo(payNo);
                 GoodsPayOrderForm payOrderForm = goodsPayOrderForm;
-//                        ResultVO payOrderVo = orderPayClient.getPayOrderInfoByPayNo(payNo);
+//                        ResultVO payOrderVo = orderPayService.getPayOrderInfoByPayNo(payNo);
 //                Map payOrderMap = (Map) payOrderVo.getData();
 //                GoodsPayOrderForm payOrderForm = JavaBeanUtils.mapToEntity(payOrderMap, GoodsPayOrderForm.class);
-                redisUtils.deleteKey("ord:"+payOrderForm.getOrderNo());
+                redisUtils.deleteKey("ord:" + payOrderForm.getOrderNo());
                 //返回响应信息给微信接口
                 return setXML("SUCCESS", "OK");
-            }else {
+            } else {
                 // 支付失败, 记录流水失败
                 return setXML("FAIL", "");
             }
@@ -337,7 +333,8 @@ public class WechatManagerController extends CarbonBaseController {
         return setXML("FAIL", "");
     }
 
-
+    @Autowired
+    private WxMpService wxMpService;
 
     @ApiOperation(value = "微信js签名接口", notes = "微信js签名接口")
     @ApiResponses({
@@ -346,7 +343,6 @@ public class WechatManagerController extends CarbonBaseController {
     @AuthCarbonValidate
     @GetMapping("getJsapiTicket")
     public ResponseBase getJsapiTicket(String url) {
-        final WxMpService wxMpService = WxMpConfiguration.getMpServices().get(appid);
         WxJsapiSignature jsapiSignature = null;
         ResultVO resultVO = new ResultVO();
         try {
@@ -368,23 +364,24 @@ public class WechatManagerController extends CarbonBaseController {
     })
     @AuthCarbonValidate
     @GetMapping("/checkWxMap")
-    public ResponseBase checkWxMap(){
+    public ResponseBase checkWxMap() {
         Map resultMap = new HashMap();
         WxMpUser wxMpUser = this.initiWwChatInfo();
-        if(Objects.nonNull(wxMpUser)){
-            resultMap.put("status",1);
+        if (Objects.nonNull(wxMpUser)) {
+            resultMap.put("status", 1);
             return responseSuccess(success(resultMap));
         }
-        resultMap.put("status",0);
+        resultMap.put("status", 0);
         return responseError(success(resultMap));
     }
 
     /**
      * 生成支付订单
+     *
      * @param orderInfoForm
      */
-    private String insertPayOrderInfo(GoodsOrderInfoForm orderInfoForm){
-        if(null!= orderInfoForm && !"".equals(orderInfoForm.getOrderNo())){
+    private String insertPayOrderInfo(GoodsOrderInfoForm orderInfoForm) {
+        if (null != orderInfoForm && !"".equals(orderInfoForm.getOrderNo())) {
             GeneratorIdUtils generatorIdUtils = new GeneratorIdUtils();
             String orderNum = generatorIdUtils.nextId();
             GoodsPayOrderForm goodsPayOrderForm = new GoodsPayOrderForm();
@@ -396,10 +393,10 @@ public class WechatManagerController extends CarbonBaseController {
             goodsPayOrderForm.setPayStatus(1);
             goodsPayOrderForm.setPayNo(orderNum);
             goodsPayOrderForm.setPayTime(new Date());
-            log.info("goodsPayOrderForm==================>{}",goodsPayOrderForm);
-            int i =  orderPayClient.saveSelective(goodsPayOrderForm);
-//            ResultVO resultVO = orderPayClient.savePayOrderInfo(goodsPayOrderForm);
-            if(i>0){
+            log.info("goodsPayOrderForm==================>{}", goodsPayOrderForm);
+            int i = orderPayService.saveSelective(goodsPayOrderForm);
+//            ResultVO resultVO = orderPayService.savePayOrderInfo(goodsPayOrderForm);
+            if (i > 0) {
                 return orderNum;
             }
         }
@@ -408,14 +405,15 @@ public class WechatManagerController extends CarbonBaseController {
 
     /**
      * 微信统一下单
-     * @param payNo 支付订单号
-     * @param money 支付金额
+     *
+     * @param payNo     支付订单号
+     * @param money     支付金额
      * @param tradeType 交易类型
-     * @param wxId 微信openid(只用于jsaip交易方式)
+     * @param wxId      微信openid(只用于jsaip交易方式)
      * @return
      * @throws WxPayException
      */
-    private Object wxUnifiedOrder(String payNo,BigDecimal money,String tradeType,String wxId) throws WxPayException {
+    private Object wxUnifiedOrder(String payNo, BigDecimal money, String tradeType, String wxId) throws WxPayException {
         WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
         orderRequest.setNonceStr(UUIDUtils.randomUUID());
         //商品描述
@@ -425,9 +423,9 @@ public class WechatManagerController extends CarbonBaseController {
         //元转成分
         BigDecimal cmoney = money.multiply(new BigDecimal(100));
         int i = cmoney.intValue();
-        if(WECHAT_PAY_FLAG_TEST.equalsIgnoreCase(payFlag)){
+        if (WECHAT_PAY_FLAG_TEST.equalsIgnoreCase(payFlag)) {
             orderRequest.setTotalFee(1);
-        }else{
+        } else {
             orderRequest.setTotalFee(i);
         }
         //终端ip
@@ -438,7 +436,7 @@ public class WechatManagerController extends CarbonBaseController {
         //交易类型
         orderRequest.setTradeType(tradeType);
         //用户标识 获取用户openid
-        if(wxId!=null){
+        if (wxId != null) {
             orderRequest.setOpenid(wxId);
         }
         // 这个可能是偏向原生一点的统一下单,返回的参数有很多没用的 或者null值 建议使用 createOrder下单

+ 2 - 1
carbon-h5/carbon-h5-service/src/main/java/com/hcloud/microserver/h5/dao/CustomerCarbonValMapper.java

@@ -2,10 +2,11 @@ package com.hcloud.microserver.h5.dao;
 
 import com.hcloud.microserver.facade.carbon.entity.CustomerCarbonVal;
 import com.hcloud.microserver.facade.carbon.entity.CustomerCarbonValExample;
+import org.apache.ibatis.annotations.Mapper;
 import org.apache.ibatis.annotations.Param;
 
 import java.util.List;
-
+@Mapper
 public interface CustomerCarbonValMapper {
     int countByExample(CustomerCarbonValExample example);
 

+ 2 - 0
carbon-h5/carbon-h5-service/src/main/java/com/hcloud/microserver/h5/dao/GoodsOrderInfoMapper.java

@@ -5,6 +5,7 @@ import com.hcloud.microserver.commoncore.base.BaseMapper;
 import com.hcloud.microserver.commoncore.base.PageBean;
 import com.hcloud.microserver.facade.carbon.entity.GoodsOrderInfo;
 import com.hcloud.microserver.facade.carbon.forms.GoodsOrderInfoForm;
+import org.apache.ibatis.annotations.Mapper;
 import org.apache.ibatis.annotations.Param;
 
 import java.util.List;
@@ -12,6 +13,7 @@ import java.util.List;
 /**
  * @author xiezt
  */
+@Mapper
 public interface GoodsOrderInfoMapper extends BaseMapper<GoodsOrderInfo,String> {
     /**
      * 分页查询订单信息

+ 14 - 0
carbon-h5/carbon-h5-service/src/main/java/com/hcloud/microserver/h5/entity/WxPayFrom.java

@@ -0,0 +1,14 @@
+package com.hcloud.microserver.h5.entity;
+
+import lombok.Data;
+
+@Data
+public class WxPayFrom {
+
+    private String orderId;
+
+    private String openid;
+
+    private String tradeType;
+
+}

+ 21 - 0
carbon-h5/carbon-h5-service/src/main/java/com/hcloud/microserver/h5/events/CustomerCarbonValEvent.java

@@ -0,0 +1,21 @@
+package com.hcloud.microserver.h5.events;
+
+import lombok.Getter;
+import org.springframework.context.ApplicationEvent;
+
+/**
+ * 个人购碳数据
+ */
+@Getter
+public class CustomerCarbonValEvent extends ApplicationEvent {
+    /**
+     * 订单id
+     */
+    private String orderId;
+
+
+    public CustomerCarbonValEvent(Object source, String orderId) {
+        super(source);
+        this.orderId = orderId;
+    }
+}

+ 61 - 0
carbon-h5/carbon-h5-service/src/main/java/com/hcloud/microserver/h5/listens/CustomerCarbonValListener.java

@@ -0,0 +1,61 @@
+package com.hcloud.microserver.h5.listens;
+
+import com.hcloud.microserver.commoncore.text.UUID;
+import com.hcloud.microserver.commoncore.util.GetUUID;
+import com.hcloud.microserver.commoncore.util.UUIDUtils;
+import com.hcloud.microserver.commoncore.util.reflect.DateUtils;
+import com.hcloud.microserver.facade.carbon.entity.CustomerCarbonVal;
+import com.hcloud.microserver.facade.carbon.entity.GoodsOrderInfo;
+import com.hcloud.microserver.h5.dao.CustomerCarbonValMapper;
+import com.hcloud.microserver.h5.dao.GoodsOrderInfoMapper;
+import com.hcloud.microserver.h5.events.CredentialInfoEvent;
+import com.hcloud.microserver.h5.events.CustomerCarbonValEvent;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.event.EventListener;
+import org.springframework.scheduling.annotation.Async;
+import org.springframework.stereotype.Component;
+
+import java.util.Date;
+
+@Slf4j
+@Component
+public class CustomerCarbonValListener {
+
+    @Autowired
+    CustomerCarbonValMapper customerCarbonValMapper;
+
+    @Autowired
+    GoodsOrderInfoMapper goodsOrderInfoMapper;
+
+    @Async
+    @EventListener
+    public void generateCredentialInfo(CustomerCarbonValEvent credentialInfoEvent) {
+        String orderId = credentialInfoEvent.getOrderId();
+
+        GoodsOrderInfo goodsOrderInfo = goodsOrderInfoMapper.selectByPrimaryKey(orderId);
+        CustomerCarbonVal record = new CustomerCarbonVal();
+        record.setGuid(GetUUID.getUUID());
+        //购买的碳汇量
+        record.setCarbonVal(goodsOrderInfo.getOrderCarbonAmount());
+        //创建时间
+        record.setCreateTime(new Date());
+        //数据来源表id
+        record.setTbGuid(orderId);
+        //数据来源表名称
+        record.setTbName("t_goods_order_info");
+        //
+        record.settCustomerId(goodsOrderInfo.getFkCustomerGuid());
+
+        record.settCustomerName(goodsOrderInfo.getCustomerName());
+        //类型 1购买碳汇 2企业碳中和 3大型活动碳中和 4碳履约
+        record.setType(1);
+        //状态 1 新增 0 减去
+        record.setStatus(1);
+        //
+        record.setRemarks("购买碳汇数据");
+        //获取年份
+        record.setYearTime(Integer.parseInt(DateUtils.year()));
+        customerCarbonValMapper.insertSelective(record);
+    }
+}

+ 15 - 2
carbon-h5/carbon-h5-service/src/main/java/com/hcloud/microserver/h5/service/OrderInfoService.java

@@ -9,10 +9,13 @@ import com.hcloud.microserver.facade.carbon.forms.GoodsOrderInfoForm;
 /**
  * @author xiezt
  */
-public interface OrderInfoService extends BaseServie<GoodsOrderInfoForm,String> {
+public interface OrderInfoService extends BaseServie<GoodsOrderInfoForm, String> {
+
+    public GoodsOrderInfo selectByPrimaryKey(String guid);
 
     /**
      * 分页查询订单信息
+     *
      * @param goodsOrderInfoForm
      * @return
      */
@@ -20,6 +23,7 @@ public interface OrderInfoService extends BaseServie<GoodsOrderInfoForm,String>
 
     /**
      * 通过用户Id查询订单信息(分页信息)
+     *
      * @param goodsOrderInfoForm
      * @return
      */
@@ -27,6 +31,7 @@ public interface OrderInfoService extends BaseServie<GoodsOrderInfoForm,String>
 
     /**
      * 获取订单信息
+     *
      * @param orderId
      * @return
      */
@@ -34,6 +39,7 @@ public interface OrderInfoService extends BaseServie<GoodsOrderInfoForm,String>
 
     /**
      * 逻辑删除订单
+     *
      * @param orderId
      * @return
      */
@@ -41,6 +47,7 @@ public interface OrderInfoService extends BaseServie<GoodsOrderInfoForm,String>
 
     /**
      * 统一下单(生成订单,订单详情,支付订单)
+     *
      * @param goodsOrderInfoForm
      * @return
      */
@@ -48,14 +55,16 @@ public interface OrderInfoService extends BaseServie<GoodsOrderInfoForm,String>
 
     /**
      * 支付成功后回调更新(订单信息,支付流水信息,证书信息)
+     *
      * @param payNo
      * @param state
      * @return
      */
-    int updateFullOrderInfo(String payNo,Integer state);
+    int updateFullOrderInfo(String payNo, Integer state);
 
     /**
      * 回滚订单信息
+     *
      * @param orderId
      * @return
      */
@@ -63,6 +72,7 @@ public interface OrderInfoService extends BaseServie<GoodsOrderInfoForm,String>
 
     /**
      * 通过订单编号查询订单信息
+     *
      * @param orderNo
      * @return
      */
@@ -70,6 +80,7 @@ public interface OrderInfoService extends BaseServie<GoodsOrderInfoForm,String>
 
     /**
      * 为离线支付申请生成订单信息
+     *
      * @param goodsOrderInfoForm
      * @return
      */
@@ -77,4 +88,6 @@ public interface OrderInfoService extends BaseServie<GoodsOrderInfoForm,String>
 
 
     GoodsOrderInfo createOrder(CreateOrderFrom createOrderFrom);
+
+    void update(GoodsOrderInfo goodsOrderInfo, String orderNum);
 }

+ 44 - 9
carbon-h5/carbon-h5-service/src/main/java/com/hcloud/microserver/h5/service/impl/OrderInfoServiceImpl.java

@@ -2,25 +2,20 @@ package com.hcloud.microserver.h5.service.impl;
 
 import com.github.pagehelper.PageHelper;
 import com.github.pagehelper.PageInfo;
-import com.hcloud.microserver.commoncore.base.ResultVO;
-import com.hcloud.microserver.commoncore.enums.ResultEnum;
-import com.hcloud.microserver.facade.carbon.entity.GoodsOrderDetail;
+import com.hcloud.microserver.facade.carbon.entity.*;
 import com.hcloud.microserver.facade.carbon.entity.from.CreateOrderDetailFrom;
 import com.hcloud.microserver.facade.carbon.entity.from.CreateOrderFrom;
 import com.hcloud.microserver.h5.bo.OrderInfoBO;
 import com.hcloud.microserver.h5.config.mq.MQConstant;
 import com.hcloud.microserver.h5.config.mq.service.impl.IMessageService;
-import com.hcloud.microserver.h5.dao.GoodsInfoMapper;
-import com.hcloud.microserver.h5.dao.GoodsOrderDetailMapper;
-import com.hcloud.microserver.h5.dao.GoodsOrderInfoMapper;
+import com.hcloud.microserver.h5.dao.*;
 import com.hcloud.microserver.h5.events.CredentialInfoEvent;
+import com.hcloud.microserver.h5.events.CustomerCarbonValEvent;
 import com.hcloud.microserver.h5.service.*;
 import com.hcloud.microserver.commoncore.base.PageBean;
 import com.hcloud.microserver.commoncore.util.BeanCopyUtil;
 import com.hcloud.microserver.commoncore.util.GeneratorIdUtils;
 import com.hcloud.microserver.commoncore.util.GetUUID;
-import com.hcloud.microserver.facade.carbon.entity.GoodsInfo;
-import com.hcloud.microserver.facade.carbon.entity.GoodsOrderInfo;
 import com.hcloud.microserver.facade.carbon.forms.*;
 import lombok.extern.slf4j.Slf4j;
 import org.redisson.api.RLock;
@@ -77,6 +72,13 @@ public class OrderInfoServiceImpl implements OrderInfoService {
     private GoodsInfoService goodsInfoService;
 
 
+    @Override
+    public GoodsOrderInfo selectByPrimaryKey(String guid) {
+        GoodsOrderInfo goodsOrderInfo = goodsOrderInfoMapper.selectByPrimaryKey(guid);
+        return goodsOrderInfo;
+    }
+
+
     /**
      * 分页查询订单信息
      *
@@ -293,13 +295,18 @@ public class OrderInfoServiceImpl implements OrderInfoService {
                     //更新农户收入信息
                     updateFarmerSaleInfo(orderId);
                     //生成证书信息
-                    applicationContext.publishEvent(new CredentialInfoEvent(new Object(), orderId));
+                    applicationContext.publishEvent(new CredentialInfoEvent(this, orderId));
+                    //生成购买碳汇数据
+                    applicationContext.publishEvent(new CustomerCarbonValEvent(this, orderId));
+
                     return i;
                 } else {
                     throw new RuntimeException();
                 }
             }
         }
+
+
         return 0;
     }
 
@@ -512,6 +519,9 @@ public class OrderInfoServiceImpl implements OrderInfoService {
         if (customerInfo == null) {
             throw new RuntimeException("获取登陆信息失败");
         }
+        if(customerInfo.getCustomerType() != 1){
+            throw new RuntimeException("无法购买商品不是自然人");
+        }
         String customerId = customerInfo.getGuid();
 
         List<CreateOrderDetailFrom> goods = createOrderFrom.getGoods();
@@ -604,4 +614,29 @@ public class OrderInfoServiceImpl implements OrderInfoService {
 
         dataList.add(goodsOrderDetail);
     }
+
+    @Autowired
+    private OrderPayApplyMapper orderPayApplyMapper;
+
+    @Autowired
+    private GoodsPayOrderMapper goodsPayOrderMapper;
+
+    @Override
+    public void update(GoodsOrderInfo goodsOrderInfo, String orderNum) {
+        goodsOrderInfo.setPayNo(orderNum);
+        goodsOrderInfoMapper.updateByPrimaryKeySelective(goodsOrderInfo);
+        GoodsPayOrder goodsPayOrder = new GoodsPayOrder();
+        goodsPayOrder.setGuid(GetUUID.getUUID());
+        goodsPayOrder.setFkOrderId(goodsOrderInfo.getGuid());
+        goodsPayOrder.setFkCustomerId(goodsOrderInfo.getFkCustomerGuid());
+        goodsPayOrder.setOrderNo(goodsOrderInfo.getOrderNo());
+        goodsPayOrder.setPayAmount(goodsOrderInfo.getOrderAmount());
+        goodsPayOrder.setPayTime(new Date());
+        //设置为未支付
+        goodsPayOrder.setPayStatus(1);
+        //设置为微信支付
+        goodsPayOrder.setPayChannel(1);
+        goodsPayOrder.setPayNo(orderNum);
+        goodsPayOrderMapper.insertSelective(goodsPayOrder);
+    }
 }