auth-wechat-miniprogram

0
0
Source

Complete guide for WeChat Mini Program authentication with CloudBase - native login, user identity, and cloud function integration.

Install

mkdir -p .claude/skills/auth-wechat-miniprogram && curl -L -o skill.zip "https://mcp.directory/api/skills/download/6874" && unzip -o skill.zip -d .claude/skills/auth-wechat-miniprogram && rm skill.zip

Installs to .claude/skills/auth-wechat-miniprogram

About this skill

Activation Contract

Use this first when

  • The task is about WeChat Mini Program auth behavior, wx.cloud identity, OPENID / UNIONID, or how a mini program caller is identified in CloudBase.
  • The project is a CloudBase mini program and the auth question is about native mini program identity rather than provider configuration.

Read before writing code if

  • The request mentions mini program login, user identity in cloud functions, or wx.cloud auth assumptions.
  • The user expects a Web-style login page or explicit token exchange in a mini program; route them back to native mini program auth behavior.

Then also read

  • Mini program project implementation -> ../miniprogram-development/SKILL.md
  • Cloud function implementation -> ../cloud-functions/SKILL.md

Do NOT use for

  • Web-based WeChat login or Web auth UI.
  • Provider enable/disable or auth console setup.
  • Generic Node-side auth flows outside mini program identity handling.

Common mistakes / gotchas

  • Generating a Web-style login page for a wx.cloud mini program.
  • Treating mini program auth as a provider-configuration problem.
  • Forgetting that caller identity is injected in cloud functions automatically.

When to use this skill

Use this skill for WeChat Mini Program (小程序) authentication in a CloudBase project.

Use it when you need to:

  • Implement identity-aware WeChat Mini Program flows 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 auth-web skill)
  • Server-side auth with Node SDK (use the auth-nodejs skill)
  • Non-WeChat authentication methods (use appropriate auth skills)

How to use this skill (for a coding 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

Core concepts

How WeChat Mini Program authentication works with 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

Scenarios – WeChat Mini Program auth patterns

Scenario 1: Initialize CloudBase in Mini Program

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:

  • 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)

Scenario 2: Get user identity in a cloud function

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:

  • 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)

Scenario 3: Call cloud function from Mini Program

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:

  • 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

Scenario 4: Test authentication - Simple test function

Cloud 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:

  • 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

Best practices

1. Always use cloud.DYNAMIC_CURRENT_ENV

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

This ensures the cloud function uses the correct environment automatically.

2. Store OPENID for user identification

  • Use OPENID as the primary user identifier
  • Store it in your database to associate data with users
  • Never expose OPENID to other users

3. Handle UNIONID availability

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 o

---

*Content truncated.*

spec-workflow

TencentCloudBase

Standard software engineering workflow for requirement analysis, technical design, and task planning. Use this skill when developing new features, complex architecture designs, multi-module integrations, or projects involving database/UI design.

773

auth-web-cloudbase

TencentCloudBase

CloudBase Web Authentication Quick Guide - Provides concise and practical Web frontend authentication solutions with multiple login methods and complete user management.

30

ai-model-nodejs

TencentCloudBase

Use this skill when developing Node.js backend services or CloudBase cloud functions (Express/Koa/NestJS, serverless, backend APIs) that need AI capabilities. Features text generation (generateText), streaming (streamText), AND image generation (generateImage) via @cloudbase/node-sdk ≥3.16.0. Built-in models include Hunyuan (hunyuan-2.0-instruct-20251111 recommended), DeepSeek (deepseek-v3.2 recommended), and hunyuan-image for images. This is the ONLY SDK that supports image generation. NOT for browser/Web apps (use ai-model-web) or WeChat Mini Program (use ai-model-wechat).

00

cloud-functions

TencentCloudBase

Complete guide for CloudBase cloud functions development - runtime selection, deployment, logging, invocation, and HTTP access configuration.

00

data-model-creation

TencentCloudBase

Optional advanced tool for complex data modeling. For simple table creation, use relational-database-tool directly with SQL statements.

00

cloudbase-document-database-in-wechat-miniprogram

TencentCloudBase

Use CloudBase document database WeChat MiniProgram SDK to query, create, update, and delete data. Supports complex queries, pagination, aggregation, and geolocation queries.

20

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

641968

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

590705

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

338397

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

318395

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

450339

fastapi-templates

wshobson

Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.

304231

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.