返回

微信小程序支付开发从入门到精通

前端

微信小程序支付:从入门到精通

准备工作

踏上微信小程序支付之旅前,你需要备齐以下装备:

  • 一个微信小程序项目
  • 一个 SpringBoot 项目
  • 一个微信支付商户号
  • 一个微信支付 API 秘钥

SpringBoot 项目配置

  1. 添加依赖:
<dependency>
  <groupId>com.github.binarywang</groupId>
  <artifactId>weixin-java-miniapp</artifactId>
  <version>3.16.0</version>
</dependency>
  1. 配置微信支付参数:
@Configuration
public class WechatPayConfig {

    @Value("${wxpay.appid}")
    private String appId;

    @Value("${wxpay.mchId}")
    private String mchId;

    @Value("${wxpay.mchKey}")
    private String mchKey;

    @Value("${wxpay.notifyUrl}")
    private String notifyUrl;

    @Bean
    public WxPayService wxPayService() {
        WxPayConfigImpl config = new WxPayConfigImpl();
        config.setAppId(appId);
        config.setMchId(mchId);
        config.setMchKey(mchKey);
        config.setNotifyUrl(notifyUrl);
        return new WxPayServiceImpl();
    }
}

微信小程序端开发

  1. 创建支付订单:
const orderInfo = {
  body: '商品名称',
  out_trade_no: '订单号',
  total_fee: '金额(单位:分)',
};

wx.requestPayment({
  ...orderInfo,
  success: (res) => {
    console.log('支付成功', res);
  },
  fail: (err) => {
    console.log('支付失败', err);
  },
});
  1. 接收支付回调:
@PostMapping("/wechat/pay/notify")
public String payNotify(@RequestBody String xml) {
    WxPayService wxPayService = wxPayService();
    PayNotifyResponse response = wxPayService.parsePayNotifyResult(xml);
    if (response.isReturnCodeSuccess()) {
        // 支付成功,处理业务逻辑
        return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
    } else {
        return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[支付失败]]></return_msg></xml>";
    }
}

结语

恭喜你!通过这篇教程,你已经掌握了使用 SpringBoot 和微信小程序实现支付功能的精髓。如果你在实践中遇到困难,欢迎随时留言提问。

常见问题解答

  1. 无法创建支付订单,提示缺少参数: 检查 orderInfo 对象是否包含了所有必需的参数:body、out_trade_no 和 total_fee。

  2. 支付回调无法正常接收: 确认你的服务器已经正确配置了支付回调 URL,并且在测试时使用的是正确的回调 URL。

  3. 支付失败,提示签名错误: 检查你的签名算法是否与微信支付的要求一致,并确保使用的密钥与配置的商户号相匹配。

  4. 无法在微信小程序中调起支付: 确保你的小程序已经通过审核,并且你的微信支付功能已经开通。

  5. 支付成功后,找不到对应的订单: 检查你的订单管理系统是否已正确接收并处理了支付回调。