auth-wechat-miniprogram

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

When to use this skill

何时使用该技能

Use this skill for WeChat Mini Program (小程序) authentication in a CloudBase project.
Use it when you need to:
  • Implement WeChat Mini Program login with CloudBase
  • Access user identity (openid, unionid) in cloud functions
  • Understand how WeChat authentication integrates with CloudBase
  • Build Mini Program features that require user identification
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:
  • Web-based WeChat login (use the CloudBase Web Auth skill at
    skills/auth-web-skill
    )
  • Server-side auth with Node SDK (use the CloudBase Node Auth skill at
    skills/auth-nodejs-skill
    )
  • Non-WeChat authentication methods (use appropriate auth skills)

在CloudBase项目中进行微信小程序认证时使用该技能。
当你需要以下操作时使用:
  • 基于CloudBase实现微信小程序登录
  • 在云函数中获取用户身份(openid、unionid)
  • 了解微信认证与CloudBase的集成方式
  • 构建需要用户身份识别的小程序功能
核心优势:基于CloudBase的微信小程序认证无缝且自动完成——无需复杂的OAuth流程。当小程序调用云函数时,用户的
openid
会由微信自动注入并验证。
请勿用于以下场景
  • 基于网页的微信登录(使用位于
    skills/auth-web-skill
    CloudBase Web Auth技能)
  • 基于Node SDK的服务端认证(使用位于
    skills/auth-nodejs-skill
    CloudBase Node Auth技能)
  • 非微信认证方式(使用对应的认证技能)

How to use this skill (for a coding agent)

如何使用该技能(面向编码Agent)

  1. Confirm CloudBase environment
    • Ask the user for:
      • env
        – CloudBase environment ID
      • Confirm the Mini Program is linked to the CloudBase environment
  2. Understand the authentication flow
    • WeChat Mini Program authentication is native and automatic
    • No explicit login API calls needed in most cases
    • User identity is automatically available in cloud functions
    • CloudBase handles all authentication verification
  3. Pick a scenario from this file
    • For basic user identity in cloud functions, use Scenario 2
    • For Mini Program initialization, use Scenario 1
    • For calling a cloud function from the Mini Program and receiving user identity, use Scenario 3
    • For testing authentication, use Scenario 4
  4. Follow CloudBase API shapes exactly
    • Use
      wx-server-sdk
      in cloud functions
    • Use
      wx.cloud
      in Mini Program client code
    • Treat method names and parameter shapes in this file as canonical
  5. If you're unsure about an API
    • Consult the official CloudBase Mini Program documentation
    • Only use methods that appear in official documentation

  1. 确认CloudBase环境
    • 向用户确认以下信息:
      • env
        – CloudBase环境ID
      • 确认小程序已关联至CloudBase环境
  2. 了解认证流程
    • 微信小程序认证是原生且自动的
    • 大多数情况下无需显式调用登录API
    • 用户身份会自动在云函数中可用
    • CloudBase负责所有认证验证工作
  3. 从本文档中选择场景
    • 若要在云函数中获取基础用户身份,使用场景2
    • 若要初始化小程序,使用场景1
    • 若要从小程序调用云函数并获取用户身份,使用场景3
    • 若要测试认证功能,使用场景4
  4. 严格遵循CloudBase API格式
    • 在云函数中使用
      wx-server-sdk
    • 在小程序客户端代码中使用
      wx.cloud
    • 将本文档中的方法名和参数格式视为标准规范
  5. 若对API有疑问
    • 查阅CloudBase小程序官方文档
    • 仅使用官方文档中列出的方法

Core concepts

核心概念

How WeChat Mini Program authentication works with CloudBase

