Java微信支付对接

2023-04-17后端3 分钟129 次阅读
AI 摘要鱼粮不足,AI 今天先歇着 · 正文在下面

一、准备开发所需的账号以及配置信息

解释:想要接入微信支付我们需要两个玩意 ,一个是公众号/小程序/企业微信(开发用的),一个是微信支付商户(收钱用的)

1、前往:https://mp.weixin.qq.com/ (微信公众平台)注册一个应用,类型只能是:公众号/小程序/企业微信,注意:订阅号不支持微信支付接口,注册完成需要完成”微信认证“(微信需要收取300元)

2、前往:https://pay.weixin.qq.com(微信支付商户平台)注册一个商户,支付成功后的钱就会在这个账号里面

上面两个平台注册完成之后就需要把配置信息拿到了:
image.png
​1. APPID:应用id也就是 公众号/小程序的ID
2. Api_key: 应用密钥
3. mch_Id:商户ID (收钱的商家ID)
image.png

二、代码实现

项目采用Gradle + SpringBoot2.5.6,微信支付有两种版本:V3和V2,本文的接入版本为V3

gradle 复制代码
dependencies {
    api com.github.wechatpay-apiv3:wechatpay-apache-httpclient:0.2.1
    ...
    ...
}

官方文档,以下是根据官方的文档编写的代码实现

  1. 编写返回给前端唤起支付的数据对象
java 复制代码
@ApiModel(value = "订单信息")
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class OrderInfoVo {

    @ApiModelProperty(value = "aliPay")
    private String orderInfo;

    @ApiModelProperty(value = "wxPay")
    private String nonceStr;

    @ApiModelProperty(value = "wxPay")
    private String prepayid;

    @ApiModelProperty(value = "wxPay")
    private String appid;

    @ApiModelProperty(value = "wxPay")
    private String partnerid;

    @ApiModelProperty(value = "wxPay")
    private String sign;

    @ApiModelProperty(value = "wxPay")
    private String timeStamp;

    public OrderInfoVo(String orderInfo) {
        this.orderInfo = orderInfo;
    }

    public OrderInfoVo(String nonceStr, String prepayid, String appid, String partnerid, String sign, String timestamp) {
        this.nonceStr = nonceStr;
        this.prepayid = prepayid;
        this.appid = appid;
        this.partnerid = partnerid;
        this.sign = sign;
        this.timeStamp = timestamp;
    }
}
  1. 编写配置信息
java 复制代码
public interface Settings {

    String DOMAIN = "https://xxxxxx.com"; //回调域名

    String WX_KEY = "xxxx";
    String WX_API_V3_KEY = "xxx";
    String WX_MCH_ID = "xxx"; //商户ID
    String WX_MCH_SERIAL_NO = "xx"; //商户API证书序列号serial_no
    String WX_APP_ID = "xxxxx"; //应用ID

    String WX_MINI_ID = "xxxx";
    String WX_MINI_SECRET = "xxxxxx";
}
  1. 编写调用微信支付接口
java 复制代码
public interface IWxPayService {

    ResVo<OrderInfoVo> getOrderInfo(Integer totalAmount, String orderNum, String ip, String productName) throws Exception;

    boolean refund(String selfOrderNum, String refundUuid, Integer money);
}
  1. 编写接口逻辑实现
java 复制代码
@Service
@Slf4j
public class WxPayServiceImpl implements IWxPayService {

    private final IRedisUtilService redisUtilService;

    private CloseableHttpClient httpClient;

    public WxPayServiceImpl(IRedisUtilService redisUtilService) {
        this.redisUtilService = redisUtilService;
    }

