auth-wechat-miniprogram by tencentcloudbase/skills
npx skills add https://github.com/tencentcloudbase/skills --skill auth-wechat-miniprogram在 CloudBase 项目中进行微信小程序认证时使用此技能。
当您需要时使用它:
关键优势: 使用 CloudBase 进行微信小程序认证是无缝且自动的 - 无需复杂的 OAuth 流程。当小程序调用云函数时,用户的 openid 会自动注入并由微信验证。
请勿用于:
env – CloudBase 环境 ID广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
wx-server-sdkwx.cloudOPENID – 用户在此特定小程序中的唯一标识符APPID – 小程序的 App IDUNIONID – (可选)同一微信开放平台账号下所有应用中的唯一标识符
openid、appid 和 unionid 是经过验证且可信的在您小程序的 app.js 或入口点中使用:
// app.js
App({
onLaunch: function () {
// Initialize CloudBase
wx.cloud.init({
env: 'your-env-id', // Your CloudBase environment ID
traceUser: true // Optional: track user access in console
})
}
})
要点:
wx.cloud.init()env 设置为您的 CloudBase 环境 IDtraceUser: true 可在 CloudBase 控制台中启用用户访问跟踪(可选但推荐)当您需要知道谁在调用您的云函数时使用:
// Cloud function: cloudfunctions/getUserInfo/index.js
const cloud = require('wx-server-sdk')
// Initialize cloud with dynamic environment
cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV
})
exports.main = async (event, context) => {
// Get user identity - this is automatically injected by WeChat
const { OPENID, APPID, UNIONID } = cloud.getWXContext()
console.log('User identity:', { OPENID, APPID, UNIONID })
// Use OPENID for user-specific operations
// For example: query user data, check permissions, etc.
return {
openid: OPENID,
appid: APPID,
unionid: UNIONID // May be undefined if not available
}
}
要点:
cloud.getWXContext() 获取用户身份OPENID 始终可用,并唯一标识用户APPID 标识小程序UNIONID 仅在以下情况下可用:
cloud.DYNAMIC_CURRENT_ENV 自动使用当前环境最佳实践:
OPENID 存储在数据库中,以便将数据与用户关联OPENID 进行授权和访问控制UNIONIDOPENID 暴露给其他用户(它是私有标识符)在您的小程序中使用此代码调用云函数并获取用户身份:
// In Mini Program page
Page({
onLoad: function() {
this.getUserInfo()
},
getUserInfo: function() {
wx.cloud.callFunction({
name: 'getUserInfo', // Cloud function name
data: {}, // Optional parameters
success: res => {
console.log('User info from cloud function:', res.result)
// res.result contains { openid, appid, unionid }
// Use the user info
this.setData({
openid: res.result.openid
})
},
fail: err => {
console.error('Failed to get user info:', err)
}
})
}
})
要点:
wx.cloud.callFunction() 调用云函数云函数 (cloudfunctions/test/index.js):
const cloud = require('wx-server-sdk')
cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV
})
exports.main = async (event, context) => {
// Get verified user identity - automatically injected by WeChat
const { OPENID, APPID, UNIONID } = cloud.getWXContext()
console.log('User identity:', { OPENID, APPID, UNIONID })
return {
success: true,
message: 'Authentication successful',
identity: {
openid: OPENID,
appid: APPID,
unionid: UNIONID || 'Not available'
},
timestamp: new Date().toISOString()
}
}
小程序代码:
// pages/index/index.js
Page({
data: {
userIdentity: null
},
onLoad: function() {
this.testAuth()
},
testAuth: function() {
console.log('Testing authentication...')
wx.cloud.callFunction({
name: 'test',
success: res => {
console.log('Authentication test result:', res.result)
this.setData({
userIdentity: res.result.identity
})
wx.showToast({
title: 'Auth successful',
icon: 'success'
})
},
fail: err => {
console.error('Authentication test failed:', err)
wx.showToast({
title: 'Auth failed',
icon: 'error'
})
}
})
}
})
要点:
OPENID 始终存在且经过验证UNIONID 可能未定义(如果不可用)cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV
})
这确保云函数自动使用正确的环境。
OPENID 作为主要用户标识符OPENID 暴露给其他用户const { OPENID, UNIONID } = cloud.getWXContext()
if (UNIONID) {
// User has UNIONID - can be used for cross-app identification
console.log('UNIONID available:', UNIONID)
} else {
// UNIONID not available - use OPENID only
console.log('Using OPENID only:', OPENID)
}
OPENID 来识别和授权用户OPENIDOPENID 以确保用户只能访问自己的数据调用云函数时始终处理错误:
wx.cloud.callFunction({
name: 'myFunction',
success: res => {
// Handle success
},
fail: err => {
console.error('Cloud function error:', err)
// Show user-friendly error message
wx.showToast({
title: 'Operation failed',
icon: 'error'
})
}
})
在 app.js 的 onLaunch 中初始化 CloudBase:
App({
onLaunch: function () {
wx.cloud.init({
env: 'your-env-id',
traceUser: true
})
}
})
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
exports.main = async (event, context) => {
const { OPENID, APPID, UNIONID } = cloud.getWXContext()
return {
openid: OPENID,
appid: APPID,
unionid: UNIONID || null
}
}
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
exports.main = async (event, context) => {
const { OPENID } = cloud.getWXContext()
// Check if user is authorized
if (OPENID === event.resourceOwnerId) {
// User is authorized to access this resource
return { authorized: true }
} else {
return { authorized: false, error: 'Unauthorized' }
}
}
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
exports.main = async (event, context) => {
const { OPENID, UNIONID } = cloud.getWXContext()
if (UNIONID) {
// Can use UNIONID for cross-app user identification
console.log('User has UNIONID:', UNIONID)
} else {
// Fall back to OPENID only
console.log('Using OPENID only:', OPENID)
}
return { openid: OPENID, hasUnionId: !!UNIONID }
}
使用 CloudBase 进行微信小程序认证简单且安全:
OPENID、APPID 和 UNIONID 是可信的cloud.getWXContext()关键要点:
wx.cloud.init() 初始化 CloudBasecloud.getWXContext() 获取用户身份OPENID 进行用户识别和授权UNIONID 的可用性对于更复杂的认证场景或与其他系统的集成,请考虑结合使用 CloudBase 自定义登录和微信认证。
每周安装数
998
代码仓库
GitHub 星标数
38
首次出现
2026年1月22日
安全审计
安装于
opencode847
codex842
gemini-cli831
cursor805
github-copilot804
kimi-cli784
Use this skill for WeChat Mini Program (小程序) authentication in a CloudBase project.
Use it when you need to:
Key advantage: WeChat Mini Program authentication with CloudBase is seamless and automatic - no complex OAuth flows needed. When a Mini Program calls a cloud function, the user's openid is automatically injected and verified by WeChat.
Do NOT use for:
Confirm CloudBase environment
env – CloudBase environment IDUnderstand the authentication flow
Pick a scenario from this file
Follow CloudBase API shapes exactly
wx-server-sdk in cloud functionswx.cloud in Mini Program client codeIf you're unsure about an API
Automatic authentication:
User identifiers:
OPENID – Unique identifier for the user in this specific Mini ProgramAPPID – The Mini Program's App IDUNIONID – (Optional) Unique identifier across all apps under the same WeChat Open Platform account
Security:
openid, appid, and unionid are Use this in your Mini Program's app.js or entry point:
// app.js
App({
onLaunch: function () {
// Initialize CloudBase
wx.cloud.init({
env: 'your-env-id', // Your CloudBase environment ID
traceUser: true // Optional: track user access in console
})
}
})
Key points:
wx.cloud.init() once when the Mini Program launchesenv to your CloudBase environment IDtraceUser: true enables user access tracking in CloudBase console (optional but recommended)Use this when you need to know who is calling your cloud function:
// Cloud function: cloudfunctions/getUserInfo/index.js
const cloud = require('wx-server-sdk')
// Initialize cloud with dynamic environment
cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV
})
exports.main = async (event, context) => {
// Get user identity - this is automatically injected by WeChat
const { OPENID, APPID, UNIONID } = cloud.getWXContext()
console.log('User identity:', { OPENID, APPID, UNIONID })
// Use OPENID for user-specific operations
// For example: query user data, check permissions, etc.
return {
openid: OPENID,
appid: APPID,
unionid: UNIONID // May be undefined if not available
}
}
Key points:
cloud.getWXContext() to get user identityOPENID is always available and uniquely identifies the userAPPID identifies the Mini ProgramUNIONID is only available when:
cloud.DYNAMIC_CURRENT_ENV to automatically use the current environmentBest practices:
OPENID in your database to associate data with usersOPENID for authorization and access controlUNIONID when you need to identify users across multiple Mini Programs or Official AccountsOPENID to other users (it's a private identifier)Use this in your Mini Program to call a cloud function and get user identity:
// In Mini Program page
Page({
onLoad: function() {
this.getUserInfo()
},
getUserInfo: function() {
wx.cloud.callFunction({
name: 'getUserInfo', // Cloud function name
data: {}, // Optional parameters
success: res => {
console.log('User info from cloud function:', res.result)
// res.result contains { openid, appid, unionid }
// Use the user info
this.setData({
openid: res.result.openid
})
},
fail: err => {
console.error('Failed to get user info:', err)
}
})
}
})
Key points:
wx.cloud.callFunction() to call cloud functionsCloud function (cloudfunctions/test/index.js):
const cloud = require('wx-server-sdk')
cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV
})
exports.main = async (event, context) => {
// Get verified user identity - automatically injected by WeChat
const { OPENID, APPID, UNIONID } = cloud.getWXContext()
console.log('User identity:', { OPENID, APPID, UNIONID })
return {
success: true,
message: 'Authentication successful',
identity: {
openid: OPENID,
appid: APPID,
unionid: UNIONID || 'Not available'
},
timestamp: new Date().toISOString()
}
}
Mini Program code:
// pages/index/index.js
Page({
data: {
userIdentity: null
},
onLoad: function() {
this.testAuth()
},
testAuth: function() {
console.log('Testing authentication...')
wx.cloud.callFunction({
name: 'test',
success: res => {
console.log('Authentication test result:', res.result)
this.setData({
userIdentity: res.result.identity
})
wx.showToast({
title: 'Auth successful',
icon: 'success'
})
},
fail: err => {
console.error('Authentication test failed:', err)
wx.showToast({
title: 'Auth failed',
icon: 'error'
})
}
})
}
})
Key points:
OPENID is always present and verifiedUNIONID may be undefined if not availablecloud.init({
env: cloud.DYNAMIC_CURRENT_ENV
})
This ensures the cloud function uses the correct environment automatically.
OPENID as the primary user identifierOPENID to other usersconst { OPENID, UNIONID } = cloud.getWXContext()
if (UNIONID) {
// User has UNIONID - can be used for cross-app identification
console.log('UNIONID available:', UNIONID)
} else {
// UNIONID not available - use OPENID only
console.log('Using OPENID only:', OPENID)
}
OPENID to identify and authorize usersOPENID when you need to associate data with usersOPENID in queries to ensure users only access their own dataAlways handle errors when calling cloud functions:
wx.cloud.callFunction({
name: 'myFunction',
success: res => {
// Handle success
},
fail: err => {
console.error('Cloud function error:', err)
// Show user-friendly error message
wx.showToast({
title: 'Operation failed',
icon: 'error'
})
}
})
Initialize CloudBase in app.js onLaunch:
App({
onLaunch: function () {
wx.cloud.init({
env: 'your-env-id',
traceUser: true
})
}
})
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
exports.main = async (event, context) => {
const { OPENID, APPID, UNIONID } = cloud.getWXContext()
return {
openid: OPENID,
appid: APPID,
unionid: UNIONID || null
}
}
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
exports.main = async (event, context) => {
const { OPENID } = cloud.getWXContext()
// Check if user is authorized
if (OPENID === event.resourceOwnerId) {
// User is authorized to access this resource
return { authorized: true }
} else {
return { authorized: false, error: 'Unauthorized' }
}
}
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
exports.main = async (event, context) => {
const { OPENID, UNIONID } = cloud.getWXContext()
if (UNIONID) {
// Can use UNIONID for cross-app user identification
console.log('User has UNIONID:', UNIONID)
} else {
// Fall back to OPENID only
console.log('Using OPENID only:', OPENID)
}
return { openid: OPENID, hasUnionId: !!UNIONID }
}
WeChat Mini Program authentication with CloudBase is simple and secure :
OPENID, APPID, and UNIONID are trustworthycloud.getWXContext() in cloud functionsKey takeaways:
wx.cloud.init() in Mini Programcloud.getWXContext() to get user identity in cloud functionsOPENID for user identification and authorizationUNIONID availability appropriatelyFor more complex authentication scenarios or integration with other systems, consider using CloudBase custom login in combination with WeChat authentication.
Weekly Installs
998
Repository
GitHub Stars
38
First Seen
Jan 22, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
opencode847
codex842
gemini-cli831
cursor805
github-copilot804
kimi-cli784
React 组合模式指南:Vercel 组件架构最佳实践,提升代码可维护性
103,800 周安装
No explicit login required: