Skip to main content

Authentication: WeChat Mini Program

Use CloudBase Auth for identity authentication in WeChat Mini Program

How to Use

See How to Use Skill for detailed usage.

Test the Skill

You can use the following prompts to test:

  • "Help me implement user login functionality using CloudBase Auth in WeChat Mini Program"
  • "Create a Mini Program application that supports WeChat login using CloudBase Auth"

Use AI to develop, integrate and manage authentication in mini programs

Installation and Viewing

To install all CloudBase Skills, execute:

npx skills add tencentcloudbase/cloudbase-skills

To install only the current Skill, execute:

npx skills add https://github.com/tencentcloudbase/skills --skill auth-wechat

View current Skill online: auth-wechat


Skill Rules Original Text

View SKILL.md Original
## Standalone Install Note

If this environment only installed the current skill, start from the CloudBase main entry and use the published `cloudbase/references/...` paths for sibling skills.

- CloudBase main entry: `https://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/SKILL.md`
- Current skill raw source: `https://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/references/auth-wechat/SKILL.md`

Keep local `references/...` paths for files that ship with the current skill directory. When this file points to a sibling skill such as `auth-tool` or `web-development`, use the standalone fallback URL shown next to that reference.

## Activation Contract

### Use this first when:

- The task is a WeChat Mini Program that uses `wx.cloud.auth()` or CloudBase Auth for login/registration.
- The Mini Program needs to know the current user identity or handle login state.

### Read before writing code if:

- The code runs inside WeChat Mini Program.
- The auth integration point is `wx.cloud.auth()`, not `@cloudbase/js-sdk` or `@cloudbase/node-sdk`.

### Then also read:

- Provider setup / publishable key -> `../auth-tool/SKILL.md` (standalone fallback: `https://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/references/auth-tool/SKILL.md`)
- Web login UI for cross-platform -> `../auth-web/SKILL.md` (standalone fallback: `https://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/references/auth-web/SKILL.md`)

### Do NOT use for:

- Web apps (use `auth-web`)
- Node.js backend or cloud functions (use `auth-nodejs`)
- Native App auth (use `auth-http-api`)

### Common mistakes / gotchas:

- Using `@cloudbase/js-sdk` imports in Mini Program code.
- Expecting the same API shape as Web SDK (`wx.cloud.auth().signIn()` vs `auth.signInWithPassword()`).
- Forgetting that Mini Program auth requires `wx.cloud.init()` before `wx.cloud.auth()`.
- Mixing Web SDK auth flow into Mini Program code.

## When to use this skill

Use this skill when the auth target is **WeChat Mini Program**, and you need to:

- Implement login/registration using CloudBase Auth in Mini Program
- Get current user identity and handle auth state
- Configure Mini Program auth provider settings

**Do NOT use for:**

- Web apps → use `auth-web`
- Node.js backend → use `auth-nodejs`
- Native Apps → use `auth-http-api`

---

## Initialization

In WeChat Mini Program, use `wx.cloud.auth()`:

```js
// In Mini Program Page or Component
wx.cloud.init({ env: 'your-env-id' })

const auth = wx.cloud.auth()

// Check current auth state
auth.getLoginState().then(res => {
console.log('Login state:', res)
}).catch(err => {
console.log('Not logged in')
})
```

**Important notes:**

- `wx.cloud.init()` must be called before `wx.cloud.auth()`
- User must be authenticated before accessing protected resources
- Get environment ID from CloudBase console

---

## Login Methods

**1. Anonymous Login**

```js
const auth = wx.cloud.auth()

auth.signInAnonymously().then(res => {
console.log('Anonymous login success:', res)
}).catch(err => {
console.error('Anonymous login failed:', err)
})
```

**2. WeChat Login**

```js
const auth = wx.cloud.auth()

// WeChat login is handled automatically when user calls wx.login()
// CloudBase Auth will link the WeChat identity

auth.signInWithWeChat().then(res => {
console.log('WeChat login success:', res)
}).catch(err => {
console.error('WeChat login failed:', err)
})
```

**3. Get User Info**

```js
const auth = wx.cloud.auth()

auth.getUserInfo().then(res => {
console.log('User info:', res.user)
// res.user.uid - CloudBase user ID
// res.user.email - email (if available)
// res.user.nickName - nickname (if available)
}).catch(err => {
console.error('Get user info failed:', err)
})
```

**4. Sign Out**

```js
const auth = wx.cloud.auth()

auth.signOut().then(() => {
console.log('Sign out success')
}).catch(err => {
console.error('Sign out failed:', err)
})
```

---

## Complete Example (Mini Program Page)

```js
// pages/index/index.js
Page({
data: {
isLoggedIn: false,
userInfo: null
},

onLoad() {
this.checkLoginState()
},

async checkLoginState() {
const auth = wx.cloud.auth()
try {
const res = await auth.getLoginState()
if (res && res.user) {
this.setData({
isLoggedIn: true,
userInfo: res.user
})
}
} catch (err) {
console.log('Not logged in')
}
},

async handleLogin() {
const auth = wx.cloud.auth()
try {
await auth.signInAnonymously()
this.checkLoginState()
} catch (err) {
console.error('Login failed:', err)
}
},

async handleLogout() {
const auth = wx.cloud.auth()
try {
await auth.signOut()
this.setData({
isLoggedIn: false,
userInfo: null
})
} catch (err) {
console.error('Logout failed:', err)
}
}
})
```

---

## Best Practices

1. **Check login state on page load** - Verify auth state before rendering protected content
2. **Handle errors gracefully** - Wrap auth calls in try/catch
3. **Use anonymous login first** - Let users try the app before requiring registration
4. **Link identities** - Link WeChat identity to other login methods for flexibility
5. **Store user data securely** - Use CloudBase database to store user profiles