当前位置:网站首页>Realize applet payment function with applet cloud development (including source code)
Realize applet payment function with applet cloud development (including source code)
2022-07-06 14:22:00 【Programming pebbles】
When we do the development of small program payment , There are always these problems . When the applet calls wechat payment , You must have your own server , Have your own domain name for filing , Have their own background development . This leads to a great cost when we do small program payment . This section will teach you how to use applet cloud development to realize the development of applet payment function . Don't build your own server , Don't have your own filing domain name . Simply use the applet cloud development .
The old rule is to see the effect picture first :

Knowledge points in this section
1, Deployment and use of cloud development
2, Payment related cloud function development
3, List of goods
4, Order list
5, Wechat payment and successful callback of payment
The function of sending push messages to users after successful payment will be explained later .
Let's teach you how to use the applet payment function with the help of cloud development .
Configuration information required for payment
1, Applet appid
2, Cloud development environment id
3, Wechat merchant No
4, Merchant key
One , preparation
1, Has applied for an applet , Get the applet AppID and Secret stay Applet tube 理 backstage in ,【 Set up 】 →【 Development and setup 】 You can get wechat applet AppID and Secret.

2, Wechat payment merchant number , Obtain the merchant number and merchant key in wechat payment merchant management 理 In the platform ,【 Account center 】→【 Merchant information 】 You can get the wechat payment merchant number .

stay 【 Account center 】 ‒> 【API Security 】 You can set merchant key .

Here's a special note , There is no way for personal applets to use wechat to pay . So if you want to use wechat payment function , Must be a non personal account number ( Of course, individuals can apply for a self-employed business license to register non personal applet accounts )
3, Wechat developers IDE https://developers.weixin.qq.com/miniprogram/dev/devtools/download.html
4, Open the applet cloud development function :javascript:void(0)
Two , Implementation of product list
The renderings are as follows , Since this section focuses on the realization of payment , So here's just the key code .

wxml The layout is as follows :
<view class="container">
<view class="good-item" wx:for="{{goods}}" wx:key="*this" ontap="getDetail" data-goodid="{{item._id}}">
<view class="good-image">
<image src="{{pic}}"></image>
</view>
<view class="good-detail">
<view class="title"> goods : {{item.name}}</view>
<view class="content"> Price : {{item.price / 100}} element </view>
<button
class="button"
type="primary"
bindtap="makeOrder"
data-goodid="{{item._id}}"
> Place an order </button>
</view>
</view>
</view>
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
All we need to do is get the commodity information in the cloud database with the help of cloud development , Then show it to the product list , About cloud development, get the product list and display it. This section does not explain ( Interested students can read my history blog , Have you written )

3、 ... and , Creation of payment cloud function
First, let's take a look at what our payment cloud functions contain

Simply explain the use of each
config Under the index.js It is used for payment configuration , It mainly configures account information related to payment
lib It's a third-party payment bank , There is no explanation here .
The focus is on cloud function entry index.js
Let's teach you how to configure
1, To configure config Under the index.js,
All you need to do in this step is put the applet appid, Cloud development environment ID, Merchant id, Merchant key . Fill in .

2, Configure the entry cloud function

