微信小程序:微信支付

前提:有一個(gè)企業(yè)認(rèn)證的小程序

開通微信支付的步驟:

  1. 開通微信支付
    按頁(yè)面指引,提交營(yíng)業(yè)執(zhí)照、身份證等信息,然后等待審核通過(guò)即可。
    https://pay.weixin.qq.com/static/applyment_guide/applyment_detail_miniapp.shtml

微信掃碼開通,該微信號(hào)作為超級(jí)管理員將接收開戶信息及日常重要管理信息,并可進(jìn)行資金操作,需確定該微信號(hào)為商戶法定代表人或負(fù)責(zé)人再進(jìn)行操作。

  1. 關(guān)聯(lián)商戶號(hào)和申請(qǐng)接入微信支付
    審核通過(guò),登錄公眾平臺(tái),點(diǎn)擊“微信支付-商戶號(hào)管理”,查看相關(guān)商戶號(hào)信息,確認(rèn)授權(quán)申請(qǐng)。
    點(diǎn)擊“微信支付-接入微信支付”,申請(qǐng)接入
    https://mp.weixin.qq.com/

  2. 賬號(hào)管理-分配開發(fā)賬號(hào)(如果是超級(jí)管理員自己開放,則不需要分配???)
    https://pay.weixin.qq.com/

  3. 開發(fā)工具-云開發(fā)-設(shè)置-其他設(shè)置
    添加商戶號(hào)

  4. 微信支付平臺(tái),產(chǎn)品中心-我的產(chǎn)品,進(jìn)行確認(rèn)授權(quán)
    https://pay.weixin.qq.com

微信支付代碼實(shí)現(xiàn)-主要邏輯:

step1. 用戶點(diǎn)擊支付按鈕
step2. 小程序彈出付款二維碼
step3. 存儲(chǔ)訂單信息status=0,待支付
step4. 用戶掃碼
step5. 用戶支付
step6. 調(diào)用回調(diào)函數(shù),設(shè)置status=1,支付成功
step7. 用戶點(diǎn)擊完成
step8. 跳轉(zhuǎn)到訂單成功頁(yè)面

微信支付代碼實(shí)現(xiàn)-次要邏輯:

  1. 用戶未掃碼或掃碼后未支付,此時(shí)訂單已創(chuàng)建,可以在訂單列表頁(yè)面查看該訂單,支持再次支付,或一定時(shí)間后自動(dòng)關(guān)閉待支付的訂單
  2. 用戶支付后未點(diǎn)擊完成,那么點(diǎn)擊完成后才能處理的邏輯不會(huì)執(zhí)行,需要通過(guò)定時(shí)器觸發(fā)已支付訂單的處理邏輯

附云函數(shù)實(shí)現(xiàn)微信支付的代碼(主要邏輯):

