Spring Boot中实现支付宝、微信和银联支付的功能
在Spring Boot中实现支付宝、微信和银联支付的功能,通常需要使用它们各自的SDK(Software Development Kit)。以下是一个简单的示例代码,演示了如何在Spring Boot项目中集成支付宝、微信和银联支付功能。请注意,这只是一个基本的示例,实际上,支付集成涉及更多的配置和安全考虑。
1. 集成支付宝支付
首先,你需要添加支付宝SDK的依赖。在pom.xml
中添加以下依赖:
<dependency>
<groupId>com.alipay.sdk</groupId>
<artifactId>alipay-sdk-java</artifactId>
<version>3.10.0.ALL</version>
</dependency>
然后,创建一个Controller类,处理支付宝支付请求:
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/alipay")
public class AlipayController {
@Value("${alipay.appId}")
private String appId;
@Value("${alipay.privateKey}")
private String privateKey;
@Value("${alipay.publicKey}")
private String publicKey;
@RequestMapping(value = "/pay", method = RequestMethod.POST)
@ResponseBody
public String alipay(@RequestParam("outTradeNo") String outTradeNo,
@RequestParam("totalAmount") String totalAmount,
@RequestParam("subject") String subject) throws AlipayApiException {
AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", appId, privateKey, "json", "utf-8", publicKey, "RSA2");
AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
alipayRequest.setReturnUrl("回调地址");
alipayRequest.setNotifyUrl("异步通知地址");
alipayRequest.setBizContent("{\"out_trade_no\":\"" + outTradeNo + "\","
+ "\"total_amount\":\"" + totalAmount + "\","
+ "\"subject\":\"" + subject + "\","
+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
return alipayClient.pageExecute(alipayRequest).getBody();
}
}
在application.properties
中添加支付宝相关的配置:
alipay.appId=your_app_id
alipay.privateKey=your_private_key
alipay.publicKey=your_public_key
2. 集成微信支付
首先,你需要添加微信支付SDK的依赖。在pom.xml
中添加以下依赖:
<dependency>
<groupId>com.github.wxpay</groupId>
<artifactId>wxpay-sdk</artifactId>
<version>0.0.3</version>
</dependency>
然后,创建一个Controller类,处理微信支付请求:
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConfigImpl;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;
@Controller
@RequestMapping("/wechat")
public class WechatController {
@Value("${wechat.appId}")
private String appId;
@Value("${wechat.mchId}")
private String mchId;
@Value("${wechat.key}")
private String key;
@RequestMapping(value = "/pay", method = RequestMethod.POST)
@ResponseBody
public Map<String, String> wechatPay(@RequestParam("outTradeNo") String outTradeNo,
@RequestParam("totalFee") String totalFee,
@RequestParam("body") String body,
@RequestParam("spbillCreateIp") String spbillCreateIp) throws Exception {
WXPayConfigImpl config = new WXPayConfigImpl();
config.setAppID(appId);
config.setMchID(mchId);
config.setKey(key);
WXPay wxPay = new WXPay(config, WXPayConstants.SignType.MD5);
Map<String, String> data = new HashMap<>();
data.put("body", body);
data.put("out_trade_no", outTradeNo);
data.put("total_fee", totalFee);
data.put("spbill_create_ip", spbillCreateIp);
data.put("trade_type", "NATIVE");
data.put("notify_url", "异步通知地址");
Map<String, String> result = wxPay.unifiedOrder(data);
if ("SUCCESS".equals(result.get("return_code")) && "SUCCESS".equals(result.get("result_code"))) {
String codeUrl = result.get("code_url");
// 返回给前端,用于生成支付二维码
Map<String, String> response = new HashMap<>();
response.put("codeUrl", codeUrl);
return response;
} else {
// 处理支付失败的逻辑
throw new Exception("微信支付失败:" + result.get("return_msg"));
}
}
}
在application.properties
中添加微信相关的配置:
wechat.appId=your_app_id
wechat.mchId=your_mch_id
wechat.key=your_key
3. 集成银联支付
首先,你需要添加银联支付SDK的依赖。在pom.xml
中添加以下依赖:
<dependency>
<groupId>cn.joylau.commons</groupId>
<artifactId>unionpay-common</artifactId>
<version>1.0.0</version>
</dependency>
然后,创建一个Controller类,处理银联支付请求:
import cn.joylau.commons.unionpay.acp.sdk.AcpService;
import cn.joylau.commons.unionpay.acp.sdk.LogUtil;
import cn.joylau.commons.unionpay.acp.sdk.SDKConfig;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;
@Controller
@RequestMapping("/unionpay")
public class UnionpayController {
@RequestMapping(value = "/pay", method = RequestMethod.POST)
@ResponseBody
public String unionpay(@RequestParam("orderId") String orderId,
@RequestParam("txnAmt") String txnAmt) {
Map<String, String> requestData = new HashMap<>();
// 银联分配的商户号
requestData.put("merId", "your_mer_id");
// 订单号,8-40位数字字母
requestData.put("orderId", orderId);
// 交易金额,单位分
requestData.put("txnAmt", txnAmt);
// 前台交易请求地址
requestData.put("frontUrl", "前台回调地址");
// 后台交易请求地址
requestData.put("backUrl", "后台回调地址");
// 其他参数...
Map<String, String> responseData = AcpService.post(requestData, "https://gateway.95516.com/gateway/api/frontTransReq.do", "UTF-8");
if (!AcpService.validate(responseData, "UTF-8")) {
// 验证签名失败
LogUtil.writeLog("验证签名失败");
// 处理支付失败的逻辑
return "验证签名失败";
}
String respCode = responseData.get("respCode");
if ("00".equals(respCode)) {
// 支付成功,处理业务逻辑
return "支付成功";
} else {
// 支付失败,处理业务逻辑
return "支付失败:" + responseData.get("respMsg");
}
}
}
在application.properties
中添加银联相关的配置:
# 银联商户号
acpsdk.merId=your_mer_id
# 银联签名私钥
acpsdk.signCert.path=/path/to/your_sign_cert.pfx
# 银联签名私钥密码
acpsdk.signCert.pwd=your_sign_cert_password
# 银联验签公钥
acpsdk.validateCert.dir=/path/to/your_validate_cert_dir
# 银联对账文件下载地址
acpsdk.fileTransUrl=https://filedownload.95516.com/
以上代码仅为示例,实际情况中需要根据具体需求进行适当调整。请确保在生产环境中采取必要的安全措施,如使用HTTPS、加密敏感信息等。
示例中完整代码,可以从下面网址获取:
https://gitee.com/jlearning/wechatdemo.git
https://github.com/icoderoad/wxdemo.git