小程序·云调用(微信支付)

本文来自哔哩哔哩视频学习所得:

微信支付·交互流程图

congig0.png

微信支付接入·前准备工作

config1.png

老版本微信签名支付

pay0.png

pay1.png

小程序·云函数实现

// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const mch_id = "商户号";
const envId = "云环境ID";
const db = cloud.database();

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let openid = wxContext.OPENID;
  let {
    totalFee
  } = event;
  let body = "商品描述";
  let nonceStr = Math.random().toString(36).substr(2, 13); // 32位随机字符串,此处是11位
  let timeStamp = parseInt(Date.now() / 1000);
  let outTradeNo = 'cloud' + timeStamp + nonceStr; // 商户订单号,32位以内的唯一字符串,此处是25位
  let tradetype = 'JSAPI'; // 交易类型,小程序:JSAPI

  // 生成预支付交易单
  const result = await cloud.cloudPay.unifiedOrder({
    body,
    nonceStr,
    tradetype,
    outTradeNo,
    spbillCreateIp: '127.0.0.1', // 调用微信支付的机器Ip
    subMchId: mch_id,
    totalFee, // 订单金额,单位(分)。必须是整数
    envId: envId,
    functionName: 'wxPayCallback' // 接收微信支付异步回调的云函数名
  })

  // 记录交易订单信息
  db.collection('order').add({
    data: {
      _openid: openid,
      body,
      outTradeNo,
      totalFee,
      status: 0,
      createTime: Date.now()
    }
  });


  return result;
}

支付回调云函数

// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const envId = "云环境id";
const db = cloud.database();

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  // resultCode:SUCCESS/FALL      teansactionId:微信订单号
  let {
    resultCode,
    outTradeNo,
    teansactionId
  } = event;

  let status = resultCode === 'SUCCESS' ? 1 : 2
  let params = {
    event,
    transactionId,
    status
  }
  await db.collection("order").where({
    outTradeNo: outTradeNo
  }).update({
    data: params
  });

  return {
    code: 0,
    msg: 'success'
  }
}

你可能感兴趣的:(小程序·云调用(微信支付))