微信小程序云开发使用云函数调用服务端链接生成获取用户token
生活随笔
收集整理的這篇文章主要介紹了
微信小程序云开发使用云函数调用服务端链接生成获取用户token
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
需求目標:
微信小程序云開發(fā)使用云函數(shù)寫后端接口獲取微信用戶token。
安裝相關(guān)文件:參考這位老哥的博客https://blog.csdn.net/u013184970/article/details/105709259/
1.首先在相關(guān)云函數(shù)安裝request請求
npm install --save request
2.安裝request-promise環(huán)境
npm install --save request-promise
實現(xiàn):
1.云函數(shù)代碼:
// 云函數(shù)入口文件 const cloud = require('wx-server-sdk') var request = require('request-promise');cloud.init()// 云函數(shù)入口函數(shù) exports.main = async (event, context) => {const wxContext = cloud.getWXContext()const appid = wxContext.APPID //獲取appidconst secret = 'a52cd53dc6d*********' //小程序的密鑰,微信公眾平臺生成const AccessToken_options = {method: 'GET',url: 'https://api.weixin.qq.com/cgi-bin/token',//微信小程序服務端提供的鏈接qs:{appid:wxContext.APPID,secret:secret,grant_type:'client_credential'},json: true}//獲取AccessTokenconst resultValue = await request(AccessToken_options);const token = resultValue.access_token;return {resultValue,token} }代碼圖:
2. 頁面js文件
bindGetUserInfo:async ()=>{//獲取用戶信息let res = ''try{res = await wx.getUserProfile({lang: "zh_CN", desc: '用于登錄'})} catch (e) {wx.showToast({title: '獲取用戶信息失敗', icon: "none", duration: 1500})return}wx.showLoading({title: '正在登錄'})let data = '' //返回是否成功的標志//獲取登錄信息const r = await wx.login({})if (!r) { //如果為空表明獲取失敗wx.showToast({title: '登錄失敗,請重新登錄', icon: "none", duration: 1500})wx.hideLoading()return}const code = r.code;if(res.rawData && res.signature){let params = {raw_data: res.rawData,signature: res.signature,code: code}//調(diào)用云函數(shù)wx.cloud.callFunction({name:'getUserInfoToken' //云函數(shù)名稱}).then(res=>{console.log("res5555")console.log(res)}).catch(res=>{console.log("res55888")console.log(res)})wx.hideLoading()},效果圖:
有小伙伴有新想法或者建議,歡迎留言,共同進步!感謝樓上那個老哥提供的安裝request方法!
總結(jié)
以上是生活随笔為你收集整理的微信小程序云开发使用云函数调用服务端链接生成获取用户token的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PCB板铜箔载流量厚度的计算方法
- 下一篇: 七、python接口开发(二)