主题
常见业务场景
小程序登录
- 执行
uni.login,返回 code - 请求后端提供的 “微信一键登录” 接口,将 code 传给后端。
- 如果已注册,返回用户信息和 token。
- 如果未注册,调用
uni.getUserProfile获取用户信息,调用后端提供的 “微信注册” 接口,传入用户信息和 code,完成注册,返回用户信息和 token。
js
// 推荐的完整流程
async function wxLogin() {
// 1. 获取登录凭证 code
const { code } = await uni.login({ provider: 'weixin' })
// 2. 将 code 发送给后端
const res = await request('/api/wechat/login', { code })
if (res.isRegistered) {
// 已注册
// 3. 直接返回 token 和用户信息
uni.setStorageSync('token', res.token)
uni.setStorageSync('userInfo', res.userInfo)
} else {
// 未注册
// 3. 获取用户信息
const userProfile = await uni.getUserProfile()
// 4. 将 code 和用户信息发送给后端完成注册
const registerRes = await request('/api/wechat/register', {
code,
userInfo: userProfile,
})
uni.setStorageSync('token', registerRes.token)
uni.setStorageSync('userInfo', registerRes.userInfo)
}
}小程序支付
- 用户点击“立即下单”,调用后端接口接口,传递一系列需要的参数,然后返回 小程序支付参数。
- 调用
uni.requestPayment,传入小程序支付参数,调起微信支付。
小程序分享
在小程序中,“分享”属于生命周期
js
export default {
// 用户点击右上角分享
onShareAppMessage() {
return {
title: '分享标题',
imageUrl: '/static/share-image.png',
path: '/pages/index/index?id=123',
}
},
// 用户点击右上角分享到朋友圈
onShareTimeline() {
return {
title: '分享标题',
imageUrl: '/static/share-image.png',
query: 'id=123',
}
},
}如果想通过自定义按钮进行分享,需要给按钮添加 open-type="share" 属性:
html
<button open-type="share">分享</button>