云函数支付以及支付回调

在cloud中 新建一个云函数payTY

// 云函数代码
const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

exports.main = async (event, context) => {
  
  const wxContext = cloud.getWXContext()
  console.log(event)
  const res = await cloud.cloudPay.unifiedOrder({
    "body" : "随便说点啥", // 支付内容描述,这里是在微信支付成功的回执上面显示的
    "outTradeNo" : event.orderid, //支付订单号
    "spbillCreateIp" : "127.0.0.1",
    "subMchId" : "12345678", // 商户号
    "totalFee" : event.money, // 订单总金额
    "envId": "test-12345", // 回调函数所处云开发环境ID,注意这两个参数即为支付结果回调的传入参数
    "functionName": "payBack", // 回调函数名,注意这两个参数即为支付结果回调的传入参数
    "tradeType": 'JSAPI', // 交易类型
    "nonceStr": Math.random().toString(36).substr(2) + '', // 随机字符串,不长于32位
    "openid": wxContext.OPENID
  })
  console.log('payTY')
  console.log(res)
  return res
}

新建另一个云函数payBack 是用户支付完成的回调函数 (不需点击支付成功显示的完成按钮)

    // 云函数入口文件
    const cloud = require('wx-server-sdk')

    cloud.init({
      env: cloud.DYNAMIC_CURRENT_ENV
    })

    // 云函数入口函数
    exports.main = async (event, context) => {
      const orderId = event.outTradeNo; // 订单号
      const returnCode = event.returnCode; // 是否支付成功
      const resultCode = event.resultCode ; // 是否支付成功
      const openId = event.userInfo.openId; // 当前购买者的openid

      if (returnCode == 'SUCCESS' && resultCode == 'SUCCESS'  ) {
        const db = cloud.database();
        // 注意:两者都为SUCCESS,支付才算正真成功

        let order = await db.collection("myOrder").where({
          _openid: openId,
          orderid: orderId,
        }).get()
        
        console.log(order.data[0].status)
        let thisStatus = order.data[0].status
        if (thisStatus == 1) {
          console.log('111111111')
          return {
            errcode: 0,
            errmsg: 'SUCCESS',
            status: '1'
          }
        } else if (thisStatus == 0) {
          console.log('0000000000000')
          // 更新状态  根据当前购买者的openid 跟订单号查询是否有数据 并更新是否已经支付的状态
          let updataO = await db.collection('myOrder').where({
            _openid: openId,
            orderid: orderId,
          }).update({
            data: {
              status: 1
            }
          })
          console.log(updataO)

          // 如果更新成功
          if (updataO.stats.updated == 1) {
            return {
              errcode: 0,
              errmsg: 'SUCCESS',
              status: '2.1'
            }
          } else {
            // 向数据库添加错误处理订单
            let addFail = await db.collection('failOrder').add({
              data: {
                openId: openId,
                orderid: orderId,
                remark: 'status订单支付状态更新失败,添加一条容错'
              }
            });
            console.log(addFail)

            return {
              errcode: 1,
              errmsg: 'FAIL',
              status: '2.2'
            }
          }
        } else {
          console.log("nononononono")  
          console.log('没查到')
          return {
            errcode: 1,
            errmsg: 'FAIL',
            status: '3'
          }
        }
      } else {
        // 记录错误信息
        conslog.log('支付出错:', event)
        return {
          errcode: 1,
          errmsg: 'FAIL',
          status: '4'
        }
      }
    }

小程序下单页面中调用云函数的方法

      let orderid = Date.now() + ''; // 时间戳 做订单号
      // 调用云函数的支付
      wx.cloud.callFunction({
        name: 'payTY', // 小程序统一下单
        data: {
          orderid: orderid,
          money: parseInt(parseFloat(that.data.totalPrice) * 100), // 订单金额 转换为分
        },
        success: async res => {
         //  that.successCB(orderid);
          const payment = res.result.payment
          wx.requestPayment({
            ...payment,
            success(res) {
               wx.showToast({
                 title: '亲,坐等收货吧!',
                 icon: 'success',
                 duration: 2000
               })
            },
            fail(res) {
              wx.showToast({
                title: '支付失败',
                icon: 'none',
                duration: 2000
              })
            }
          })
        },
        fail(res) {
         console.log(res)
        },
      })
    }

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值