    @Override
    public ResVo<AdBuyOrderInfoVo> getOrderInfo(Integer totalAmount, String orderNum, String ip, String name) throws Exception {
        before();
        HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/v3/pay/transactions/app");
        String reqdata = "{"
                + "\"amount\": {"
                + "\"total\":"+totalAmount
                + "},"
                + "\"mchid\":\""+Settings.WX_MCH_ID+"\","
                + "\"description\":\""+ (name.length() > 40? name.substring(0, 40): name) +"\","
                + "\"notify_url\":\""+Settings.DOMAIN + "/api/notify/syncWxPay"+"\","
                + "\"out_trade_no\":\""+orderNum+"\","
                + "\"appid\":\""+ Settings.WX_APP_ID +"\""
                + "}";
        StringEntity entity = new StringEntity(reqdata, StandardCharsets.UTF_8);
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        httpPost.setHeader("Accept", "application/json");
        try(CloseableHttpResponse response = httpClient.execute(httpPost)) {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200 || statusCode == 204) {
                String result = EntityUtils.toString(response.getEntity());
                log.info("success, status: {} , return body {}", statusCode, result);
                String prepayId = JSON.parseObject(result).getString("prepay_id");
                String nonceStr = Utils.generateNonceStr();
                long timeStamp = System.currentTimeMillis() / 1000;
                String originStr = Settings.WX_APP_ID + "\n"
                        + timeStamp + "\n"
                        + nonceStr + "\n"
                        + prepayId + "\n";
                PrivateKey merchantPrivateKey = PemUtil
                        .loadPrivateKey(new ByteArrayInputStream(Settings.WX_KEY.getBytes(StandardCharsets.UTF_8)));
                String paySign;
                try {
                    Signature sign = Signature.getInstance("SHA256withRSA");
                    sign.initSign(merchantPrivateKey);
                    sign.update(originStr.getBytes(StandardCharsets.UTF_8));
                    paySign = Base64.getEncoder().encodeToString(sign.sign());
                } catch (NoSuchAlgorithmException e) {
                    throw new RuntimeException("当前Java环境不支持SHA256withRSA", e);
                } catch (SignatureException e) {
                    throw new RuntimeException("签名计算失败", e);
                } catch (InvalidKeyException e) {
                    throw new RuntimeException("无效的私钥", e);
                }
                log.info("signature: {}", paySign);
                AdBuyOrderInfoVo orderInfoVo = new AdBuyOrderInfoVo(nonceStr, prepayId, Settings.WX_APP_ID, Settings.WX_MCH_ID, paySign, timeStamp + "");
                return ResVo.ok(orderInfoVo);
            }  else {
                String msg = EntityUtils.toString(response.getEntity());
                log.error("failed,resp code = " + statusCode + ",return body = " + msg);
                return ResVo.error(JSON.parseObject(msg).getString("message"));
            }
        }finally {
            try {
                httpPost.releaseConnection();
            } catch (Exception e) {
                log.error("error", e);
            }
            after();
        }
    }

    public void before() {
        PrivateKey merchantPrivateKey = PemUtil
                .loadPrivateKey(new ByteArrayInputStream(Settings.WX_KEY.getBytes(StandardCharsets.UTF_8)));

        AutoUpdateCertificatesVerifier verifier = new AutoUpdateCertificatesVerifier(
                new WechatPay2Credentials(Settings.WX_MCH_ID, new PrivateKeySigner(Settings.WX_MCH_SERIAL_NO, merchantPrivateKey)),Settings.WX_API_V3_KEY.getBytes(StandardCharsets.UTF_8));

        httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(Settings.WX_MCH_ID, Settings.WX_MCH_SERIAL_NO, merchantPrivateKey)
                .withValidator(new WechatPay2Validator(verifier)).build();
    }

    public void after() {
        try{
            httpClient.close();
        }catch (Exception e){
            log.error("", e);
        }
    }

    public boolean refund(String selfOrderNum, String refundUuid, Integer money){
        before();
        Map<String, Object> map = new HashMap<>();
        map.put("out_trade_no", selfOrderNum);
        map.put("out_refund_no", refundUuid);
        Map<String, Object> innerMap = new HashMap<>();
        innerMap.put("refund", money);
        innerMap.put("total", money);
        innerMap.put("currency", "CNY");
        map.put("amount", innerMap);
        String url = "https://api.mch.weixin.qq.com/v3/refund/domestic/refunds";
        HttpPost httpPost = new HttpPost(url);
        StringEntity entity = new StringEntity(JSON.toJSONString(map), StandardCharsets.UTF_8);
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        httpPost.addHeader("Accept", "application/json");
        try(CloseableHttpResponse response = httpClient.execute(httpPost)){
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200 || statusCode == 204) {
                String result = EntityUtils.toString(response.getEntity());
                log.info("success, status: {} , return body {}", statusCode, result);
                return true;
            }  else {
                log.error("failed,resp code = " + statusCode + ",return body = " + EntityUtils.toString(response.getEntity()));
                throw new IOException("request failed");
            }
        }catch (Exception e){
            log.error("", e);
        }finally {
            try {
                httpPost.releaseConnection();
            } catch (Exception e) {
                log.error("error url: {}", url, e);
            }
            after();
        }
        return false;
    }

}
  1. 编写支付回调逻辑
java 复制代码
@RestController
@Slf4j
@RequestMapping("/api/notify")
@AllArgsConstructor
public class NotifyController extends BaseController {

    private IOrderService orderService;

    @PostMapping("/syncWxPay")
    public Map<String, String> syncWxPayAdBuyOrder(
            @RequestBody JSONObject wxPaySyncDto
    ) throws Exception {
        String event_type = wxPaySyncDto.getString("event_type");
        String resource = wxPaySyncDto.getString("resource");
        log.info("event_type: {}, resource: {}", event_type, resource);
        if ("TRANSACTION.SUCCESS".equals(event_type)) {
            AesUtil decryptor = new AesUtil(Settings.WX_API_V3_KEY.getBytes(StandardCharsets.UTF_8));
            JSONObject encryptCertificateNode = Utils.getJSonFromRaw(resource);
            log.info("encryptCertificateNode: {}", JSON.toJSONString(encryptCertificateNode));
            String result = decryptor.decryptToString(
                    encryptCertificateNode.getString("associated_data").replaceAll("\"", "")
                            .getBytes(StandardCharsets.UTF_8),
                    encryptCertificateNode.getString("nonce").replaceAll("\"", "")
                            .getBytes(StandardCharsets.UTF_8),
                    encryptCertificateNode.getString("ciphertext").replaceAll("\"", ""));
            log.info("result: {}", result);
            JSONObject params = JSON.parseObject(result);
            String uuid = params.getString("out_trade_no");
            String status = params.getString("trade_state");
            if ("SUCCESS".equals(status)) {
                String res = payThirdSuccess(uuid, params.getString("transaction_id"), PayTypeEnum.WX.getKey());
                if (!"success".equals(res)) {
                    return ret("FAILED", res);
                }
            }
            return ret("SUCCESS", "OK");
        }
        return ret("FAILED", "unnecessary event type: " + event_type);
    }


    private Map<String, String> ret(String code, String msg) {
        Map<String, String> map = new HashMap<>();
        map.put("code", code);
        map.put("message", msg);
        return map;
    }
    private String payThirdSuccess(String orderNum, String thirdTradeNo, int type) {
        log.info("调用支付成功方法,orderNum: {}, thirdTradeNo: {}, type: {}", orderNum, thirdTradeNo, type);
        if (orderNum.startsWith("xxx")) {
             
            } catch (Exception e) {
                log.error("error notify: {}, {}, {}", thirdTradeNo, orderNum, type, e);
                return "failure";
            }
        }
        return "success";
    }
}
觉得有用就点个赞,不用登录也能读

评论

0 条
登录 之后才能评论
—
还没有评论,来说第一句