SpringBoot集成微信支付(JAVA)

微信支付(Java)

目录

微信支付(Java)

简介:

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

注意事项:

添加依赖:

application.yaml:

WeixinPayController:

PaymentService:

PaymentServiceImpl:

实体类PaymentJSAPI:


简介:

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

登录微信支付(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";
    }
}

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

  • 36
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

偷猪的

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

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

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

打赏作者

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

抵扣说明:

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

余额充值