1. 程式人生 > 其它 >uniapp+nodejs實現小程式登入流程,獲取openID,附uniapp請求封裝

uniapp+nodejs實現小程式登入流程,獲取openID,附uniapp請求封裝

技術標籤:uniappnodejsvueuni-app

小程式授權,拿到code向後臺nodejs 傳送請求互動過程

前端程式碼(uniapp)

<template>
	<view class="login">
		<view v-if="isCanUse">
			<view>
				<view class="header"><image src="../../static/icon/news-active.png"></image>
</view> <view class="content"> <view>申請獲取以下許可權</view> <text>獲得你的公開資訊(暱稱,頭像、地區等)</text> </view> <button class="bottom" type="primary" open-type="getUserInfo" withCredentials="true" lang="zh_CN"
@getuserinfo="wxGetUserInfo">授權登入</button> </view> </view> <u-toast ref="uToast" /> </view> </template> <script> export default { name: 'login', data() { return { SessionKey: '', OpenId: 'wxe8462175783ee72d', //自己小程式後臺管理的appid,可登入小程式後臺檢視
nickName: null, avatarUrl: null, isCanUse: uni.getStorageSync('isCanUse') || true //預設為true }; }, async onLoad() { //預設載入 await this.login(); this.isCanUse = uni.getStorageSync('isCanUse'); }, methods: { //第一授權獲取使用者資訊===》按鈕觸發 wxGetUserInfo() { let _this = this; uni.getUserInfo({ provider: 'weixin', success: function(infoRes) { uni.setStorageSync('isCanUse', false); //記錄是否第一次授權 false:表示不是第一次授權 _this.userLogin(infoRes.userInfo); }, fail(res) { uni.showToast({ title: '微信登入授權失敗', icon: 'none' }); } }); }, //登入 login() { let _this = this; wx.getSetting({ success: function(res) { if (res.authSetting['scope.userInfo']) { console.log('使用者授權了'); uni.showLoading({ title: '登入中...' }); uni.setStorageSync('isCanUse', false); //記錄是否第一次授權 false:表示不是第一次授權 _this.userLogin(); } else { //使用者沒有授權 console.log('使用者沒有授權'); _this.isCanUse = true; } } }); }, userLogin(data) { let _this = this; // 1.wx獲取登入使用者code uni.login({ provider: 'weixin', success: function(loginRes) { let code = loginRes.code; // console.log( loginRes) //2.將使用者登入code傳遞到後臺置換使用者SessionKey、OpenId等資訊 // _this.getOpenId({ code }); uni.hideLoading(); //_this.$api.getOpenId是我介面的封裝 _this.$api.getOpenId({ code }).then(res => { console.log(res) uni.hideLoading(); if (!data) { // 獲取使用者資訊 uni.getUserInfo({ provider: 'weixin', success: function(infoRes) { //獲取使用者資訊後向呼叫資訊更新方法 console.log(infoRes) // _this.updateUserInfo(infoRes.userInfo, res); //呼叫更新資訊方法 } }); } else { _this.updateUserInfo(data, res); //呼叫更新資訊方法 } }); } }); }, }, }; </script> <style scoped lang="scss"> .header { margin: 90upx 0 90upx 50upx; border-bottom: 1px solid #ccc; text-align: center; width: 650upx; height: 300upx; line-height: 450upx; } .header image { width: 200upx; height: 200upx; } .content { margin-left: 50upx; margin-bottom: 90upx; } .content text { display: block; color: #9d9d9d; margin-top: 40upx; } .bottom { border-radius: 80upx; margin: 70upx 50upx; font-size: 35upx; } </style>

後臺程式碼(nodeJS)路由檔案

module.exports = (app) => {
  const express = require("express");
  const router = express.Router();
  let openid, sessionKey;
  router.post("/get_openid", async (req, res) => {
    let code = req.body.params.code; //獲取小程式傳來的code
    // let encryptedData = params.encryptedData;//獲取小程式傳來的encryptedData
    // let iv = params.iv;//獲取小程式傳來的iv( iv 是加密演算法的初始向量)  uni.getUserInfo獲取
    let appid = "自己的"; //自己小程式後臺管理的appid,可登入小程式後臺檢視
    let secret = "自己的"; //小程式後臺管理的secret,可登入小程式後臺檢視
    let grant_type = "authorization_code"; // 授權(必填)預設值
    let url =
      "https://api.weixin.qq.com/sns/jscode2session?grant_type=" +
      grant_type +
      "&appid=" +
      appid +
      "&secret=" +
      secret +
      "&js_code=" +
      code;
    let openid, sessionKey;
    let https = require("https");
    https.get(url, (res1) => {
      res1
        .on("data", (d) => {
          console.log("返回的資訊: ", JSON.parse(d));
          openid = JSON.parse(d).openid; //得到openid
          sessionKey = JSON.parse(d).session_key; //得到session_key
          
          let data = {
            openid: openid,
            sessionKey: sessionKey,
          };
          //返回前端
          res.send(data);
        })
        .on("error", (e) => {
          console.error(e);
        });
    });
  });
    app.use("/user/api", router);
};

贈介面封裝
檔案目錄
在這裡插入圖片描述
config.js

const BASE_URL = 'http://localhost:3000'
// import regeneratorRuntime from 'regenerator-runtime'
const showToast = (title) => {
    uni.showToast({
        title: title,
        icon: 'none'
    })
}
/**請求介面
 * @method http
 * @param {String} url 介面地址
 * @param {Object} data 介面引數
 * @param {Object} option 介面配置資訊,可選
 * @return {Object} Promise
 */
const api = (url, data = {}, option = {}) => {
    let hideLoading = option.hideLoading || true // 是否顯示 loading
    let hideMsg = option.hideMsg || true // 是否隱藏錯誤提示
    let token = '' // 登入鑑權獲得的 token
    uni.getStorage({
        key: 'token',
        success: (ress) => {
            token = ress.data
        }
    })
    if (!hideLoading) {
        uni.showLoading({
            title: '載入中...',
            mask: true
        })
    }
    return new Promise((resolve, reject) => {
        uni.request({
            url: BASE_URL + url,
            method: option.method || 'POST', // 預設 post 請求
            header: {
                'Token': token
            },
            data: data,
            success: res => { // 伺服器成功返回的回撥函式
                if (!hideLoading) uni.hideLoading()
                if (res.statusCode === 200) {
					// console.log(res.data)
                    let result = res.data
					// console.log(result,2)
					  resolve(result)
                    if (result.errcode === '0') {
                        resolve(result)
                        return
                    }
                    // reject(result.errmsg)
                    if (!hideMsg) showToast(result.errmsg)
                } else { // 返回值非 200,強制顯示提示資訊
                    showToast('[' + res.statusCode + '] 系統處理失敗')
                    reject('[' + res.statusCode + '] 系統處理失敗')
                }
            },
            fail: (err) => { // 介面呼叫失敗的回撥函式
                if (!hideLoading) uni.hideLoading()
                if (err.errMsg != 'request:fail abort') {
                    showToast('連線超時,請檢查您的網路。')
                    reject('連線超時,請檢查您的網路。')
                }
            }
        })
    })
}
export default api

data.js

import api from '@/api/config.js'
let Api = {
	// 登入
	getOpenId(params) {
		return api('/user/api/get_openid', {params}, {method: 'POST'});
	},
};
export default Api;

main.js

import Vue from 'vue'
import App from '@/App'
import api from '@/api/data.js'
Vue.prototype.$api =api;
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
    ...App
})
app.$mount()

頁面呼叫

//方法內
this.$api.getOpenId(params).then(res => {
	console.log(res)
});
或者
 async getOpenId() {
	let res=await this.$api.getOpenId(params)
	 console.log(res);
  },