最近公司业务需要微信支付,上网查了很多资料没有最新版的简易使用方法,今天它来了(包成功)!!!
微信支付API文档https://pay.weixin.qq.com/docs/merchant/products/jsapi-payment/development.html
1、 导入官方推荐的maven依赖
<!-- 微信支付-->
<dependency>
<groupId>com.github.wechatpay-apiv3</groupId>
<artifactId>wechatpay-java</artifactId>
<version>0.2.12</version>
</dependency>
2、封装微信支付配置类
@Configuration
public class WechatPayConfig {
@Value("${wechat.merchantId}")
private String merchantId;
@Value("${wechat.privateKeyPath}")
private String privateKeyPath;
@Value("${wechat.merchantSerialNumber}")
private String merchantSerialNumber;
@Value("${wechat.apiV3Key}")
private String apiV3Key;
/**
* 创建 Native 支付服务对象
*
* @return NativePayService
*/
@Bean
public NativePayService nativePayService() {
Config config =
new RSAAutoCertificateConfig.Builder()
.merchantId(merchantId)
.privateKeyFromPath(privateKeyPath)
.merchantSerialNumber(merchantSerialNumber)
.apiV3Key(apiV3Key)
.build();
return new NativePayService.Builder().config(config).build();
}
}
3、注入微信支付依赖
@Autowired
private NativePayService nativePayService;
@Value("${wechat.appId}")
private String appId;
@Value("${wechat.merchantId}")
private String merchantId;
PrepayRequest request = new PrepayRequest();
Amount amount = new Amount();
amount.setTotal(1);
request.setAmount(amount);
request.setAppid(appId);
request.setMchid(merchantId);
request.setDescription("测试商品标题");
request.setNotifyUrl("https://api.mch.weixin.qq.com/v3/pay/transactions/native");
request.setOutTradeNo("20190914144714889");
// 调用下单方法,得到应答
PrepayResponse response = nativePayService.prepay(request);
// 使用微信扫描 code_url 对应的二维码,即可体验Native支付
System.out.println(response.getCodeUrl());
4、请商户调用第三方库将code_url生成二维码图片
weixin://wxpay/bizpayurl?pr=8LGofvcz3(生成示例)
5、将二维码生成可访问图片
(1)后端: 中间对比了几家,ZXing相对简单、好用
<!-- ZXing核心库 -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.4.1</version>
</dependency>
<!-- ZXing Java SE工具库 -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.4.1</version>
</dependency>
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(response.getCodeUrl(), BarcodeFormat.QR_CODE, 350, 350);
Path path = FileSystems.getDefault().getPath("./QRCode.png");
MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
(2)前端:@chenfengyuan/vue-qrcode
官网:vue-qrcode
npm install @chenfengyuan/vue-qrcode
<template>
<div>
<VueQrcode
:value="qrCode"
:options="QrCodeOpt"
style="margin: 0 auto"
></VueQrcode>
</div>
</template>
<script>
// 插件直接生成二维码
import VueQrcode from "@chenfengyuan/vue-qrcode";
export default {
components: { VueQrcode },
data() {
return {
qrCode: "weixin://wxpay/bizpayurl?pr=8LGofvcz3",
QrCodeOpt: {
errorCorrectionLevel: "H",
width: 250,
height: 250,
quality: 0.3,
margin: 1,
color: {
dark: "#010599FF",
light: "#FFBF60FF",
},
},
};
},
};
</script>