超碰人人人人人,亚洲AV午夜福利精品一区二区,亚洲欧美综合区丁香五月1区,日韩欧美亚洲系列

LOGO OA教程 ERP教程 模切知識交流 PMS教程 CRM教程 開發(fā)文檔 其他文檔  
 
網(wǎng)站管理員

微信授權(quán)全鏈路打通指南(小程序、網(wǎng)頁、開放平臺、企業(yè)微信授權(quán))

freeflydom
2024年12月17日 15:49 本文熱度 1397

近期,我在致力于打造自己的小程序產(chǎn)品時(shí),迎來了一項(xiàng)關(guān)鍵性的進(jìn)展——微信相關(guān)授權(quán)流程的完整實(shí)現(xiàn)。從用戶登錄到權(quán)限獲取,我們細(xì)致入微地梳理并實(shí)現(xiàn)了每一項(xiàng)授權(quán)機(jī)制,確保了用戶體驗(yàn)的流暢與安全。

微信小程序授權(quán)

授權(quán)流程:

  1. 用戶在小程序中點(diǎn)擊登錄按鈕,觸發(fā) wx.login() 獲取 code
  2. 小程序?qū)?nbsp;code 發(fā)送到后端服務(wù)器。
  3. 后端通過微信接口 jscode2session 使用 code 獲取 session_key 和 openid
  4. 后端返回 session_key 和 openid 給前端。
  5. 前端獲取 session_key 和 openid,使用 wx.getUserProfile() 獲取用戶信息(如昵稱、頭像等)。
  6. 如果需要,可以將用戶信息(如昵稱、頭像等)發(fā)送到后端進(jìn)行存儲或處理。
wx.login({
  success: function(res) {
    if (res.code) {
      // 將 code 發(fā)送到服務(wù)器
      wx.request({
        url: 'https://localhost:8080/api/login',
        method: 'POST',
        data: {
          code: res.code
        },
        success: function(response) {
          // 處理服務(wù)器返回的數(shù)據(jù)
          console.log(response.data);
        }
      });
    }
  }
});

下面是Nest 偽代碼實(shí)現(xiàn)

import { Injectable } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { firstValueFrom } from 'rxjs';
interface MiniProgramLoginResponse {
  openid: string;
  session_key: string;
  unionid?: string;
  errcode?: number;
  errmsg?: string;
}
@Injectable()
  export class MiniProgramAuthService {
    constructor(private readonly httpService: HttpService) {}
    async login(code: string): Promise<MiniProgramLoginResponse> {
      const url = 'https://api.weixin.qq.com/sns/jscode2session';
      try {
        const response = await firstValueFrom(
          this.httpService.get(url, {
            params: {
              appid: process.env.MINIPROGRAM_APPID,
              secret: process.env.MINIPROGRAM_APPSECRET,
              js_code: code,
              grant_type: 'authorization_code'
            }
          })
        );
        return response.data;
      } catch (error) {
        throw new Error('小程序登錄失敗');
      }
    }
    // 解密用戶敏感信息
    async decryptUserInfo(sessionKey: string, encryptedData: string, iv: string) {
      // 實(shí)現(xiàn)微信小程序用戶信息解密邏輯
      // 通常需要使用第三方加密庫如 crypto-js
    }
  }

微信網(wǎng)頁授權(quán)(OAuth 2.0)

網(wǎng)頁授權(quán)是通過微信官方提供的OAuth2.0認(rèn)證方式,使第三方網(wǎng)站或應(yīng)用能夠獲取用戶基本信息,實(shí)現(xiàn)用戶身份識別。

授權(quán)流程

  1. 發(fā)起授權(quán)
    • 用戶點(diǎn)擊登錄/授權(quán)按鈕
    • 生成授權(quán)鏈接
    • 跳轉(zhuǎn)至微信授權(quán)頁面
  2. 用戶確認(rèn)
    • 用戶選擇是否授權(quán)
    • 確認(rèn)后獲取臨時(shí)授權(quán)碼 code
  3. 換取 Access Token
    • 服務(wù)端使用 code 換取 access_token
    • 獲取用戶的 openid 和 access_token
  4. 獲取用戶信息
    • 使用 access_token 和 openid
    • 調(diào)用微信接口獲取用戶詳細(xì)信息
  5. 系統(tǒng)內(nèi)部處理
    • 創(chuàng)建或更新用戶信息
    • 生成系統(tǒng)內(nèi)部登錄態(tài)
