Browse Source

小程序购买书籍

花田厝 9 months ago
parent
commit
972d59c6d4

+ 20 - 4
jsjp-admin/src/main/java/com/miaxis/app/controller/wx/WxJsjpController.java

@@ -134,7 +134,11 @@ public class WxJsjpController extends BaseController {
         order.setGoodsName(sysDictData.getDictLabel());
         order.setGoodsType(1);
         order.setPhoneType(wxOrderDTO.getPhoneType());  //手机类型
-        order.setDqbh(gzptUserInfo.getCity());
+        if ("yntms".equals(gzptUserInfo.getCity())) { //如果是一诺地市
+            order.setDqbh(gzptUserInfo.getCountry().substring(0,4));
+        } else {
+            order.setDqbh(gzptUserInfo.getCity());
+        }
         order.setDqmc(gzptUserInfo.getCityName());
         order.setSchool(gzptUserInfo.getSchool());
         order.setSchoolName(gzptUserInfo.getSchoolName());
@@ -223,7 +227,11 @@ public class WxJsjpController extends BaseController {
             order.setPhoneType(wxOrderGoodsDTO.getPhoneType()); //手机类型 1:苹果 2:安卓
             order.setTotal(examInfo.getPrice());
             order.setIsShare(0);
-            order.setDqbh(gzptUserInfo.getCity());
+            if ("yntms".equals(gzptUserInfo.getCity())) { //如果是一诺地市
+                order.setDqbh(gzptUserInfo.getCountry().substring(0,4));
+            } else {
+                order.setDqbh(gzptUserInfo.getCity());
+            }
             order.setDqmc(gzptUserInfo.getCityName());
             order.setSchool(gzptUserInfo.getSchool());
             order.setSchoolName(gzptUserInfo.getSchoolName());
@@ -348,7 +356,11 @@ public class WxJsjpController extends BaseController {
             order.setPhoneType(wxOrderGoodsDTO.getPhoneType()); //手机类型 1:苹果 2:安卓
             order.setTotal(examInfo.getPrice());
             order.setIsShare(0);
-            order.setDqbh(gzptUserInfo.getCity());
+            if ("yntms".equals(gzptUserInfo.getCity())) { //如果是一诺地市
+                order.setDqbh(gzptUserInfo.getCountry().substring(0,4));
+            } else {
+                order.setDqbh(gzptUserInfo.getCity());
+            }
             order.setDqmc(gzptUserInfo.getCityName());
             order.setSchool(gzptUserInfo.getSchool());
             order.setSchoolName(gzptUserInfo.getSchoolName());
@@ -391,7 +403,11 @@ public class WxJsjpController extends BaseController {
         order.setGoodsName(sysDictData.getDictLabel());
         order.setGoodsType(1);
         order.setPhoneType(wxOrderDTO.getPhoneType());  //手机类型
-        order.setDqbh(gzptUserInfo.getCity());
+        if ("yntms".equals(gzptUserInfo.getCity())) { //如果是一诺地市
+            order.setDqbh(gzptUserInfo.getCountry().substring(0,4));
+        } else {
+            order.setDqbh(gzptUserInfo.getCity());
+        }
         order.setDqmc(gzptUserInfo.getCityName());
         order.setSchool(gzptUserInfo.getSchool());
         order.setSchoolName(gzptUserInfo.getSchoolName());

+ 241 - 0
jsjp-admin/src/main/java/com/miaxis/app/controller/wx/WxXcxController.java

@@ -0,0 +1,241 @@
+package com.miaxis.app.controller.wx;
+
+import com.alibaba.fastjson.JSONObject;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.miaxis.common.config.AppConfig;
+import com.miaxis.common.config.WxpayConfig;
+import com.miaxis.common.config.XcxConfig;
+import com.miaxis.common.constant.Constants;
+import com.miaxis.common.core.controller.BaseController;
+import com.miaxis.common.core.domain.Response;
+import com.miaxis.common.core.domain.entity.SysDictData;
+import com.miaxis.common.core.domain.entity.UserInfo;
+import com.miaxis.common.enums.OrderStatusEnum;
+import com.miaxis.common.exception.CustomException;
+import com.miaxis.common.utils.SecurityUtils;
+import com.miaxis.common.utils.ServletUtils;
+import com.miaxis.common.utils.ip.IpUtils;
+import com.miaxis.common.utils.uuid.CommonUtils;
+import com.miaxis.exam.domain.ExamInfo;
+import com.miaxis.exam.service.IExamInfoService;
+import com.miaxis.examvip.domain.VipUserExam;
+import com.miaxis.examvip.service.IVipUserExamService;
+import com.miaxis.newgzpt.domain.GzptUserInfo;
+import com.miaxis.newgzpt.service.IGzptSchActivationService;
+import com.miaxis.newgzpt.service.IGzptSchPayConfigService;
+import com.miaxis.newgzpt.service.IGzptUserInfoService;
+import com.miaxis.system.service.ISysDictDataService;
+import com.miaxis.wx.domain.WxJsOrder;
+import com.miaxis.wx.domain.WxOrder;
+import com.miaxis.wx.dto.WxOrderDTO;
+import com.miaxis.wx.dto.WxOrderGoodsDTO;
+import com.miaxis.wx.service.IWxJsOrderService;
+import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
+import com.wechat.pay.contrib.apache.httpclient.auth.AutoUpdateCertificatesVerifier;
+import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
+import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
+import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import lombok.Data;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang.RandomStringUtils;
+import org.apache.http.HttpResponse;
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.util.EntityUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.core.io.ClassPathResource;
+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 java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.security.PrivateKey;
+import java.security.Signature;
+import java.util.Base64;
+import java.util.Date;
+
+import static com.miaxis.common.utils.OrderCodeFactory.getOrderCode;
+
+/**
+ * 【小程序-微信支付】Controller
+ *
+ * @author miaxis
+ * @date 2021-03-10
+ */
+@RestController
+@RequiredArgsConstructor
+@RequestMapping(Constants.OPEN_PREFIX + "/wxjs")
+@Api(tags = {"【APP-微信支付】"})
+@Slf4j
+public class WxXcxController extends BaseController {
+
+    @Autowired
+    private HttpClient httpClient;
+
+    @Autowired
+    private WxpayConfig wxpayConfig;
+
+
+
+    @Autowired
+    private XcxConfig xcxConfig;
+
+    @Autowired
+    private IGzptUserInfoService userInfoService;
+
+
+    /**
+     * 微信小程序支付获取预订单id
+
+    @PostMapping(value = "/xcxPrepareOrder")
+    @ApiOperation("微信小程序支付下单")
+    public Response<JSONObject> xcxPrepareOrder(@RequestBody WxOrderDTO wxOrderDTO) throws Exception {
+
+        if (wxOrderDTO.getGoodsType() == 1) {
+            int count = vipUserExamService.getUserExamCountByUserIdAndGoodsId(userInfo.getId(), wxOrderDTO.getGoodsId());
+            if (count > 0) {
+                throw new CustomException("您已购买过该考场,退回上个页面,重新进入。");
+            }
+            ExamInfo examInfo = examInfoService.getById(wxOrderDTO.getGoodsId());
+            //创建本地微信订单
+            WxOrder order = new WxOrder();
+            String orderCode = getOrderCode(userInfo.getId());
+            order.setGoodsId(wxOrderDTO.getGoodsId());
+            order.setGoodsName(examInfo.getName());
+            order.setGoodsType(1);
+            order.setOutTradeNo(orderCode);
+            order.setUserId(userInfo.getId());
+            order.setXcxOpenid(userInfo.getXcxOpenid());
+            order.setUnionId(userInfo.getUnionId());
+            order.setPhoneType(wxOrderDTO.getPhoneType()); //手机类型 1:苹果 2:安卓
+            order.setForeType(wxOrderDTO.getForeType()); //前端类型 1:app 2:小程序 3:公众号
+            order.setShopId(userInfo.getShopId());
+            if (shopInfo.getFzOpen()==1) {
+                order.setIsSharing(1); //分账
+            } else {
+                order.setIsSharing(0); //不分账
+            }
+            order.setTotal(examInfo.getPrice());
+            order.setOrderStatus(OrderStatusEnum.PROCESSING.getCode());
+            wxOrderService.save(order);
+            return Response.success(placeXcxWxOrder(order));
+        }  else {
+            throw new CustomException("请正确传入GoodsType。");
+        }
+    }
+     */
+
+    /**
+     * 极速生活圈小程序或公众号内  JSAPI下单
+     * @param order
+     * @return
+     * @throws Exception
+     */
+    private JSONObject placeXcxWxOrder(WxOrder order) throws Exception {
+        HttpPost httpPost = initHttpPost(wxpayConfig.getV3JsUrl());
+        ByteArrayOutputStream bos = new ByteArrayOutputStream();
+        ObjectMapper objectMapper = new ObjectMapper();
+        ObjectNode rootNode = objectMapper.createObjectNode();
+        rootNode.put("mchid",wxpayConfig.getMerchantId())
+                .put("appid", xcxConfig.getAppId())
+                .put("description", "商品名称")
+                .put("notify_url", wxpayConfig.getNotifyUrl())
+                .put("out_trade_no", order.getOutTradeNo());
+        rootNode.putObject("amount").put("total", order.getTotal());
+        rootNode.putObject("payer").put("openid", order.getOpenid());
+        objectMapper.writeValue(bos, rootNode);
+        httpPost.setEntity(new StringEntity(rootNode.toString(), "utf-8"));
+
+        HttpClient httpClient = initHttpClient();
+        HttpResponse response = httpClient.execute(httpPost);
+        String bodyAsString = EntityUtils.toString(response.getEntity());
+        if (JSONObject.parseObject(bodyAsString).get("prepay_id") == null){
+            throw new CustomException(JSONObject.parseObject(bodyAsString).get("message").toString());
+        }
+        return getWxParamJson(bodyAsString);
+
+    }
+
+
+
+
+
+    /**
+     * 微信小程序或公众号内  JSAPI下单
+     * 生成调用调起微信支付所需参数
+     * @param bodyAsString
+     * @return
+     * @throws Exception
+     */
+    private JSONObject getWxParamJson(String bodyAsString) throws Exception {
+        String  packageStr = "prepay_id="+JSONObject.parseObject(bodyAsString).get("prepay_id");
+        JSONObject jsonObject = new JSONObject();
+        jsonObject.put("package",packageStr);
+        String nonce_str = RandomStringUtils.randomAlphanumeric(32);
+        jsonObject.put("nonceStr",nonce_str);
+        long timestamp =  System.currentTimeMillis()/1000;
+        jsonObject.put("timeStamp",String.valueOf(timestamp));
+        jsonObject.put("signType","RSA");
+        StringBuffer sb = new StringBuffer();
+        sb.append(xcxConfig.getAppId() + "\n");
+        sb.append(timestamp + "\n");
+        sb.append(nonce_str + "\n");
+        sb.append(packageStr+ "\n");
+
+        File file = new ClassPathResource("wechatpay/apiclient_key.pem").getFile();
+        //File file = new ClassPathResource(apiclientPath+"apiclient_key.pem").getFile();
+        String realPath =file.getAbsolutePath();
+        PrivateKey privateKey = CommonUtils.getPrivateKey(realPath);
+        // 进行签名服务
+        Signature signature = Signature.getInstance("SHA256withRSA");
+        signature.initSign(privateKey);
+        signature.update(sb.toString().getBytes("UTF-8"));
+        byte[] signedData = signature.sign();
+        String base64Str =  Base64.getEncoder().encodeToString(signedData);
+        jsonObject.put("paySign",base64Str);
+        jsonObject.put("appId", xcxConfig.getAppId());
+        return jsonObject;
+    }
+
+    private HttpPost initHttpPost(String url) {
+        HttpPost httpPost = new HttpPost(url);
+        httpPost.addHeader("Accept", "application/json");
+        httpPost.addHeader("Content-type", "application/json; charset=utf-8");
+        return httpPost;
+    }
+
+
+
+
+
+
+    private HttpClient initHttpClient() throws IOException {
+        File file = new ClassPathResource("wechatpay/apiclient_key.pem").getFile();
+        String realPath = file.getAbsolutePath();
+        PrivateKey privateKey = CommonUtils.getPrivateKey(realPath);
+
+        // 加载平台证书(mchId:商户号,mchSerialNo:商户证书序列号,apiV3Key:V3密钥)
+        AutoUpdateCertificatesVerifier verifier = new AutoUpdateCertificatesVerifier(
+                new WechatPay2Credentials(wxpayConfig.getMerchantId(),
+                        new PrivateKeySigner(wxpayConfig.getSerialNumber(), privateKey)),
+                wxpayConfig.getV3key().getBytes("utf-8"));
+
+        // 初始化httpClient
+        HttpClient httpClient = WechatPayHttpClientBuilder.create()
+                .withMerchant(wxpayConfig.getMerchantId(), wxpayConfig.getSerialNumber(), privateKey)
+                .withValidator(new WechatPay2Validator(verifier)).build();
+
+        return httpClient;
+
+    }
+
+
+}

+ 5 - 0
jsjp-admin/src/main/resources/application-dev.yml

@@ -93,6 +93,11 @@ app:
     bundleId: com.kestrel.JSJPStudent
     packageName: com.jsjp.student
 
+# 小程序
+xcx:
+    appId: wx8f43db501343feab
+    secret: 3509a81880669ffa6fa554b2aa050351
+
 
 # 教练管家 微信开放平台
 coachApp:

+ 10 - 1
jsjp-admin/src/test/java/com/miaxis/test/Test03.java

@@ -20,7 +20,16 @@ public class Test03 {
     public static void main(String[] args) throws IOException {
         //test1();
 
-        test5();
+
+       // order.setDqbh(gzptUserInfo.getCountry().substring(0,3));
+
+
+        String dqbh = "210103";
+
+
+        System.out.println(dqbh.substring(0,4));
+
+        //test5();
 
     }
 

+ 17 - 0
jsjp-common/src/main/java/com/miaxis/common/config/XcxConfig.java

@@ -0,0 +1,17 @@
+package com.miaxis.common.config;
+
+import lombok.Data;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.stereotype.Component;
+
+@Data
+@Component
+@ConfigurationProperties(prefix = "xcx")
+public class XcxConfig {
+    //appid
+    private String appId;
+    //secret
+    private String secret;
+
+
+}

+ 19 - 0
jsjp-service/src/main/java/com/miaxis/wx/dto/WxXcxDTO.java

@@ -0,0 +1,19 @@
+package com.miaxis.wx.dto;
+
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+
+@Data
+public class WxXcxDTO {
+    private static final long serialVersionUID = 1L;
+
+
+    @ApiModelProperty(value = "商品字典编码",required = true)
+    private Long dictCode;
+
+    @ApiModelProperty(value = "用户id",required = true)
+    private Long userId;
+
+    @ApiModelProperty(value = "手机类型 1苹果 2安卓")
+    private Integer phoneType;  // 1苹果 2安卓
+}