微信小程式 使用雲開發完成支付閉環

2022-01-11 21:35:34 字數 2777 閱讀 9594

優化版支付流程

1.流程介紹

2. **實現和邏輯思想描述

雲函式統一下單 對應雲函式unipay

【cloudpay.unifiedorder】

函式思路: 呼叫雲函式封裝功能,用時間戳生成對應訂單號,進行統一下單處理,如果兩個返回結果都是success,那麼將該訂單記錄寫入資料庫,狀態設定為waiting

body填寫商戶名稱

submchid填寫商戶id,在雲函式環境管理後台獲取

const cloud = require('wx-server-sdk')

cloud.init()

const db = cloud.database();

const _ = db.command;

exports.main = async (event, context) => )

res.outtradeno = tradeno

res.totalfee = fee

//在此處寫入訂單表

paydata.paytimestamp = res.payment.timestamp;

paydata.orderid = res.outtradeno;//訂單號

paydata.paystatus = 'waiting'

paydata.orderamount = fee

paydata.paytime = timecode()

paydata.mchid = res.submchid

if(res.returncode=='success' && res.resultcode=='success'))

} return res

}function gettradeno()

outtradeno = "lhzhwy" + new date().gettime() + outtradeno; //時間戳,用來生成訂單號。

return outtradeno;

}function timecode()

function timecodeymd()

function formatnumber(n)

fee 需要根據訂單計算 fee單位為0.01paydata是商品訂單引數,形式為object,可存放顧客手機號,支付總金額,支付哪一項費用等資訊

timerquery是定時器,查詢支付結果

let fee = 1

//該費用只是代指,以實際開發為準

wx.cloud.callfunction(,

success: res => ,

fail(res) )}})

},fail: r => )

}})

**函式unipaynotify【cloud.paymentcallback】

訂單在支付成功時會觸發該**函式

該**函式必須有返回值,且必須是固定格式

根據**函式攜帶的訂單號,修改對應訂單號的waiting狀態為success,並且返回對應格式的返回資訊

欄位名變數名

必填型別

描述錯誤碼

errcode

是number

0錯誤資訊

errmsg

是string

**函式攜帶引數如下

}

const cloud = require('wx-server-sdk')

cloud.init()

const db = cloud.database();

const _ = db.command;

// 雲函式入口函式

exports.main = async (event, context) => ).update(

})console.log(res)

} catch (error)

} return

}

定時查詢器,查詢結果timerquery

沒間隔一秒查詢一次,查詢到該訂單記錄為success清除定時觸發器,並展示成功資訊

可以使用遞迴疊加器,計算請求次數,到幾次就終止,可自行完成

timerquery(tradeno, paydata) ).get()

clearinterval(that.data.setinter)}}

})}, 1000);

}

參考 - 我的未開源專案

寫文不易,求個關注

小程式微信支付

weixinpay new weixinpay openid,orderid.res2,訂單支付 res3 goods name total price 100,tsd res2 ret weixinpay pay class weixinpay public function pay 統一下單介面...

微信小程式支付

class wxpay protected mch id protected key protected openid protected out trade no protected body protected total fee protected notifyurl protected un...

微信小程式開發之微信支付(三)微信下單

在發起支付之前,後台會生成商戶訂單,呼叫統一下單api,得到預支付資訊。我是使用的是這個sdk com.github.binarywang.wxpay.bean.notify.wxpayordernotifyresult 統一下單返回結果類 com.github.binarywang.wxpay.b...