微信支付示例

引入dom4j依赖

  1. 配置文件在项目中新增一个配置文件,例如 wechat.properties,并添加以下内容:
# 微信支付相关配置
# 公众账号ID
weixin.appId = YOUR_APP_ID
# 商户号
weixin.mchId = YOUR_MCH_ID
# API密钥,用于签名
weixin.apiKey = YOUR_API_KEY
# 支付成功后的回调地址
weixin.notifyUrl = YOUR_NOTIFY_URL
  1. 发起微信支付定义一个 pay 方法,用于发起微信支付:
public class WeChatPayService {
    private static final String UNIFIED_ORDER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
    private final String appId;
    private final String mchId;
    private final String apiKey;
    private final String notifyUrl;

    public WeChatPayService(String appId, String mchId, String apiKey, String notifyUrl) {
        this.appId = appId;
        this.mchId = mchId;
        this.apiKey = apiKey;
        this.notifyUrl = notifyUrl;
    }

    public String pay(String openid, String orderId, int totalFee, String ipAddress) throws Exception {
        Map<String, String> params = new HashMap<>();
        params.put("appid", appId);
        params.put("mch_id", mchId);
        params.put("nonce_str", UUID.randomUUID().toString().replaceAll("-", ""));
        params.put("",", "商品描述");
        params.put("out_trade_no", orderId);
        params.put("total_fee", String.valueOf(totalFee));
        params.put("spbill_create_ip", ipAddress);
        params.put("notify_url", notifyUrl);
        params.put("trade_type", "JSAPI");
        params.put("openid", openid);

        String xml = buildXml(params);
        String responseXml = HttpUtil.post(UNIFIED_ORDER_URL, xml);
        Map<String, String> resultMap = parseXml(responseXml);

        String returnCode = resultMap.get("return_code");
        if (!"SUCCESS".equals(returnCode)) {
            throw new Exception(resultMap.get("return_msg"));
        }

        String resultCode = resultMap.get("result_code");
        if (!"SUCCESS".equals(resultCode)) {
            throw new Exception(resultMap.get("err_code_des"));
        }

        String prepayId = resultMap.get("prepay_id");
        String nonceStr = UUID.randomUUID().toString().replaceAll("-", "");
        long timestamp = System.currentTimeMillis() / 1000;
        String packageStr = "prepay_id=" + prepayId;
        String signType = "MD5";
        String sign = sign(appId, mchId, nonceStr, packageStr, signType, apiKey, timestamp);

        Map<String, String> result = new HashMap<>();
        result.put("appId", appId);
        result.put("timeStamp", String.valueOf(timestamp));
        result.put("nonceStr", nonceStr);
        result.put("package", packageStr);
        result.put("signType", signType);
        result.put("paySign", sign);

        return new ObjectMapper().writeValueAsString(result);
    }

    private String buildXml(Map<String, String> params) throws Exception {
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("xml");
        for (Map.Entry<String, String> entry : params.entrySet()) {
            root.addElement(entry.getKey()).addText(entry.getValue());
        }
        return document.asXML();
    }

    private Map<String, String> parseXml(String xml) throws Exception {
        Map<String, String> resultMap = new HashMap<>();
        Document document = DocumentHelper.parseText(xml);
        Element root = document.getRootElement();
        List<Element> elements = root.elements();
        for (Element element : elements) {
            resultMap.put(element.getName(), element.getText());
        }
        return resultMap;
    }

    private String sign(String appId, String mchId, String nonceStr, String packageStr, String signType, String apiKey, long timestamp) throws Exception {
        Map<String, String> params = new HashMap<>();
        params.put("appId", appId);
        params.put("timeStamp", String.valueOf(timestamp));
        params.put("nonceStr", nonceStr);
        params.put("package", packageStr);
        params.put("signType", signType);

        List<String> sortedKeys = new ArrayList<>(params.keySet());
        Collections.sort(sortedKeys);

        StringBuilder sb = new StringBuilder();
        for (String key : sortedKeys) {
            sb.append(key).append("=").append(params.get(key)).append("&");
        }
        sb.append("key=").append(apiKey);

        String sign = DigestUtils.md5Hex(sb.toString()).toUpperCase();

        return sign;
    }
}
  1. 支付结果通知定义一个 notify 方法,用于处理微信支付结果通知:
public class WeChatPayService {
    public boolean notify(String requestBody) throws Exception {
        Map<String, String> params = parseXml(requestBody);
        String returnCode = params.get("return_code");
        if (!"SUCCESS".equals(returnCode)) {
            return false;
        }

        String resultCode = params.get("result_code");
        if (!"SUCCESS".equals(resultCode)) {
            return false;
        }

        String appId = params.get("appid");
        String mchId = params.get("mch_id");
        String openid = params.get("openid");
        String orderId = params.get("out_trade_no");
        String transactionId = params.get("transaction_id");
        int totalFee = Integer.parseInt(params.get("total_fee"));

        String sign = params.get("sign");
        String signType = params.get("sign_type");
        params.remove("sign");
        params.remove("sign_type");

        List<String> sortedKeys = new ArrayList<>(params.keySet());
        Collections.sort(sortedKeys);

        StringBuilder sb = new StringBuilder();
        for (String key : sortedKeys) {
            sb.append(key).append("=").append(params.get(key)).append("&");
        }
        sb.append("key=").append(apiKey);

        String calculatedSign = DigestUtils.md5Hex(sb.toString()).toUpperCase();

        if (!calculatedSign.equals(sign)) {
            return false;
        }

        // 在这里处理支付结果
        // ...

        return true;
    }
}
  1. 使用示例
public class Main {
    public static void main(String[] args) throws Exception {
        Properties props = new Properties();
        props.load(Main.class.getClassLoader().getResourceAsStream("wechat.properties"));

        String appId = props.getProperty("weixin.appId");
        String mchId = props.getProperty("weixin.mch");

        String apiKey = props.getProperty("weixin.apiKey");
        String notifyUrl = props.getProperty("weixin.notifyUrl");

        WeChatPayService payService = new WeChatPayService(appId, mchId, apiKey, notifyUrl);

        // 发起支付
        String openid = "YOUR_OPENID";
        String orderId = "YOUR_ORDER_ID";
        int totalFee = 100;
        String ipAddress = "YOUR_IP_ADDRESS";
        String result = payService.pay(openid, orderId, totalFee, ipAddress);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值