javaspringboot创建微信支付,使用apiv2 JSAPI支付代码怎么写
时间: 2024-05-06 09:20:54 浏览: 174
wechatpay-java-main.zip
下面是一个简单的Java Spring Boot微信支付示例,使用APIv2 JSAPI支付代码:
1. 创建微信支付配置类
```java
@Configuration
public class WechatPayConfig {
@Value("${wechat.pay.appId}")
private String appId;
@Value("${wechat.pay.mchId}")
private String mchId;
@Value("${wechat.pay.apiKey}")
private String apiKey;
@Bean
public WXPay wxPay() throws Exception {
WXPayConfigImpl config = WXPayConfigImpl.getInstance();
config.setAppID(appId);
config.setMchID(mchId);
config.setKey(apiKey.getBytes());
return new WXPay(config);
}
}
```
2. 创建微信支付控制器
```java
@RestController
@RequestMapping("/api/wechat/pay")
public class WechatPayController {
@Autowired
private WXPay wxPay;
@PostMapping("/unifiedorder")
public ResponseEntity<?> unifiedOrder(@RequestBody WechatPayRequest request, HttpServletRequest httpRequest) {
try {
// 构造支付请求参数
Map<String, String> data = new HashMap<>();
data.put("body", request.getBody());
data.put("out_trade_no", request.getOutTradeNo());
data.put("total_fee", request.getTotalFee().toString());
data.put("spbill_create_ip", httpRequest.getRemoteAddr());
data.put("notify_url", "https://your-notify-url.com");
data.put("trade_type", "JSAPI");
data.put("openid", request.getOpenid());
// 调用统一下单API
Map<String, String> result = wxPay.unifiedOrder(data);
// 生成JSAPI支付参数
String prepayId = result.get("prepay_id");
Map<String, String> jsApiParams = new HashMap<>();
jsApiParams.put("appId", wxPay.getConfig().getAppID());
jsApiParams.put("timeStamp", String.valueOf(System.currentTimeMillis() / 1000));
jsApiParams.put("nonceStr", WXPayUtil.generateNonceStr());
jsApiParams.put("package", "prepay_id=" + prepayId);
jsApiParams.put("signType", "MD5");
String paySign = WXPayUtil.generateSignature(jsApiParams, wxPay.getConfig().getKey());
jsApiParams.put("paySign", paySign);
return ResponseEntity.ok(jsApiParams);
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
}
```
3. 创建微信支付请求类
```java
public class WechatPayRequest {
private String body;
private String outTradeNo;
private BigDecimal totalFee;
private String openid;
// getters and setters
}
```
4. 在application.properties文件中添加微信支付配置
```properties
wechat.pay.appId=your-appId
wechat.pay.mchId=your-mchId
wechat.pay.apiKey=your-apiKey
```
5. 使用Postman等工具测试JSAPI支付接口
发送POST请求到http://localhost:8080/api/wechat/pay/unifiedorder,请求体如下:
```json
{
"body": "测试支付",
"outTradeNo": "20220101000001",
"totalFee": 1,
"openid": "your-openid"
}
```
其中,openid是JSAPI支付必须的参数,可以通过微信OAuth2.0授权获取。
返回结果如下:
```json
{
"appId": "your-appId",
"timeStamp": "1641260647",
"nonceStr": "9jvOvEJZzVw2STN5",
"package": "prepay_id=wx01155047389241f9c9ab15d8d8e9813000",
"signType": "MD5",
"paySign": "B24F9D7F2DBE3048F7BA4D400C4B0B4B"
}
```
将返回结果中的数据传递给微信JSAPI支付接口即可完成支付。
阅读全文