@sigodenjs/wechatpay

微信支付 SDK,支持刷卡支付、公众号支付、扫码支付、APP支付、H5支付,以及优惠券,红包,企业付款,微信代扣

Usage no npm install needed!

<script type="module">
  import sigodenjsWechatpay from 'https://cdn.skypack.dev/@sigodenjs/wechatpay';
</script>

README

微信支付 node.js

Build Status Codacy Badge dependencies Status Known Vulnerabilities

微信支付 SDK,支持刷卡支付、公众号支付、扫码支付、APP 支付、H5 支付,以及优惠券,红包,企业付款,微信代扣

特性

  • 使用 Typescript 编写,拥有更安全的类型和更好的代码提示
  • 支持所有类型微信支付
  • 支持微信代扣
  • 提供调试模式

开始使用

const path = require("path");
const fs = require("fs");
const {
  PubPay,
  RequestError,
  CommunicationError,
  utils: { getXMLBody }
} = require("@sigodenjs/wechatpay");

const pay = new PubPay({
  appId: "wxb80e5bddb2d804f3",
  key: "6Q9VX4N3WTBM9G9XBL7H1L9PB9ANHLY7",
  mchId: "1434712502",
  pfx: fs.readFileSync(path.resolve(__dirname, "cert.p12"))
});

// 调用统一下单接口
pay
  .unifiedOrder({
    body: "腾讯充值中心-QQ会员充值",
    out_trade_no: "1217752501201407033233368018",
    total_fee: 888,
    spbill_create_ip: "8.8.8.8",
    notify_url: "https://example.com/wechatpay/notify",
    trade_type: "JSAPI",
    openid: "oUpF8uMuAJO_M2pxb1Q9zNjWeS6o"
  })
  .then(res => {
    if (!pay.verifySign(res)) {
      // 签名校验失败
      throw new Error("签名校验失败");
    }
    if (res.result_code === "FAIL") {
      console.log(res.err_code, res.err_code_des);
    } else {
      console.log(res.prepay_id);
    }
  })
  .catch(err => {
    if (err instanceof RequestError) {
      // 请求错误
    } else if (err instanceof CommunicationError) {
      // return_code = FAIL
    }
  });

// 支付结果通知
router.post("/wechatpay/notify", (req, res) => {
  const options = {
    length: req.headers["content-length"],
    limit: "1mb",
    encoding: "utf8"
  };
  getXMLBody(req, options).then(data => {
    pay
      .payNotify(data, async parsedData => {
        if (!pay.verifySign(parsedData)) {
          // 签名校验失败
        }
        if (parsedData.result_code === "FAIL") {
          // 业务逻辑失败
        }
        // ...
        return {
          return_code: "SUCCESS",
          return_msg: "OK"
        };
      })
      .then(returnData => {
        res.set("Content-Type", "application/xml; charset=utf-8");
        res.end(returnData);
      });
  });
});

类和接口

业务类

综合类

  • Pay: 组合所有支付类,包含所有支付相关接口
  • Entrust: 组合所有代扣类,包含所有代扣相关接扣

如果你只使用了某一项支付,请使用业务类。但如果涉及多种支付,使用综合类更便捷。

支付相关接口

代扣相关接口

许可证

Copyright (c) 2018 sigoden

Licensed under the MIT license.