import { Injectable } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { firstValueFrom } from 'rxjs';
// 用戶授權(quán)信息接口定義
interface WechatUserInfo {
  openid: string;      // 用戶唯一標(biāo)識
  nickname: string;    // 用戶昵稱
  sex: number;         // 用戶性別
  province: string;    // 省份
  city: string;        // 城市
  country: string;     // 國家
  headimgurl: string;  // 頭像地址
  privilege: string[]; // 用戶特權(quán)信息
  unionid?: string;    // 開放平臺唯一標(biāo)識
}
@Injectable()
export class WebAuthService {
  constructor(private readonly httpService: HttpService) {}
  // 生成授權(quán)鏈接
  generateAuthUrl(redirectUri: string, scope: 'snsapi_base' | 'snsapi_userinfo' = 'snsapi_userinfo') {
    const baseUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize';
    const params = new URLSearchParams({
      appid: process.env.WECHAT_APPID,
      redirect_uri: redirectUri,
      response_type: 'code',
      scope: scope,
      state: 'STATE#wechat_redirect'  // 自定義參數(shù),用于回傳
    });
    
    return `${baseUrl}?${params}#wechat_redirect`;
  }
  // 獲取 Access Token
  async getAccessToken(code: string) {
    const url = 'https://api.weixin.qq.com/sns/oauth2/access_token';
    
    try {
      const response = await firstValueFrom(
        this.httpService.get(url, {
          params: {
            appid: process.env.WECHAT_APPID,
            secret: process.env.WECHAT_APPSECRET,
            code: code,
            grant_type: 'authorization_code'
          }
        })
      );
      return response.data;
    } catch (error) {
      throw new Error('獲取 Access Token 失敗');
    }
  }
  // 獲取用戶信息
  async getUserInfo(accessToken: string, openid: string): Promise<WechatUserInfo> {
    const url = 'https://api.weixin.qq.com/sns/userinfo';
    
    try {
      const response = await firstValueFrom(
        this.httpService.get(url, {
          params: {
            access_token: accessToken,
            openid: openid,
            lang: 'zh_CN'
          }
        })
      );
      return response.data;
    } catch (error) {
      throw new Error('獲取用戶信息失敗');
    }
  }
}

微信開放平臺授權(quán)

特點(diǎn):

  • 適用于第三方應(yīng)用
  • 支持移動應(yīng)用、網(wǎng)站應(yīng)用等
  • 需要開發(fā)者資質(zhì)認(rèn)證
import { Injectable } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { firstValueFrom } from 'rxjs';
// 定義開放平臺授權(quán)響應(yīng)接口
interface OpenPlatformAuthResponse {
  access_token: string;    // 接口調(diào)用憑證
  expires_in: number;      // access_token 過期時(shí)間
  refresh_token: string;   // 刷新 token
  openid: string;          // 授權(quán)用戶唯一標(biāo)識
  scope: string;           // 用戶授權(quán)的作用域
  unionid: string;         // 開放平臺唯一標(biāo)識
}
@Injectable()
export class OpenPlatformAuthService {
  constructor(private readonly httpService: HttpService) {}
  /**
   * 獲取 access_token
   * @param code 授權(quán)碼
   * @returns 授權(quán)響應(yīng)信息
   */
  async getAccessToken(code: string): Promise<OpenPlatformAuthResponse> {
    // 微信獲取 access_token 的接口地址
    const url = 'https://api.weixin.qq.com/sns/oauth2/access_token';
    
    try {
      // 使用授權(quán)碼換取 access_token
      const response = await firstValueFrom(
        this.httpService.get(url, {
          params: {
            // 從環(huán)境變量讀取開放平臺 AppID
            appid: process.env.OPEN_PLATFORM_APPID,
            // 從環(huán)境變量讀取開放平臺密鑰
            secret: process.env.OPEN_PLATFORM_APPSECRET,
            // 授權(quán)碼
            code: code,
            // 授權(quán)類型,固定值
            grant_type: 'authorization_code'
          }
        })
      );
      return response.data;
    } catch (error) {
      // 捕獲并拋出授權(quán)失敗的錯誤
      throw new Error('開放平臺授權(quán)失敗');
    }
  }
  /**
   * 刷新 access_token
   * @param refreshToken 刷新 token
   * @returns 新的授權(quán)信息
   */
  async refreshAccessToken(refreshToken: string) {
    // 微信刷新 access_token 的接口地址
    const url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token';
    
    try {
      // 使用 refresh_token 換取新的 access_token
      const response = await firstValueFrom(
        this.httpService.get(url, {
          params: {
            // 開放平臺 AppID
            appid: process.env.OPEN_PLATFORM_APPID,
            // 授權(quán)類型,固定值
            grant_type: 'refresh_token',
            // 用于刷新的 token
            refresh_token: refreshToken
          }
        })
      );
      return response.data;
    } catch (error) {
      // 捕獲并拋出刷新 Token 失敗的錯誤
      throw new Error('刷新 Token 失敗');
    }
  }
}

企業(yè)微信授權(quán)

企業(yè)微信授權(quán)是針對企業(yè)內(nèi)部應(yīng)用和員工的身份認(rèn)證機(jī)制,提供更嚴(yán)格和精細(xì)的權(quán)限控制。

特點(diǎn):

  • 主要面向企業(yè)內(nèi)部應(yīng)用
  • 更強(qiáng)的權(quán)限控制
  • 安全性更高