微信小程序认证与CloudBase的协作方式

  1. Automatic authentication:
    • When a Mini Program user calls a cloud function, WeChat automatically injects the user's identity
    • No need for complex OAuth flows or token management
    • CloudBase verifies the authenticity of the identity
  2. User identifiers:
    • OPENID
      – Unique identifier for the user in this specific Mini Program
    • APPID
      – The Mini Program's App ID
    • UNIONID
      – (Optional) Unique identifier across all apps under the same WeChat Open Platform account
      • Only available when the Mini Program is bound to a WeChat Open Platform account
      • Useful for identifying the same user across multiple Mini Programs or Official Accounts
  3. Security:
    • The
      openid
      ,
      appid
      , and
      unionid
      are verified and trustworthy
    • WeChat has already completed authentication
    • Developers can directly use these identifiers without additional verification
  4. No explicit login required:
    • Users are automatically authenticated when they use the Mini Program
    • No need to call login APIs in most cases
    • Identity is available immediately in cloud functions

  1. 自动认证
    • 当小程序用户调用云函数时,微信会自动注入用户身份
    • 无需复杂的OAuth流程或令牌管理
    • CloudBase会验证身份的真实性
  2. 用户标识符
    • OPENID
      – 用户在当前小程序中的唯一标识符
    • APPID
      – 小程序的App ID
    • UNIONID
      –(可选)同一微信开放平台账号下所有应用的用户唯一标识符
      • 仅当小程序绑定至微信开放平台账号时可用
      • 适用于在多个小程序或公众号中识别同一用户
  3. 安全性
    • openid
      appid
      unionid
      均经过验证且可信
    • 微信已完成所有认证流程
    • 开发者可直接使用这些标识符,无需额外验证
  4. 无需显式登录
    • 用户使用小程序时会自动完成认证
    • 大多数情况下无需调用登录API
    • 身份在云函数中立即可用

Scenarios – WeChat Mini Program auth patterns

场景——微信小程序认证模式

Scenario 1: Initialize CloudBase in Mini Program

场景1:在小程序中初始化CloudBase

Use this in your Mini Program's
app.js
or entry point:
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
    })
  }
})
Key points:
  • Call
    wx.cloud.init()
    once when the Mini Program launches
  • Set
    env
    to your CloudBase environment ID
  • traceUser: true
    enables user access tracking in CloudBase console (optional but recommended)

在小程序的
app.js
或入口文件中使用以下代码:
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环境ID
  • traceUser: true
    可在CloudBase控制台中启用用户访问追踪(可选但推荐)

Scenario 2: Get user identity in a cloud function

场景2:在云函数中获取用户身份

Use this when you need to know who is calling your cloud function:
js
// 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:
  • Use
    cloud.getWXContext()
    to get user identity
  • OPENID
    is always available and uniquely identifies the user
  • APPID
    identifies the Mini Program
  • UNIONID
    is only available when:
    • The Mini Program is bound to a WeChat Open Platform account
    • The user has authorized the Mini Program
  • These values are verified and trustworthy - no need to validate them
  • Use
    cloud.DYNAMIC_CURRENT_ENV
    to automatically use the current environment
Best practices:
  • Store
    OPENID
    in your database to associate data with users
  • Use
    OPENID
    for authorization and access control
  • Use
    UNIONID
    when you need to identify users across multiple Mini Programs or Official Accounts
  • Never expose
    OPENID
    to other users (it's a private identifier)

当你需要知道谁在调用云函数时使用以下代码:
js
// 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
    进行用户授权和访问控制
  • 当需要在多个小程序或公众号中识别用户时使用
    UNIONID
  • 切勿向其他用户暴露
    OPENID
    (这是私有标识符)

Scenario 3: Call cloud function from Mini Program

场景3:从小程序调用云函数

Use this in your Mini Program to call a cloud function and get user identity:
js
// 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:
  • Use
    wx.cloud.callFunction()
    to call cloud functions
  • User identity is automatically passed to the cloud function
  • No need to manually send user credentials
  • Handle both success and error cases

在小程序中使用以下代码调用云函数并获取用户身份:
js
// 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()
    调用云函数
  • 用户身份会自动传递至云函数
  • 无需手动发送用户凭证
  • 同时处理成功和失败情况

Scenario 4: Test authentication - Simple test function

场景4:测试认证——简单测试函数

Cloud function (cloudfunctions/test/index.js):
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:
js
// 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:
  • No explicit login API call needed
  • User identity is automatically available in cloud function
  • OPENID
    is always present and verified
  • UNIONID
    may be undefined if not available
  • Use this pattern to verify authentication is working correctly

云函数(cloudfunctions/test/index.js)
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()
  }
}
小程序代码
js
// 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'
        })
      }
    })
  }
})
关键点
  • 无需显式调用登录API
  • 用户身份会自动在云函数中可用
  • OPENID
    始终存在且经过验证
  • UNIONID
    可能不可用(为undefined)
  • 使用该模式验证认证功能是否正常工作

