小程序云函数如何接入微信支付分功能?

小程序云开发现在越来越备受开发者的喜欢,但是如何在云函数里面接入微信支付分呢?这方面的文档还比较少,今天有点空余时间,简单总结下我在接入微信支付分的一些经验

  1. 要接入微信支付分之前,需要写邮件给腾讯去申请,一般要等2到3天时间回收到回复

  2. 开发之前需要仔细阅读如下接入文档

https://pay.weixin.qq.com/wiki/doc/apiv3/wxpay/payscore/chapter6_1.shtml

  1. 具体代码如下,最麻烦的地方在验证签名的地方, 官方并没有提供nodejs相关验证签名的实例代码。
//云函数入口文件
const cloud = require('wx-server-sdk')
const TcbRouter = require('tcb-router');
const moment = require('moment')
const stringRandom = require('string-random');
const request = require('request');
const rp = require('request-promise');
const crypto = require('crypto')
const jsrsasign = require('jsrsasign')
const KEYUTIL = jsrsasign.KEYUTIL
const KJUR = jsrsasign.KJUR
const tenpay = require('tenpay');
const util = require('util');
const forge = require('node-forge');
const fs = require('fs')
const uuid = require('node-uuid');
cloud.init({
  env: process.env.ID
})
const db = cloud.database()
const private_key = fs.readFileSync('apiclient_key.pem');

const mchid = "你自己的商户号";
const serialNo = "商户证书号";
const serviceId = "申请的支付分服务号"
const api3Key = "api3 key"
const apiKey = "api key"

const config = {
  appid: '您的appid',
  mchid: '商户号',
  partnerKey: apiKey, //就是微信支付账户里面设置的API密钥
  pfx: require('fs').readFileSync('apiclient_cert.p12'), //这是pfx格式的证书,支付不用证书,但是退款什么的会用到
  notify_url: 'http://www.weixin.qq.com/wxpay/pay.php', //随便写一个,云函数无法实现返回结果,但有巧妙的方法实现同样功能
  spbill_create_ip: '127.0.0.1' //随便写一个,为一些POS场合用的
};