page.js

  // 開通會(huì)員(step1. 用戶點(diǎn)擊了支付按鈕)
  onBuyMemberships: util.throttleFunc(function(e) {
    // 提示:執(zhí)行中
    wx.showLoading({
      title: '執(zhí)行中',
      mask: true,
    })
    // 定義參數(shù)
    let newDate = new Date()
    let money = parseInt(e.currentTarget.dataset.money) //* 100 // 總金額(單位:分),注意是int型
    let body = e.currentTarget.dataset.body // 商品描述
    let timeStr = util.formatTime2(newDate) // 年月日時(shí)分秒,長(zhǎng)度14位
    let nonceStr = Math.random().toString(36).substr(2,9).toUpperCase() + Math.random().toString(36).substr(2,9).toUpperCase() // 隨機(jī)字符串,長(zhǎng)度18
    let outTradeNo = timeStr + nonceStr // 商戶訂單號(hào),長(zhǎng)度32
    let spbillCreateIp = this.data.terminalIp // 終端IP
    let timestart = timeStr // 交易起始時(shí)間,長(zhǎng)度14位
    let orderInfo = {
      money: money,
      body: body,
      nonceStr: nonceStr,
      outTradeNo: outTradeNo,
      spbillCreateIp: spbillCreateIp,
      timestart: timestart,
    }
    console.log('orderInfo', orderInfo)
    // 調(diào)用微信支付云函數(shù)下單
    this.placeAnOrder(orderInfo)
  }, 3000), // 節(jié)流,3秒內(nèi)重復(fù)點(diǎn)擊無(wú)效
  
  // 調(diào)用微信支付云函數(shù)下單
  placeAnOrder(orderInfo) {
    var that = this
    wx.cloud.callFunction({
      name: 'wechatcloudpay',
      data: {
        action: 'placeAnOrder',
        orderInfo: orderInfo,
      },
      success: res => {
        console.warn('[云函數(shù)] [wechatcloudpay] placeAnOrder 調(diào)用成功:', res)
        let returnCode = res.result.returnCode // 通信標(biāo)識(shí)
        if(returnCode == 'SUCCESS') {
          let resultCode = res.result.resultCode // 是否成功
          console.log('resultCode', resultCode)
          if(resultCode == 'SUCCESS') {
            const payment = res.result.payment
            // 喚起二維碼支付頁(yè)面(發(fā)起微信支付)
            wx.requestPayment({
              ...payment,
              success (res) {
                // 用戶點(diǎn)擊了支付成功界面中的“完成”按鈕,才會(huì)執(zhí)行下面的代碼
                console.log('支付成功', res)
                // 跳轉(zhuǎn)到訂單成功頁(yè)面
              },
              fail (err) {
                // 用戶掃碼后點(diǎn)擊了左上角“x”關(guān)閉支付,則會(huì)執(zhí)行下面的代碼
                console.error('支付失敗', err)
                // 跳轉(zhuǎn)到訂單失敗頁(yè)面
              }
            })
          }
        }else {
          /**
           * returnMsg:
           * --參數(shù)格式校驗(yàn)錯(cuò)誤,沒有將'總金額'轉(zhuǎn)為int型
           * --受理關(guān)系不存在,沒有在'微信支付商家助手'的'模板消息'中確認(rèn)
           */
          let returnMsg = res.result.returnMsg
          wx.showToast({
            icon: 'none',
            title: returnMsg,
            duration: 3000,
          })
        }
      },
      fail: err => {
        console.error('[云函數(shù)] [wechatcloudpay] placeAnOrder 調(diào)用失敗:', err)
      },
      complete: res => {
        // 隱藏提示:執(zhí)行中
        wx.hideLoading({
          success: (res) => {},
        })
      }
    })
  },
  
  // 獲取終端ip
  getTerminalIp() {
    var that = this
    let url = 'https://pv.sohu.com/cityjson?ie=utf-8'
    let terminalIp = '127.0.0.1'
    wx.request({
      url: url,
      success(res) {
        // console.log('res', res)
        let start = res.data.indexOf('{')
        let stop = res.data.lastIndexOf('}') + 1
        let cityjson = res.data.substring(start, stop) // {"cip": "49.67.182.147", "cid": "320000", "cname": "江蘇省"}
        if(res.errMsg == "request:ok") {
          cityjson = JSON.parse(cityjson)
          terminalIp = cityjson.cip
        }
      },
      complete() {
        that.setData({
          terminalIp: terminalIp
        })
      }
    })
  },

  /**
   * 生命周期函數(shù)--監(jiān)聽頁(yè)面加載
   */
  onLoad: function (options) {
    // 設(shè)置導(dǎo)航欄背景色
    wx.setNavigationBarColor({
      backgroundColor: '#4752A4',
      frontColor: '#ffffff',
    })
    // 獲取本地用戶信息
    this.getLocalUserInfo() 
    // 獲取終端ip
    this.getTerminalIp()
  },

云函數(shù)實(shí)現(xiàn)微信支付

