一.pom.xml
在 pom.xml 内添加相关依赖:
<dependency>
<groupId>com.github.wechatpay-apiv3</groupId>
<artifactId>wechatpay-java</artifactId>
<version>0.2.14</version>
</dependency>
二.application.yml
在 application.yml 内添加相关基础配置
app:
merchant:
id: XXXXXXXXXXX //商户号
private-key-path: XXXXXX/XXXXX/apiclient_key.pem //商户API私钥路径
serial-number: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX //商户证书序列号
api-v3-key: 12345678910111213141516171819202 //商户APIV3密钥
三.config下
1.创建MerchantConfig类
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**功能:绑定配置文件属性 **/
@Component
@ConfigurationProperties(prefix = "app.merchant")
public class MerchantConfig {
/** 商户号 */
private String id;
/** 商户API私钥路径 */
private String privateKeyPath;
/** 商户证书序列号 */
private String serialNumber;
/** 商户APIV3密钥 */
private String apiV3Key;
// Getters and Setters
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPrivateKeyPath() {
return privateKeyPath;
}
public void setPrivateKeyPath(String privateKeyPath) {
this.privateKeyPath = privateKeyPath;
}
public String getSerialNumber() {
return serialNumber;
}
public void setSerialNumber(String serialNumber) {
this.serialNumber = serialNumber;
}
public String getApiV3Key() {
return apiV3Key;
}
public void setApiV3Key(String apiV3Key) {
this.apiV3Key = apiV3Key;
}
}
2.创建AppConfig类
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
/**
* 功能:应用启动时自动初始化与微信支付相关的配置
* **/
@Configuration
public class AppConfig {
private Config config;
@Autowired
private MerchantConfig merchantConfig;
@PostConstruct
public void init() {
// 使用自动更新平台证书的RSA配置
// 一个商户号只能初始化一个配置,否则会因为重复的下载任务报错
config = new RSAAutoCertificateConfig.Builder()
.merchantId(merchantConfig.getId())
.privateKeyFromPath(merchantConfig.getPrivateKeyPath())
.merchantSerialNumber(merchantConfig.getSerialNumber())
.apiV3Key(merchantConfig.getApiV3Key())
.build();
}
public Config getConfig() {
return config;
}
}
四.service下
创建QuickStart
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.model.*;
import com.zhaoxinms.config.AppConfig;
import com.zhaoxinms.config.MerchantConfig;
import com.zhaoxinms.payment.entity.PaymentBillEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/** 构建和发送微信支付的预支付请求。 **/
@Service
public class QuickStart {
@Autowired
private MerchantConfig merchantConfig;
@Autowired
private AppConfig config;
public PrepayWithRequestPaymentResponse calculateSignature(Integer moneyCount, List<PaymentBillEntity> costArray,String openid) throws Exception{
//拼接商品名
StringBuilder sb = new StringBuilder();
for (PaymentBillEntity p : costArray) {
sb.append(p.getFeeItemName());
sb.append("-");
}
if (sb.length() > 0) {
sb.setLength(sb.length() - 1);
}
String result = sb.toString();
PrepayRequest request = new PrepayRequest();
Amount amount = new Amount();
amount.setTotal(moneyCount);
request.setAmount(amount);
request.setAppid("wxXXXXXXXXXXXXX");
request.setMchid(merchantConfig.getId());
request.setDescription(costArray.get(0).getResourceName()+":"+result);
request.setNotifyUrl("https://www.xxxx.xxx/wx/notify");
request.setOutTradeNo(costArray.get(0).getId());
Payer payer = new Payer();
payer.setOpenid(openid);
request.setPayer(payer);
JsapiServiceExtension jsapiServiceExtension = new JsapiServiceExtension.Builder().config(config.getConfig()).build();
PrepayWithRequestPaymentResponse abc = jsapiServiceExtension.prepayWithRequestPayment(request);
return abc;
}
五.controller
创建WeChatPay类
import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
import com.zhaoxinms.owner.service.impl.QuickStart;
import com.zhaoxinms.payment.entity.PaymentBillEntity;
import com.zhaoxinms.payment.entity.PaymentRequest;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
/**
* 微信小程序对接的接口
**/
@RestController
@RequestMapping("/wx")
public class WeChatPay {
private final QuickStart quickStart;
public WeChatPay(QuickStart quickStart) {
this.quickStart = quickStart;
}
@PostMapping("/generate-signature")
public PrepayWithRequestPaymentResponse generateSignatures(@RequestBody PaymentRequest request) throws Exception{
if (request.getOpenid() != null && request.getCostArray() != null && request.getMoneyCount() != null){
Integer moneyCount = request.getMoneyCount();
List<PaymentBillEntity> costArray = request.getCostArray();
String openid = request.getOpenid();
if (moneyCount == 0){
return null;
}
return quickStart.calculateSignature(moneyCount,costArray,openid);
}
return null;
}
@PostMapping("/notify")
public String receiveNotification() {
System.out.println("支付成功!");
// 返回给微信支付系统一个成功的响应
return "<xml><return_code>SUCCESS</return_code><return_msg>OK</return_msg></xml>";
}
}
六.其它
PaymentBillEntity类自建,属性为订单相关信息。PaymentRequest类自建,为接收前端传过来的相关数据集合。(主要有:moneyCount、costArray、openid)
七.微信小程序
支付相关js页面,点击支付的方法如下:
wx.request({
url: app.globalData.url+'/wx/generate-signature',
data: {
moneyCount: that.data.moneyCount*100,
costArray: that.data.costArray,
openid:openid
},
method: 'POST',
success(res){
const abc = res.data
const timeStamp = res.data.timeStamp
const nonceStr =res.data.nonceStr
const packageVal = res.data.packageVal
const paySign = res.data.paySign
wx.requestPayment({
"timeStamp": timeStamp,
"nonceStr": nonceStr,
"package": packageVal,
"signType": "RSA",
"paySign": paySign,
success:function(res){
const paymentBillListVO = that.data.costArray
const totalMoney = that.data.moneyCount
const dataToSend = {
paymentBillListVO: paymentBillListVO,
totalMoney: totalMoney.toString()
wx.request({
url: app.globalData.url+'/wx/notifys',
method:"POST",
data:dataToSend,
success(res){
wx.showToast({
title: '支付成功!',
})
that.hqjfxx()
},
fail(err){
console.log(err+"err");
wx.showToast({
title: '已取消支付!',
icon:'none'
})
}
})
},
fail:function(res){
wx.showToast({
title: '已取消支付!',
icon:'none'
})
},
complete:function(res){
// console.log(res+"取消支付");
}
})
console.log(res);
},
fail(err){
console.log(err);
}
})