一.所需参数及maven依赖
官方文档
1.公众号id appid
2.商户号 mchid
3.APIv3秘钥 secret
4.商户api私钥 apiclient_key.pem
5.证书序列号
maven依赖
<!-- 微信支付V3版sdk -->
<dependency>
<groupId>com.github.wechatpay-apiv3</groupId>
<artifactId>wechatpay-apache-httpclient</artifactId>
<version>0.2.1</version>
</dependency>
二.前端vue部分
// 确认支付
onSubmit() {
// 手机端校验
if (!navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)) {
this.$dialog.alert({
message: '请在手机端微信关注公众号"跃迁赋能中心"进行购买' })
return
}
// TODO 购买商品参数拼接、非空校验
let that = this
this.$api.request({
url: '/wxpay/pay',
method: 'post',
params: params
}).then(response => {
// 拉起微信支付参数赋值
that.payMap = response.data
if (typeof WeixinJSBridge === 'undefined') {
if (document.addEventListener) {
document.addEventListener('WeixinJSBridgeReady', this.onBridgeReady, false)
} else if (document.attachEvent) {
document.attachEvent('WeixinJSBridgeReady', this.onBridgeReady)
document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady)
}
} else {
this.onBridgeReady()
}
})
},
// 拉起微信支付
onBridgeReady() {
let payMap = this.payMap
let that = this
WeixinJSBridge.invoke(
'getBrandWCPayRequest', {
'appId': payMap.appId, // 公众号名称,由商户传入
'timeStamp': payMap.timeStamp, // 时间戳,自1970年以来的秒数
'nonceStr': payMap.nonceStr, // 随机串
'package': payMap.package,
'signType': payMap.signType, // 微信签名方式:
'paySign': payMap.paySign // 微信签名
},
function(res) {
if (res.err_msg == 'get_brand_wcpay_request:ok') {
// 付款成功处理
that.$router.replace({
path: '/' })
}
})
},
三.后端java部分
3.1 获取前端拉起微信支付参数
Controller
@ApiOperation("微信公众号支付")
@PostMapping("/pay")
public AjaxResult pay(HttpServletRequest request, @RequestParam(required = false) String miniIdStr,
@RequestParam Double payAmount, @RequestParam String couponIdStr,
@RequestParam(required = false) Long courseId) {
Long personId = tokenService.getPersonId(request);
// TODO 购买课程参数校验
try {
JSONObject result = officeOrderService.wxPay(personId, miniIdStr, payAmount, couponIdStr, courseId);
Integer status = result.getInteger("status");
if (status != null && status == 0) {
// 支付失败不反回前端拉起微信支付参数
return AjaxResult.error("支付失败,请稍后再试");
}
return AjaxResult.success(result);
} catch (Exception e) {
log.error("微信支付下单接口失败,personId:{},miniIdStr:{},payAmount:{},couponIdStr:{},courseId:{}", personId,
miniIdStr, payAmount, couponIdStr, courseId, e);
return AjaxResult.error("支付失败,请稍后再试");
}
}
Service
@Override
public JSONObject wxPay(Long personId, String miniIdStr, Double payAmount, String couponIdStr, Long courseId) {
// 根据personId获取公众号openId
String openId = wxLoginMapper.selectOpenIdByPersonId(personId);
// 生成商品订单号
String orderNumber = UUID.