微信小程序—支付功能
只提供微信小程序端代碼
var app = getApp();
Page({
data: {},
onLoad: function (options) {
// 頁面初始化 options為頁面跳轉所帶來的參數
var that = this
//登陸獲取code
wx.login({
success: function (res) {
console.log(res.code)
//獲取openid
that.getOpenId(res.code)
}
});
},
getOpenId: function (code) {
var that = this;
wx.request({
url: "https://api.weixin.qq.com/sns/jscode2session?appid=小程序appid&secret=小程序應用密鑰&js_code=" + code + "&grant_type=authorization_code",
data: {},
method: 'GET',
success: function (res) {
that.generateOrder(res.data.openid)
},
fail: function () {
// fail
},
complete: function () {
// complete
}
})
},
/**生成商戶訂單 */
generateOrder: function (openid) {
var that = this
//統一支付
wx.request({
url: '后臺路徑',
method: 'GET',
data: {
gfee: '商品價錢',
gname: '商品名稱',
openId:openid
(商品價錢和商品名稱根據自身需要是否傳值,openid為必傳)
},
success: function (res) {
var pay = res.data
//發起支付
var timeStamp = pay[0].timeStamp;
var packages = pay[0].package;
var paySign = pay[0].paySign;
var nonceStr = pay[0].nonceStr;
var param = { "timeStamp": timeStamp, "package": packages, "paySign": paySign, "signType": "MD5", "nonceStr": nonceStr };
that.pay(param)
},
})
},
/* 支付 */
pay: function (param) {
console.log("支付")
console.log(param)
wx.requestPayment({
timeStamp: param.timeStamp,
nonceStr: param.nonceStr,
package: param.package,
signType: param.signType,
paySign: param.paySign,
success: function (res) {
// success
wx.navigateBack({
delta: 1, // 回退前 delta(默認為1) 頁面
success: function (res) {
wx.showToast({
title: '支付成功',
icon: 'success',
duration: 2000
})
},
fail: function () {
// fail
},
complete: function () {
// complete
}
})
},
fail: function (res) {
// fail
},
complete: function () {
// complete
}
})
}
})