SpringBoot整合微信支付JSAPI支付

本文详细介绍了如何在Springboot项目中集成微信支付JSAPI功能,包括登录微信支付所需参数、添加依赖、配置文件设置以及关键接口实现,帮助开发者快速接入微信支付功能。
摘要由CSDN通过智能技术生成

微信支付(Java)

目录

微信支付(Java)

简介:

登录微信公众平台(JSAPI支付):

注意事项:

添加依赖:

application.yaml:

WeixinPayController:

PaymentService:

PaymentServiceImpl:

实体类PaymentJSAPI:


 

 

 

 

简介:

        Springboot项目集成微信支付(JSAPI),用于微信公众号对接支付功能。

d6ec075300914d99b4313102ff738877.png

 

登录微信支付(JSAPI支付)

        获取如下参数:

        商户号、商户API私钥路径、商户证书序列号、商户APIV3密钥、appId

注意事项:

        JDK版本建议11。

添加依赖:

<dependency>
    <groupId>com.github.wechatpay-apiv3</groupId>
    <artifactId>wechatpay-java</artifactId>
    <version>0.2.12</version>
</dependency>

application.yaml:

        添加微信支付相关配置。

weixin:
  merchantId: XXXXXX # 商户号
  privateKeyPath: /www/weixin/cert/apiclient_key.pem # 商户API私钥路径
  merchantSerialNumber: XXXXXXXXXXXXXXXXXXXXXXXXXXXX  #商户证书序列号
  apiV3Key: XXXXXX # 商户APIV3密钥
  appId: XXXXXX# 自己的AppId
  notifyUrl: http://localhost:${server.port}/weixin/payment/notify # 自定义回调地址

WeixinPayController:

        功能描述

  •                 发起支付;
  •                 获取签名;
  •                 成功回调(需自测)。
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Map;

/**
 * 微信支付
 *
 */
@RequestMapping("weixin/payment")
@RestController
public class WeixinPayController {
    @Autowired
    private PaymentService paymentService;

    /**
     * 发起支付
     * @param payment
     * @return
     */
    @PostMapping("send")
    public String payment(@RequestBody PaymentJSAPI payment){
        return paymentService.payment(payment);
    }


    /**
     * 获取签名
     * @param jsonObject
     * @return
     */
    @PostMapping("sign")
    public String sign(@RequestBody JSONObject jsonObject) throws Exception {
        return paymentService.sign(jsonObject);
    }



}

PaymentService:

import com.alibaba.fastjson.JSONObject;

public interface PaymentService {
    /**
     * 发起支付
     *
     * @param payment
     * @return
     */
    String payment(PaymentJSAPI payment);

    /**
     * 生成签名
     *
     * @param jsonObject
     * @return
     */
    String sign(JSONObject  jsonObject) throws Exception;
}

PaymentServiceImpl:

import com.alibaba.fastjson.JSONObject;
import com.wechat.pay.java.service.payments.jsapi.JsapiService;
import com.wechat.pay.java.service.payments.jsapi.model.Amount;
import com.wechat.pay.java.service.payments.jsapi.model.Payer;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class PaymentServiceImpl  implements PaymentService {
    @Autowired
    private  JsapiService jsapiService;
    @Autowired
    private WeiXinConfig weiXinConfig;

    @Override
    public String payment(PaymentJSAPI payment) {
        PrepayRequest request = new PrepayRequest();
        Amount  amount = new Amount();
        amount.setTotal(weiXinConfig.amountVal);
        request.setAmount(amount);
        request.setAppid(weiXinConfig.appId);
        request.setMchid(weiXinConfig.merchantId);

        Payer payer = new Payer();
        payer.setOpenid(payment.getOpenid());
        request.setPayer(payer);
        request.setDescription(payment.getDescription());
        request.setNotifyUrl(weiXinConfig.notifyUrl);
        request.setOutTradeNo("trade_no_" + System.currentTimeMillis());  // 一个用户就一次
        // 调用下单方法,得到应答
        PrepayResponse response = jsapiService.prepay(request);
        log.info("----payment--response:{}---------", response);
        return response.getPrepayId();
    }

    @Override
    public String sign(JSONObject jsonObject) throws Exception {
        return weiXinConfig.sign(jsonObject.toJSONString());
    }

}

实体类PaymentJSAPI:

import lombok.Data;
import java.io.Serializable;

/**
 * 发起账单参数
 */
@Data
public class PaymentJSAPI implements Serializable {
    // 描述
    private String description;
    // 用户的openId
    private String openid;

}

WeiXinConfig:

import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.util.PemUtil;
import com.wechat.pay.java.service.payments.jsapi.JsapiService;
import okhttp3.HttpUrl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.security.PrivateKey;
import java.security.Signature;
import java.util.Base64;

@Configuration
public class WeiXinConfig {

    /** 商户号 */
    @Value("${weixin.merchantId}")
    public  String merchantId;
    /** 商户API私钥路径 */
    @Value("${weixin.privateKeyPath}")
    public  String privateKeyPath;
    /** 商户证书序列号 */
    @Value("${weixin.merchantSerialNumber}")
    public  String merchantSerialNumber;
    /** 商户APIV3密钥 */
    @Value("${weixin.apiV3Key}")
    public  String apiV3Key;
    @Value("${weixin.appId}")
    public  String appId;