授權(quán)流程

  1. 發(fā)起授權(quán)
    • 員工訪問企業(yè)內(nèi)部應(yīng)用
    • 觸發(fā)登錄機(jī)制(掃碼/輸入)
    • 生成企業(yè)微信授權(quán)鏈接
  2. 身份驗(yàn)證
    • 跳轉(zhuǎn)企業(yè)微信登錄頁
    • 員工確認(rèn)身份
    • 獲取臨時(shí)授權(quán)碼
  3. 換取用戶信息
    • 服務(wù)端使用 code 換取用戶標(biāo)識
    • 獲取 userid
    • 調(diào)用接口獲取用戶詳細(xì)信息
  4. 系統(tǒng)內(nèi)部處理
    • 驗(yàn)證員工身份
    • 檢查權(quán)限狀態(tài)
    • 生成系統(tǒng)內(nèi)部登錄態(tài)
import { Injectable } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { firstValueFrom } from 'rxjs';
// 定義企業(yè)微信授權(quán)響應(yīng)接口
interface EnterpriseWechatAuthResponse {
  access_token: string;    // 企業(yè)接口調(diào)用憑證
  expires_in: number;      // access_token 過期時(shí)間
  user_ticket?: string;    // 用戶票據(jù)(可選)
  user_info?: {
    userid: string;        // 企業(yè)成員 ID
    name: string;          // 成員名稱
    department: number[];  // 部門 ID 列表
  };
}
@Injectable()
export class EnterpriseWechatAuthService {
  constructor(private readonly httpService: HttpService) {}
  /**
   * 獲取企業(yè)微信用戶信息
   * @param code 臨時(shí)授權(quán)碼
   * @returns 用戶信息和 access_token
   */
  async getUserInfo(code: string): Promise<EnterpriseWechatAuthResponse> {
    // 獲取企業(yè) access_token 的接口地址
    const tokenUrl = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken';
    // 獲取用戶信息的接口地址
    const userInfoUrl = 'https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo';
    // 第一步:獲取企業(yè) access_token
    // 需要使用企業(yè) ID 和應(yīng)用的秘鑰
    const tokenResponse = await firstValueFrom(
      this.httpService.get(tokenUrl, {
        params: {
          // 從環(huán)境變量讀取企業(yè) ID
          corpid: process.env.ENTERPRISE_CORPID,
          // 從環(huán)境變量讀取企業(yè)應(yīng)用秘鑰
          corpsecret: process.env.ENTERPRISE_CORPSECRET
        }
      })
    );
    // 從響應(yīng)中提取 access_token
    const accessToken = tokenResponse.data.access_token;
    // 第二步:使用 access_token 和臨時(shí)授權(quán)碼獲取用戶信息
    const userInfoResponse = await firstValueFrom(
      this.httpService.get(userInfoUrl, {
        params: {
          // 企業(yè) access_token
          access_token: accessToken,
          // 臨時(shí)授權(quán)碼
          code: code
        }
      })
    );
    return userInfoResponse.data;
  }
}

各個平臺授權(quán)小結(jié)

授權(quán)類型個人是否可用是否收費(fèi)主要適用場景
網(wǎng)頁授權(quán)免費(fèi)網(wǎng)站、H5應(yīng)用
小程序授權(quán)免費(fèi)小程序登錄、開放平臺
公眾號授權(quán)部分可用免費(fèi)+增值服務(wù)公眾號相關(guān)應(yīng)用(服務(wù)號、訂閱號)
企業(yè)微信有費(fèi)用企業(yè)內(nèi)部協(xié)作

?轉(zhuǎn)自https://www.cnblogs.com/HaiJun-Aion/p/18609286

該文章在 2024/12/17 15:49:13 編輯過
關(guān)鍵字查詢
相關(guān)文章
正在查詢...
點(diǎn)晴ERP是一款針對中小制造業(yè)的專業(yè)生產(chǎn)管理軟件系統(tǒng),系統(tǒng)成熟度和易用性得到了國內(nèi)大量中小企業(yè)的青睞。
點(diǎn)晴PMS碼頭管理系統(tǒng)主要針對港口碼頭集裝箱與散貨日常運(yùn)作、調(diào)度、堆場、車隊(duì)、財(cái)務(wù)費(fèi)用、相關(guān)報(bào)表等業(yè)務(wù)管理,結(jié)合碼頭的業(yè)務(wù)特點(diǎn),圍繞調(diào)度、堆場作業(yè)而開發(fā)的。集技術(shù)的先進(jìn)性、管理的有效性于一體,是物流碼頭及其他港口類企業(yè)的高效ERP管理信息系統(tǒng)。
點(diǎn)晴WMS倉儲管理系統(tǒng)提供了貨物產(chǎn)品管理,銷售管理,采購管理,倉儲管理,倉庫管理,保質(zhì)期管理,貨位管理,庫位管理,生產(chǎn)管理,WMS管理系統(tǒng),標(biāo)簽打印,條形碼,二維碼管理,批號管理軟件。
點(diǎn)晴免費(fèi)OA是一款軟件和通用服務(wù)都免費(fèi),不限功能、不限時(shí)間、不限用戶的免費(fèi)OA協(xié)同辦公管理系統(tǒng)。
Copyright 2010-2025 ClickSun All Rights Reserved