Best practices

最佳实践

1. Always use cloud.DYNAMIC_CURRENT_ENV

1. 始终使用cloud.DYNAMIC_CURRENT_ENV

js
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
This ensures the cloud function uses the correct environment automatically.
js
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
这确保云函数自动使用正确的环境。

2. Store OPENID for user identification

2. 存储OPENID用于用户识别

  • Use
    OPENID
    as the primary user identifier
  • Store it in your database to associate data with users
  • Never expose
    OPENID
    to other users
  • 使用
    OPENID
    作为主要用户标识符
  • 将其存储在数据库中以关联用户数据
  • 切勿向其他用户暴露
    OPENID

3. Handle UNIONID availability

3. 处理UNIONID的可用性

js
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)
}
js
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)
}

4. Use OPENID for user-specific operations

4. 使用OPENID进行用户专属操作

  • Use
    OPENID
    to identify and authorize users
  • Store
    OPENID
    when you need to associate data with users
  • Use
    OPENID
    in queries to ensure users only access their own data
  • 使用
    OPENID
    识别和授权用户
  • 当需要关联用户数据时存储
    OPENID
  • 在查询中使用
    OPENID
    确保用户仅能访问自己的数据

5. Error handling

5. 错误处理

Always handle errors when calling cloud functions:
js
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'
    })
  }
})
调用云函数时始终处理错误:
js
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'
    })
  }
})

6. Initialize CloudBase early

6. 尽早初始化CloudBase

Initialize CloudBase in
app.js
onLaunch
:
js
App({
  onLaunch: function () {
    wx.cloud.init({
      env: 'your-env-id',
      traceUser: true
    })
  }
})

app.js
onLaunch
中初始化CloudBase:
js
App({
  onLaunch: function () {
    wx.cloud.init({
      env: 'your-env-id',
      traceUser: true
    })
  }
})

Common patterns

常见模式

Pattern 1: Get and return user identity

模式1:获取并返回用户身份

js
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
  }
}
js
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
  }
}

Pattern 2: Use OPENID for authorization

模式2:使用OPENID进行授权

js
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' }
  }
}
js
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' }
  }
}

Pattern 3: Handle UNIONID availability

模式3:处理UNIONID的可用性

js
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 }
}

js
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 }
}

Summary

总结

WeChat Mini Program authentication with CloudBase is simple and secure:
  1. No explicit login needed - authentication is automatic
  2. User identity is verified -
    OPENID
    ,
    APPID
    , and
    UNIONID
    are trustworthy
  3. Easy to use - just call
    cloud.getWXContext()
    in cloud functions
  4. Secure by default - WeChat handles all authentication verification
Key takeaways:
  • Initialize CloudBase with
    wx.cloud.init()
    in Mini Program
  • Use
    cloud.getWXContext()
    to get user identity in cloud functions
  • Use
    OPENID
    for user identification and authorization
  • Handle
    UNIONID
    availability appropriately
  • No explicit login API calls needed - authentication is automatic
For more complex authentication scenarios or integration with other systems, consider using CloudBase custom login in combination with WeChat authentication.
基于CloudBase的微信小程序认证简单且安全
  1. 无需显式登录——认证自动完成
  2. 用户身份已验证——
    OPENID
    APPID
    UNIONID
    均可信
  3. 易于使用——只需在云函数中调用
    cloud.getWXContext()
  4. 默认安全——微信负责所有认证验证工作
核心要点
  • 在小程序中使用
    wx.cloud.init()
    初始化CloudBase
  • 在云函数中使用
    cloud.getWXContext()
    获取用户身份
  • 使用
    OPENID
    进行用户识别和授权
  • 适当处理
    UNIONID
    的可用性
  • 无需显式调用登录API——认证自动完成
对于更复杂的认证场景或与其他系统的集成,可考虑结合使用CloudBase自定义登录与微信认证。