//云函数入口函数
exports.main = async(event, content) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID
  const app = new TcbRouter({
    event
  });
  app.router('queryZFFOrder', async(ctx) => {
    console.log(util.inspect(event))
    event.method = "GET"
    event.url = `https://api.mch.weixin.qq.com/v3/payscore/serviceorder?out_order_no=${event.out_order_no}&service_id=${serviceId}&appid=${config.appid}`
    let auth = getAuthorization(event)
    let result = await rp({
      url: event.url,
      method: event.method,
      json: true,
      headers: {
        "Content-Type": "application/json",
        "Accept": "application/json",
        "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 9_3_5 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13G36",
        "Authorization": auth
      }
    })
    ctx.body = result
  })
  app.router('completeZFFOrder', async(ctx) => {
    console.log(util.inspect(event))
    event.url = `https://api.mch.weixin.qq.com/v3/payscore/serviceorder/${event.out_order_no}/complete`
    event.method = "POST"
    event.body = {
      appid: config.appid,
      service_id: serviceId,
      post_payments: [{
        name: "借阅费用",
        amount: event.amount
      }],
      total_amount: event.amount,
      time_range: {
        end_time: moment().utcOffset(8).format("YYYYMMDDHHmmss")
      }
    }
    let authorization = getAuthorization(event)
    let result = await rp({
      uri: event.url,
      method: "POST",
      json: true,
      headers: {
        "Content-Type": "application/json; charset=utf-8",
        "Accept": "application/json",
        "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 9_3_5 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13G36",
        "Authorization": authorization
      },
      body: event.body
    })
    ctx.body = result
  })
  app.router("createZFFOrder", async(ctx) => {
    console.log(util.inspect(event))
    const configuration = await db.collection("configuration").where({
      name: "deposit"
    }).get()
    let deposit = configuration.data[0].value
    const configuration2 = await db.collection("configuration").where({
      name: "ZFFCallbackURL"
    }).get()
    let callbackURL = configuration2.data[0].value

    let out_order_no = uuid.v1().replace(new RegExp('-', "g"), "")
    event.url = "https://api.mch.weixin.qq.com/v3/payscore/serviceorder"
    event.method = "POST"
    event.body = {
      out_order_no: out_order_no,
      appid: config.appid,
      service_id: serviceId,
      service_introduction: "借书巴巴",
      location: {
        start_location: event.address.slice(0, 49)
      },
      time_range: {
        start_time: "OnAccept"
      },
      risk_fund: {
        name: "DEPOSIT",
        amount: deposit
      },
      post_payments: [{
        name: `${event.title.slice(0, 14)}-借阅费用`,
        amount: parseInt(event.price * 100),
        description: `借阅${event.days}天, 共${event.price}元`
      }],
      notify_url: callbackURL,
      need_user_confirm: true
    }

    let authorization = getAuthorization(event)
    let result = await rp({
      uri: event.url,
      method: "POST",
      json: true,
      headers: {
        "Content-Type": "application/json; charset=utf-8",
        "Accept": "application/json",
        "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 9_3_5 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13G36",
        "Authorization": authorization
      },
      body: event.body
    })
    result.out_order_no = out_order_no
    if (result.state == "CREATED") {
      ctx.body = getExtraData(result.package, out_order_no)
    } else {
      ctx.body = result
    }
  })
  app.router('changeZFFOrder', async(ctx) => {
    event.method = "POST"
    event.url = `https://api.mch.weixin.qq.com/v3/payscore/serviceorder/${event.out_order_no}/modify`
    event.body = {
      appid: config.appid,
      service_id: serviceId,
      post_payments: event.payments,
      total_amount: event.total_amount,
      reason: event.reason
    }
    console.log(util.inspect(event))
    let auth = getAuthorization(event)
    let result = await rp({
      url: event.url,
      method: event.method,
      json: true,
      headers: {
        "Content-Type": "application/json",
        "Accept": "application/json",
        "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 9_3_5 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13G36",
        "Authorization": auth
      },
      body: event.body
    })
    ctx.body = result
  })
  app.router('cancelZFFOrder', async(ctx) => {
    console.log(util.inspect(event))
    event.url = `https://api.mch.weixin.qq.com/v3/payscore/serviceorder/${event.out_order_no}/cancel`
    event.method = "POST"
    event.body = {
      appid: config.appid,
      service_id: serviceId,
      reason: event.reason
    }
    let authorization = getAuthorization(event)
    let result = await rp({
      uri: event.url,
      method: "POST",
      json: true,
      headers: {
        "Content-Type": "application/json; charset=utf-8",
        "Accept": "application/json",
        "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 9_3_5 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13G36",
        "Authorization": authorization
      },
      body: event.body
    })
    ctx.body = result
  })
  app.router('syncZFFOrder', async(ctx) => {
    event.method = "POST"
    event.url = `https://api.mch.weixin.qq.com/v3/payscore/serviceorder/${event.out_order_no}/sync`
    event.body = {
      appid: config.appid,
      service_id: serviceId,
      type: event.type,
      detail: {
        paid_time: event.paid_time
      }
    }
    let auth = getAuthorization(event)
    let result = await rp({
      url: event.url,
      method: event.method,
      json: true,
      headers: {
        "Content-Type": "application/json",
        "Accept": "application/json",
        "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 9_3_5 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13G36",
        "Authorization": auth
      },
      body: event.body
    })
    ctx.body = result
  })
  app.router('ZFFOrderPay', async(ctx) => {
    event.method = "POST"
    event.url = `https://api.mch.weixin.qq.com/v3/payscore/serviceorder/${event.out_order_no}/pay`
    event.body = {
      appid: config.appid,
      service_id: serviceId
    }
    let auth = getAuthorization(event)
    let result = await rp({
      url: event.url,
      method: event.method,
      json: true,
      headers: {
        "Content-Type": "application/json",
        "Accept": "application/json",
        "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 9_3_5 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13G36",
        "Authorization": auth
      },
      body: event.body
    })
    ctx.body = result
  })
  
  return app.serve();

}

function getExtraData(package, out_order_no) {
  var now = Date.now();
  var timeStamp = (Math.round(now / 1000)).toString();
  var nonceStr = now.toString();
  var str = `mch_id=${mchid}&nonce_str=${nonceStr}&package=${package}&sign_type=HMAC-SHA256×tamp=${timeStamp}&key=${apiKey}`
  var sign = crypto.createHmac("sha256", apiKey).update(str).digest("hex").toUpperCase()

  return {
    mchid: mchid,
    package: package,
    timeStamp: timeStamp,
    nonceStr: nonceStr,
    signType: "HMAC-SHA256",
    sign: sign,
    out_order_no: out_order_no
  }
}

function getAuthorization(event) {
  let method = event.method
  let relativePath = event.url.replace("https://api.mch.weixin.qq.com", "")
  let body = ""
  if (event.body) {
    body = JSON.stringify(event.body)
  }
  var now = Date.now();
  var timeStamp = Math.round(now / 1000);
  var nonceStr = now;

  let message = `${method}\n${relativePath}\n${timeStamp}\n${nonceStr}\n${body}\n`
  var privateKey = forge.pki.privateKeyFromPem(private_key);
  var sha256 = forge.md.sha256.create();
  sha256.update(forge.util.encodeUtf8(message));
  var signature = forge.util.encode64(privateKey.sign(sha256));

  console.log(`message=[${message}]`);

  var auth = `WECHATPAY2-SHA256-RSA2048 mchid="${mchid}",serial_no="${serialNo}",nonce_str="${nonceStr}",timestamp="${timeStamp}",signature="${signature}"`;

  return auth;
}
  1. 具体效果可以参考借书巴巴小程序里面,申请借阅借书驿站图书


    小程序云函数如何接入微信支付分功能?_第1张图片
    image.png

你可能感兴趣的:(小程序云函数如何接入微信支付分功能?)