属于入门内容,大佬可直接忽略!!
写在开头
自从微信云开发涨价以后,大家都是怨声载道,纯纯的割韭菜。这时发现了好用且更便宜的Laf云开发,于是如何将Laf云开发作为自己的小程序后端,就成了新手的难题了,本帖纯入门内容,有不懂的可以跟帖哦~
1、申请测试用小程序
申请地址:https://mp.weixin.qq.com/wxamp/sandbox?doc=1
2、获取小程序Appid 和 Secret
https://mp.weixin.qq.com/ 扫码登录后选择刚申请的测试小程序,即可显示测试号的Appid 和 AppSecret
[upl-image-preview url=https://forum.laf.run/assets/files/2023-03-27/1679925572-532124-image.png]
3、新建小程序
微信开发工具创建小程序
[upl-image-preview url=https://forum.laf.run/assets/files/2023-03-27/1679925722-722309-image.png]
4、新建一个登录用的Laf云函数
命名为:wxLogin
代码如下:
import cloud from '@lafjs/cloud'
const appid = "你的小程序的Appid" // 微信小程序 AppId
const appsecret = "你的小程序的AppSecret" // 微信小程序 AppSecret
export async function main(ctx: FunctionContext) {
const code = ctx.query.code
const openid = await getOpenId(code)
return { openid: openid }
}
/**
* 获取 openid
* @param {string} code Then auth code
* @return {Promise<string>}
*/
async function getOpenId(code) {
const api_url = `https://api.weixin.qq.com/sns/jscode2session`
const param = `appid=${appid}&secret=${appsecret}&js_code=${code}&grant_type=authorization_code`
console.log('request url: ', `${api_url}?${param}`)
const res = await cloud.fetch(`${api_url}?${param}`)
console.log(res.data)
if (res.data.errcode > 0) {
return null
}
return res?.data?.openid
}
5、修改小程序代码并设置不校验合法域名
[upl-image-preview url=https://forum.laf.run/assets/files/2023-03-27/1679926258-10057-image.png]
找到截图的代码位置
加入代码:
// 登录
wx.login({
success: res => {
// 发送 res.code 到后台换取 openId, sessionKey, unionId
if (res.code) {
//发起网络请求
wx.request({
url: 'https://<你的应用Appid>.laf.dev/wxLogin',
data: {
code: res.code
},
success(res){
console.log("登录成功,登录用户的openid为:",res.data)
}
})
} else {
console.log('登录失败!' + res.errMsg)
}
}
})
[upl-image-preview url=https://forum.laf.run/assets/files/2023-03-27/1679926570-929028-image.png]
正式上线的小程序需要设置域名白名单,由于这里只是测试开发使用,直接勾选不校验合法域名即可
[upl-image-preview url=https://forum.laf.run/assets/files/2023-03-27/1679927738-772881-image.png]
6、编译小程序并测试
[upl-image-preview url=https://forum.laf.run/assets/files/2023-03-27/1679927413-613407-image.png]
至此,一个对接Laf登录的小程序就写完了,并成功获取到了用户的openid