前言
这里介绍微信小程序如何使用微信进行支付。并且提供前端代码以及后端代码(nodeJs)。这里后端使用nodeJs写的哈。
需要准备:
1、小程序(企业级或个体工商)的appId
2、微信支付商户的商户号,以及v2支付密钥
一、前端登录将code发送后端
提示:以下内容流程:前端进行uni.login登录,将code传给后端,后端根据code获取用户的openid
因为没有使用数据库,也没有使用Redis去缓存openid。所以这里拿到openid后,写死在config.js配置文件中
1、前端代码
<script setup>
const handleLogin = async () => {
const loginRes = await uni.login({
provider: 'weixin'}); // 获取微信登录code
// 发送code到服务器 后端通过code获取到用户openid
const res = await uni.request({
url: 'http://127.0.0.1:3030/api/login',
method: 'POST',
data: {
code: loginRes.code}
});
// 存储返回的 token
if (res.data.code === 200) {
uni.setStorageSync('token', res.data.token)
uni.showToast({
title: '登录成功',
success() {
uni.switchTab({
url:'/pages/home/home'})
}
});
}
};
</script>
2、nodeJs代码
代码示例中提到的config.js代码文件 后面会贴出来
// src/services/login.js
const axios = require('axios');
const config = require('../../config/config'); // 将配置独立出来
// 获取openid session_key
async function getOpenid(code) {
const weixinRes = await axios.get('https://api.weixin.qq.com/sns/jscode2session', {
params: {
appid: config.appId,
secret: config.appSecret,
js_code: code,
grant_type: 'authorization_code'
}
})
return weixinRes;
}
// 用 code 换取 session_key 和 openid...
module.exports = {
getOpenid };
// app.js
app.post('/api/login', async (req, res) => {
try {
const {
code } = req.body
// 1. 用 code 换取 session_key 和 openid
const weixinRes = await getOpenid(code<