Spring Boot中实现支付宝、微信和银联支付的功能

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

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
下面是一个使用Spring Boot实现企业级微信支付接口的代码示例: 1. 配置文件(application.properties): ``` # 微信支付配置 wechat.pay.appId=your_appId wechat.pay.mchId=your_mchId wechat.pay.key=your_key wechat.pay.notifyUrl=your_notifyUrl wechat.pay.certPath=/path/to/your_cert.p12 ``` 2. 支付参数实体类(PayParams.java): ```java public class PayParams { private String body; // 商品描述 private String outTradeNo; // 商户订单号 private int totalFee; // 订单总金额(单位:分) // 其他参数... // getter和setter方法... } ``` 3. 支付回调实体类(PayCallback.java): ```java public class PayCallback { private String returnCode; // 返回状态码 private String returnMsg; // 返回信息 // 其他参数... // getter和setter方法... } ``` 4. 支付服务类(PayService.java): ```java @Service public class PayService { @Value("${wechat.pay.appId}") private String appId; @Value("${wechat.pay.mchId}") private String mchId; @Value("${wechat.pay.key}") private String key; @Value("${wechat.pay.notifyUrl}") private String notifyUrl; @Value("${wechat.pay.certPath}") private String certPath; public String unifiedOrder(PayParams payParams) throws Exception { // 构建统一下单请求参数 Map<String, String> data = new HashMap<>(); data.put("appid", appId); data.put("mch_id", mchId); data.put("nonce_str", WXPayUtil.generateNonceStr()); data.put("body", payParams.getBody()); data.put("out_trade_no", payParams.getOutTradeNo()); data.put("total_fee", String.valueOf(payParams.getTotalFee())); // 其他参数... // 生成签名 String sign = WXPayUtil.generateSignature(data, key); data.put("sign", sign); // 发起统一下单请求 WXPayRequest wxPayRequest = new WXPayRequest(); Map<String, String> result = wxPayRequest.requestWithCert("/pay/unifiedorder", data, certPath, mchId); // 处理返回结果 if ("SUCCESS".equals(result.get("return_code")) && "SUCCESS".equals(result.get("result_code"))) { return result.get("prepay_id"); } else { throw new Exception(result.get("return_msg")); } } public PayCallback parsePayCallback(String xmlData) throws Exception { // 解析支付回调数据 Map<String, String> map = WXPayUtil.xmlToMap(xmlData); // 验证签名 if (WXPayUtil.isSignatureValid(map, key)) { PayCallback payCallback = new PayCallback(); payCallback.setReturnCode(map.get("return_code")); payCallback.setReturnMsg(map.get("return_msg")); // 其他参数... return payCallback; } else { throw new Exception("Invalid signature"); } } } ``` 5. 支付控制器类(PayController.java): ```java @RestController @RequestMapping("/pay") public class PayController { @Autowired private PayService payService; @PostMapping("/unifiedOrder") public String unifiedOrder(@RequestBody PayParams payParams) throws Exception { return payService.unifiedOrder(payParams); } @PostMapping("/callback") public String callback(HttpServletRequest request) throws Exception { String xmlData = IOUtils.toString(request.getInputStream(), "UTF-8"); PayCallback payCallback = payService.parsePayCallback(xmlData); // 处理支付结果,更新订单状态等逻辑... return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>"; } } ``` 以上代码示例使用了微信支付Java SDK:`com.github.wxpay.sdk`,你需要添加相应的依赖。 这只是一个简单的示例,实际开发还需要根据业务需求进行适当的调整和扩展。同时,还需要保证支付过程的安全性和正确性,例如验证回调通知的有效性、处理支付结果等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

雨轩智能

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值