springboot+微信小程序接入微信小程序支付(使用微信支付公钥与JSAPI)

1、引入maven依赖

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

2、配置文件application.yml

#微信支付相关参数
wx-pay:
    #商户id(微信支付商户平台获取)
    mch-id: xxxxxxxxx
    #公众号appid(和商户id绑定过后,微信支付商户平台或者微信公众平台获取)
    appid: xxxxxxxxx
 
    #商户证书序列号(从微信支付商户平台-API安全获取)
    mch-serial-no: xxxxxxxxx
    #商户私钥(从微信支付商户平台-API安全获取,放在项目根目录与src同级)
    private-key-path: apiclient_key.pem
    #APIv3密钥(在微信支付回调通知和商户获取平台证书使用APIv3密钥)
    api-v3-key: xxxxxxxxx
 
    #微信服务器地址
    domain: https://api.mch.weixin.qq.com
    #接收结果通知地址(自己项目的域名,发布到服务器上就是服务器的域名,必须域名不支持ip,本地调试需要使用内网穿透-推荐使用花生壳来做内网穿透,但会收取少量费用,也可使用ngrok,免费但每次启动域名会变化,需要修改此处地址)
    notify-domain: https://xxxxxxxxx

    #微信支付公钥
    public-key-path: pub_key.pem
    #微信支付公钥
    public-key-id: xxxxxxxxx

3、支付配置类WxPayApiConfig(https://github.com/wechatpay-apiv3/wechatpay-java?tab=readme-ov-file

@Configuration
@Data
public class WxPayApiConfig {

    @Value("${wx-pay.mch-id}")
    private String mchId;

    @Value("${wx-pay.appid}")
    private String appid;

    @Value("${wx-pay.mch-serial-no}")
    private String mchSerialNo;

    @Value("${wx-pay.private-key-path}")
    private String privateKeyPath;

    @Value("${wx-pay.api-v3-key}")
    private String apiV3Key;

    @Value("${wx-pay.domain}")
    private String domain;

    @Value("${wx-pay.notify-domain}")
    private String notifyDomain;

    @Value("${wx-pay.public-key-path}")
    private String publicKeyPath;

    @Value("${wx-pay.public-key-id}")
    private String publicKeyId;


    public Config getApiConfig(){
        return new RSAPublicKeyConfig.Builder()
                .merchantId(mchId)
                .privateKeyFromPath(privateKeyPath)
                .publicKeyFromPath(publicKeyPath)
                .publicKeyId(publicKeyId)
                .merchantSerialNumber(mchSerialNo)
                .apiV3Key(apiV3Key)
                .build();
    }


    public PrepayRequest getPrepayRequest(){
        PrepayRequest request = new PrepayRequest();
        request.setAppid(appid);
        request.setMchid(mchId);
        request.setNotifyUrl(notifyDomain+"/wx/order/paySignal");
        return request;
    }

    @Bean
    public JsapiServiceExtension jsapiServiceExtension(){
        return new JsapiServiceExtension.Builder().config(getApiConfig()).build();
    }

}

4、后台获取小程序发起支付需要的参数

@TableName("order_info")
@Data
public class OrderInfo {
    //根据自己项目
    private String outTradeNo;
}

@PostMapping({"/createPay"})
public JsonResult createPay(@RequestBody OrderInfo entity) {
    PayMentDto response = orderInfoService.createPay(entity);
    return JsonResult.OK().data(response);
}
 
    @SaIgnore
    @PostMapping("/callback")
    public JsonResult paySignal(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try{
            Gson gson = new Gson();
            Map<String, Object> map = gson.fromJson(request.getReader(), Map.class);
            log.info(map.toString());
            log.info("支付id:{}", map.get("id"));
        }catch (Exception e){
 
        }
 
        return JsonResult.OK().data("444");
}
@Service
@Slf4j
public class OrderInfoService {

    @Resource
    private JsapiServiceExtension jsapiServiceExtension;

    @Resource
    private WxPayApiConfig wxPayApiConfig;

    public PrepayWithRequestPaymentResponse createPay(OrderInfo entity) {

        //构造请求参数
        PrepayRequest request = wxPayApiConfig.getPrepayRequest();
        request.setDescription("测试商品标题");
        request.setOutTradeNo(entity.getOutTradeNo());
        Amount amount = new Amount();
        amount.setTotal(1);
        request.setAmount(amount);
        Payer payer = new Payer();
        payer.setOpenid("oXAAU7WqQnKWKNnnTOfE8ADJKjLE");
        request.setPayer(payer);

        // response包含了调起支付所需的所有参数,可直接用于前端调起支付
        PrepayWithRequestPaymentResponse response = jsapiServiceExtension.prepayWithRequestPayment(request);

        return response;
    }

5、前台发起支付

<template>
	<view @click="createPay">发起支付</view>
</template>

<script setup name="order">
	import { onReady , onShow , onPullDownRefresh} from '@dcloudio/uni-app'
	import * as orderApi from "@/api/biz/orderApi.js"
	
	const createPay = () => {
		orderApi.createPay().then((res)=>{
			console.log(res);
			wx.requestPayment
			(
				{
					"appId":res.data.appId,
					"timeStamp": res.data.timeStamp,
					"nonceStr": res.data.nonceStr,
					"package": `prepay_id=${res.data.prepayId}`,
					"signType": res.data.signType,
					"paySign": res.data.paySign,
					success (res) {
					    console.log('pay success', res)
					},
					fail (err) {
					    console.error('pay fail', err)
					},
					"complete":function(res){
						console.log("complete",res);
					}
				}
			)
		})
	}
	
	onPullDownRefresh(()=>{
		console.log("刷新成功");
	}) 
</script>

<style lang="scss">
	
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值