The detailed code is as follows , The comments in the code are very clear , There will be no separate explanation here :
const cloud = require('wx-server-sdk')
cloud.init()
const app = require('tcb-admin-node');
const pay = require('./lib/pay');
const {
mpAppId,
KEY
} = require('./config/index');
const {
WXPayConstants,
WXPayUtil
} = require('wx-js-utils');
const Res = require('./lib/res');
const ip = require('ip');
/**
*
* @param {obj} event
* @param {string} event.type Function type
* @param {} userInfo.openId User openid
*/
exports.main = async function(event, context) {
const {
type,
data,
userInfo
} = event;
const wxContext = cloud.getWXContext()
const openid = userInfo.openId;
app.init();
const db = app.database();
const goodCollection = db.collection('goods');
const orderCollection = db.collection('order');
// Of the order document status 0 Did not pay 1 Paid 2 closed
switch (type) {
// [ Place... Here unifiedorder Related code ]
case 'unifiedorder':
{
// Query the product ID Whether it exists in the database , And extract the data
const goodId = data.goodId
let goods = await goodCollection.doc(goodId).get();
if (!goods.data.length) {
return new Res({
code: 1,
message: ' Product not found '
});
}
// Extract data from cloud functions , Include the name 、 The price is more reasonable and safe ,
// Because the commodity data transmitted from the end is unreliable
let good = goods.data[0];
// Pieced together the parameters of wechat payment unified order
const curTime = Date.now();
const tradeNo = `${goodId}-${curTime}`;
const body = good.name;
const spbill_create_ip = ip.address() || '127.0.0.1';
// The cloud function will not pay http trigger , So here's the callback notify_url You can just fill in .
const notify_url = 'http://www.qq.com'; //'127.0.0.1';
const total_fee = good.price;
const time_stamp = '' + Math.ceil(Date.now() / 1000);
const out_trade_no = `${tradeNo}`;
const sign_type = WXPayConstants.SIGN_TYPE_MD5;
let orderParam = {
body,
spbill_create_ip,
notify_url,
out_trade_no,
total_fee,
openid,
trade_type: 'JSAPI',
timeStamp: time_stamp,
};
// call wx-js-utils Unified ordering method in
const {
return_code,
...restData
} = await pay.unifiedOrder(orderParam);
let order_id = null;
if (return_code === 'SUCCESS' && restData.result_code === 'SUCCESS') {
const {
prepay_id,
nonce_str
} = restData;
// Wechat applet payment should be signed separately , And back to the applet side
const sign = WXPayUtil.generateSignature({
appId: mpAppId,
nonceStr: nonce_str,
package: `prepay_id=${prepay_id}`,
signType: 'MD5',
timeStamp: time_stamp
}, KEY);
let orderData = {
out_trade_no,
time_stamp,
nonce_str,
sign,
sign_type,
body,
total_fee,
prepay_id,
sign,
status: 0, // Of the order document status 0 Did not pay 1 Paid 2 closed
_openid: openid,
};
let order = await orderCollection.add(orderData);
order_id = order.id;
}
return new Res({
code: return_code === 'SUCCESS' ? 0 : 1,
data: {
out_trade_no,
time_stamp,
order_id,
...restData
}
});
}
// [ Place... Here payorder Related code ]
case 'payorder':
{
// Relevant orders come out of the end. I believe
const {
out_trade_no,
prepay_id,
body,
total_fee
} = data;
// Check the wechat payment side to see if the order exists , And query the order status , See if the payment has been successful .
const {
return_code,
...restData
} = await pay.orderQuery({
out_trade_no
});
// If the order exists and payment is successful , Then start processing payment
if (restData.trade_state === 'SUCCESS') {
let result = await orderCollection
.where({
out_trade_no
})
.update({
status: 1,
trade_state: restData.trade_state,
trade_state_desc: restData.trade_state_desc
});
let curDate = new Date();
let time = `${curDate.getFullYear()}-${curDate.getMonth() +
1}-${curDate.getDate()} ${curDate.getHours()}:${curDate.getMinutes()}:${curDate.getSeconds()}`;
}
return new Res({
code: return_code === 'SUCCESS' ? 0 : 1,
data: restData
});
}
case 'orderquery':
{
const {
transaction_id,
out_trade_no
} = data;
// Query order
const {
data: dbData
} = await orderCollection
.where({
out_trade_no
})
.get();
const {
return_code,
...restData
} = await pay.orderQuery({
transaction_id,
out_trade_no
});
return new Res({
code: return_code === 'SUCCESS' ? 0 : 1,
data: { ...restData,
...dbData[0]
}
});
}
case 'closeorder':
{
// Close order
const {
out_trade_no
} = data;
const {
return_code,
...restData
} = await pay.closeOrder({
out_trade_no
});
if (return_code === 'SUCCESS' &&
restData.result_code === 'SUCCESS') {
await orderCollection
.where({
out_trade_no
})
.update({
status: 2,
trade_state: 'CLOSED',
trade_state_desc: ' Order closed '
});
}
return new Res({
code: return_code === 'SUCCESS' ? 0 : 1,
data: restData
});
}
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
- 59.
- 60.
- 61.
- 62.
- 63.
- 64.
- 65.
- 66.
- 67.
- 68.
- 69.
- 70.
- 71.
- 72.
- 73.
- 74.
- 75.
- 76.
- 77.
- 78.
- 79.
- 80.
- 81.
- 82.
- 83.
- 84.
- 85.
- 86.
- 87.
- 88.
- 89.
- 90.
- 91.
- 92.
- 93.
- 94.
- 95.
- 96.
- 97.
- 98.
- 99.
- 100.
- 101.
- 102.
- 103.
- 104.
- 105.
- 106.
- 107.
- 108.
- 109.
- 110.
- 111.
- 112.
- 113.
- 114.
- 115.
- 116.
- 117.
- 118.
- 119.
- 120.
- 121.
- 122.
- 123.
- 124.
- 125.
- 126.
- 127.
- 128.
- 129.
- 130.
- 131.
- 132.
- 133.
- 134.
- 135.
- 136.
- 137.
- 138.
- 139.
- 140.
- 141.
- 142.
- 143.
- 144.
- 145.
- 146.
- 147.
- 148.
- 149.
- 150.
- 151.
- 152.
- 153.
- 154.
- 155.
- 156.
- 157.
- 158.
- 159.
- 160.
- 161.
- 162.
- 163.
- 164.
- 165.
- 166.
- 167.
- 168.
- 169.
- 170.
- 171.
- 172.
- 173.
- 174.
- 175.
- 176.
- 177.
- 178.
- 179.
- 180.
- 181.
- 182.
- 183.
- 184.
- 185.
- 186.
- 187.
- 188.
- 189.
- 190.
- 191.
- 192.
- 193.
- 194.
- 195.
- 196.
- 197.
- 198.
- 199.
- 200.
- 201.
- 202.
- 203.
- 204.
- 205.
- 206.
- 207.
- 208.
- 209.
- 210.
- 211.
- 212.
- 213.
- 214.
- 215.
- 216.
- 217.
- 218.
- 219.
- 220.
- 221.
- 222.
- 223.
- 224.
- 225.
- 226.
- 227.
- 228.
- 229.
- 230.
- 231.
- 232.
- 233.
- 234.
- 235.
- 236.
- 237.
- 238.
- 239.
- 240.
In fact, the key functions of our payment are in the above codes .

And then look at , Screenshot of relevant payment process

The above figure relates to our order list , Payment status , Callback after successful payment .
Let's talk about it today , We will continue to explain other functions of payment . For example, message push after successful payment , It can also be realized with the help of cloud development .
Because the source code involves some private information , There is no separate link to download the source code , If you are interested , You can write to me , Or leave a message at the bottom . It's OK to ask me for the source code alone
边栏推荐
- How to understand the difference between technical thinking and business thinking in Bi?
- Xray and burp linkage mining
- Which is more advantageous in short-term or long-term spot gold investment?
- Record an API interface SQL injection practice
- 实验四 数组
- Meituan dynamic thread pool practice ideas, open source
- 7-4 hash table search (PTA program design)
- Experiment 7 use of common classes
- 【VMware异常问题】问题分析&解决办法
- Low income from doing we media? 90% of people make mistakes in these three points
猜你喜欢

Middleware vulnerability recurrence Apache

链队实现(C语言)

Hackmyvm target series (5) -warez

Canvas foundation 1 - draw a straight line (easy to understand)

强化学习基础记录

Wei Shen of Peking University revealed the current situation: his class is not very good, and there are only 5 or 6 middle-term students left after leaving class

强化學習基礎記錄

Captcha killer verification code identification plug-in

记一次api接口SQL注入实战

Xray and burp linkage mining
随机推荐
On the idea of vulnerability discovery
Simply understand the promise of ES6
【VMware异常问题】问题分析&解决办法
内网渗透之内网信息收集(四)
[three paradigms of database] you can understand it at a glance
Intranet information collection of Intranet penetration (2)
Network technology related topics
7-1 output all primes between 2 and n (PTA programming)
Sqqyw (indifferent dot icon system) vulnerability recurrence and 74cms vulnerability recurrence
SQL注入
MSF generate payload Encyclopedia
[data processing of numpy and pytoch]
XSS之冷门事件
Captcha killer verification code identification plug-in
Hackmyvm target series (4) -vulny
Hackmyvm target series (7) -tron
记一次api接口SQL注入实战
Xray and burp linkage mining
强化學習基礎記錄
力扣152题乘数最大子数组