// 云函數(shù)入口函數(shù)
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  // console.log('event', event)
  
  switch (event.action) {
    // 下單
    case 'placeAnOrder': {
      return placeAnOrder(event, wxContext)
    }
  }

  // 下單
  async function placeAnOrder(event, wxContext) {
    try {  
      // 生成支付交易單,小程序云函數(shù)調(diào)用免填屬性:mch_id、appid、sign、sign_type
      const res = await cloud.cloudPay.unifiedOrder({
        "body" : event.orderInfo.body, // 商品描述 String(128)
        "nonceStr": event.orderInfo.nonceStr, // 隨機(jī)字符串 String(32)
        "outTradeNo" : event.orderInfo.outTradeNo, // 商戶訂單號(hào) String(32)
        "spbillCreateIp" : event.orderInfo.spbillCreateIp, // 終端IP String(64)
        "subMchId" : mchId, // 子商戶號(hào) String(32)
        "totalFee" : event.orderInfo.money, // 總金額 Int
        "tradeType": 'JSAPI', // String(16) 小程序取值如下:JSAPI
        "openid": wxContext.OPENID, // 用戶標(biāo)識(shí), trade_type=JSAPI,此參數(shù)必傳,用戶在商戶appid下的唯一標(biāo)識(shí)
        "subOpenid": wxContext.OPENID, // 用戶子標(biāo)識(shí),trade_type=JSAPI,此參數(shù)必傳,用戶在子商戶appid下的唯一標(biāo)識(shí)
        "timeStart": event.orderInfo.timeStart, // 交易起始時(shí)間 String(14),訂單生成時(shí)間,格式為yyyyMMddHHmmss
        "envId": envId, // envId 和 functionName 用來(lái)設(shè)置接收支付后的異步通知回調(diào)的云函數(shù)
        "functionName": "wechatcloudpaycallback", // 用戶支付成功就會(huì)調(diào)用該回調(diào)函數(shù)(不需要點(diǎn)擊支付成功頁(yè)面的完成按鈕)
      })
      // 記錄預(yù)支付交易單信息
      db.collection('orderInfo').add({
        data: {
          _openid: wxContext.OPENID,
          outTradeNo: event.orderInfo.outTradeNo, // 訂單號(hào)
          totalFee: event.orderInfo.money, // 總金額
          orderInfo: event.orderInfo, // 訂單信息
          result: res, // 生成交易訂單的返回結(jié)果
          status: 0,
          createTime: Date.now()
        }
      })
      // 返回
      return res
    } catch (e) {
      console.error(e)
    }
  }
}

云函數(shù)實(shí)現(xiàn)的回調(diào)函數(shù)

// 云函數(shù)入口函數(shù)
exports.main = async (event, context) => {
  try {
    console.log('event', event)
    const wxContext = cloud.getWXContext()
    let resultCode = event.resultCode
    let transactionId = event.transactionId
    let outTradeNo = event.outTradeNo
    let status = resultCode === 'SUCCESS' ? 1 : -1 // 0:新建訂單,1:支付成功,-1:支付失敗
    const res = await db.collection('orderInfo').where({
      outTradeNo: outTradeNo
    })
    .update({
      data: {
        status: status, // 更新狀態(tài)
        event: event,
        transactionId: transactionId,
        updateTime: Date.now(),
      }
    })
    return {
      errcode: 0, // 注意:一定要返回errcode,否則回調(diào)函數(shù)會(huì)多次調(diào)用
      msg: 'wechatcloudpaycallback:ok',
    }
  } catch (e) {
    console.error(e)
  }
}

注意點(diǎn):

  1. 總金額的單位是分,總金額只能是int型,字符串型的話會(huì)報(bào)錯(cuò):參數(shù)格式校驗(yàn)錯(cuò)誤
  2. 回調(diào)函數(shù)最后要返回{errcode:0},否則會(huì)重復(fù)調(diào)用回調(diào)函數(shù)

微信官網(wǎng)文檔及視頻
https://developers.weixin.qq.com/miniprogram/dev/wxcloud/guide/wechatpay/wechatpay.html
https://developers.weixin.qq.com/community/business/doc/000c82ce840420b2483b556f25e40d

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容