    @Value("${weixin.amount}")
    public  Integer amountVal;

    @Value("${weixin.notifyUrl}")
    public  String notifyUrl;
    @Bean
    public JsapiService jsapiService(){
        Config config =
                new RSAAutoCertificateConfig.Builder()
                        .merchantId(merchantId)
                        .privateKeyFromPath(privateKeyPath)
                        .merchantSerialNumber(merchantSerialNumber)
                        .apiV3Key(apiV3Key)
                        .build();
        JsapiService service = new JsapiService.Builder().config(config).build();
        return service;
    }

    /**
     * 签名方法
     * @param body
     * @return
     * @throws Exception
     */
    public String sign(String body) throws Exception {
        return this.getToken(body);
    }

    private String getToken(String body) throws Exception {
        HttpUrl url = HttpUrl.parse("https://api.mch.weixin.qq.com/v3/certificates");
        String nonceStr = System.currentTimeMillis() + "";
        long timestamp = System.currentTimeMillis() / 1000;
        String message = buildMessage("POST", url, timestamp, nonceStr, body);
        String signature = sign(message.getBytes("utf-8"));
        return "mchid=\"" + merchantId + "\","
                + "nonce_str=\"" + nonceStr + "\","
                + "timestamp=\"" + timestamp + "\","
                + "serial_no=\"" + merchantSerialNumber + "\","
                + "signature=\"" + signature + "\"";
    }
    private String sign(byte[] message) throws Exception {
        Signature sign = Signature.getInstance("SHA256withRSA");
        // 加载密钥库
        PrivateKey privateKey = PemUtil.loadPrivateKeyFromPath(privateKeyPath);
        sign.initSign(privateKey);
        sign.update(message);
        return Base64.getEncoder().encodeToString(sign.sign());
    }
    private String buildMessage(String method, HttpUrl url, long timestamp, String nonceStr, String body) {
        String canonicalUrl = url.encodedPath();
        if (url.encodedQuery() != null) {
            canonicalUrl += "?" + url.encodedQuery();
        }
        return method + "\n"
                + canonicalUrl + "\n"
                + timestamp + "\n"
                + nonceStr + "\n"
                + body + "\n";
    }
}

后续我们会更新订单查询等功能。

 

 

 

首先,你需要在微信公众平台申请开通JSAPI支付,并获取到商户号、密钥、证书等信息。 接着,在Spring Boot项目中添加微信支付SDK的依赖,比如: ```xml <dependency> <groupId>com.github.binarywang</groupId> <artifactId>weixin-java-pay</artifactId> <version>3.6.0</version> </dependency> ``` 然后,创建一个配置类来配置微信支付相关的参数,比如: ```java @Configuration public class WxPayConfig { @Value("${wxpay.appid}") private String appId; @Value("${wxpay.mchid}") private String mchId; @Value("${wxpay.key}") private String key; @Value("${wxpay.certPath}") private String certPath; @Bean public WxPayService wxPayService() throws Exception { WxPayConfig payConfig = new WxPayConfig(); payConfig.setAppId(appId); payConfig.setMchId(mchId); payConfig.setMchKey(key); payConfig.setKeyPath(certPath); return new WxPayServiceImpl(payConfig); } } ``` 其中,`appId`、`mchId`、`key`和`certPath`是申请支付时所获取到的信息。然后,通过`WxPayServiceImpl`创建一个`WxPayService`的实例,用于后续的支付操作。 接下来,编写控制器处理支付请求,比如: ```java @RestController @RequestMapping("/wxpay") public class WxPayController { @Autowired private WxPayService wxPayService; @PostMapping("/unifiedorder") public Map<String, String> unifiedOrder(@RequestBody WxPayUnifiedOrderRequest request) throws WxPayException { WxPayUnifiedOrderResult result = wxPayService.unifiedOrder(request); Map<String, String> resultMap = new HashMap<>(); resultMap.put("appId", result.getAppid()); resultMap.put("timeStamp", String.valueOf(System.currentTimeMillis() / 1000)); resultMap.put("nonceStr", result.getNonceStr()); resultMap.put("package", "prepay_id=" + result.getPrepayId()); resultMap.put("signType", "MD5"); resultMap.put("paySign", wxPayService.createSign(resultMap)); return resultMap; } } ``` 其中,`WxPayUnifiedOrderRequest`是支付请求参数,包括订单号、金额、回调地址等信息。`wxPayService.unifiedOrder(request)`方法返回的是支付下单结果,包括预支付ID等信息。最后,将这些信息组装成JSAPI支付所需的数据格式,返回给前端即可。 注意,在进行支付之前,需要先通过微信公众平台获取用户的openid,然后将其作为支付请求参数的一个字段传递给微信支付。另外,JSAPI支付还需要在页面上引入微信JSAPI的SDK,同时配置好微信公众平台的授权域名等信息。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

diudiu9628

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值