微信小游戏 (Cocos) 快速开始
准备工作
在开始之前,请确保您已完成以下准备:
更多详情请参考:微信小游戏 (Cocos) 完整文档
添加 CloudBase AI 开发插件
可选:如果你使用 AI 编程助手(如 Cursor、Claude Code、CodeBuddy 等)进行开发,建议先完成本步骤,让 AI 具备 CloudBase 开发能力。
复制 AI Prompt 粘贴到 AI IDE
在 AI 对话中输入:
帮我把 CloudBase 接好,按下面做:
1. 打开 https://docs.cloudbase.net/skill.md,按说明完成接入。
2. 接入完成后告诉我,并建议最相关的下一步。
使用 Skills 开发
对 AI 说:
使用 CloudBase Skills:在微信小游戏 (Cocos)中集成云开发,包括数据库和云存储功能
也可以手动安装 CloudBase Skills:
npx skills add tencentcloudbase/cloudbase-skills -y
安装 SDK
@cloudbase/js-sdk 配合 @cloudbase/adapter-cocos_native 可以让您在 Cocos 项目中访问 CloudBase 服务和资源。
npm
npm i @cloudbase/js-sdk @cloudbase/adapter-cocos_native
yarn
yarn add @cloudbase/js-sdk @cloudbase/adapter-cocos_native
pnpm
pnpm add @cloudbase/js-sdk @cloudbase/adapter-cocos_native
初始化 SDK
新增如下代码到您的 Cocos 项目
scripts/services/CloudbaseService.js
import cloudbaseSDK from "@cloudbase/js-sdk";
import adapter from "@cloudbase/adapter-cocos_native";
// 注册适配器
cloudbaseSDK.useAdapters(adapter);
const cloudbase = cloudbaseSDK.init({
// 环境 ID
env: "{%ENV_ID%}",
// 地域
region: "{%REGION%}",
// 匿名访问令牌
accessKey: "{%PUBLISHABLE_KEY%}"
});
export default cloudbase;
身份认证
- 短信验证码注册
- 邮箱验证码注册
- 账号密码登录
- 短信验证码登录
- 邮箱验证码登录
- 匿名登录
使用 短信验证码注册 请先前往 身份认证/登录方式 开启 短信验证码
调用方式:
import cloudbase from "./services/CloudbaseService";
const auth = cloudbase.auth();
// 发送验证码
const res = await auth.getVerification({ phone_number: phone });
const verificationId = res.verification_id;
// 验证验证码
const verifyRes = await auth.verify({
verification_id: verificationId,
verification_code: code
});
// 注册
await auth.signUp({
phone_number: `+86 ${phone}`,
verification_code: code,
verification_token: verifyRes.verification_token,
name: `user_${phone.slice(-4)}`,
password: "admin@123"
});
完整示例:
import { _decorator, Component, Node, EditBox, Label } from 'cc';
import cloudbase from './services/CloudbaseService';
const { ccclass, property } = _decorator;
@ccclass('SmsRegister')
export class SmsRegister extends Component {
@property(EditBox)
phoneInput: EditBox = null;
@property(EditBox)
codeInput: EditBox = null;
@property(Label)
messageLabel: Label = null;
private verificationId: string = '';
// 发送验证码
async onSendCodeButtonClick() {
const phone = this.phoneInput.string;
if (!phone) {
this.messageLabel.string = '请输入手机号';
return;
}
try {
const auth = cloudbase.auth();
const res = await auth.getVerification({ phone_number: phone });
this.verificationId = res.verification_id;
this.messageLabel.string = '验证码已发送!';
} catch (error) {
this.messageLabel.string = `发送失败: ${error.message}`;
}
}
// 注册
async onRegisterButtonClick() {
const phone = this.phoneInput.string;
const code = this.codeInput.string;
if (!this.verificationId || !code) {
this.messageLabel.string = '请先发送验证码';
return;
}
try {
const auth = cloudbase.auth();
// 验证验证码
const verifyRes = await auth.verify({
verification_id: this.verificationId,
verification_code: code,
});
// 注册(如用户已存在则自动登录)
await auth.signUp({
phone_number: `+86 ${phone}`,
verification_code: code,
verification_token: verifyRes.verification_token,
name: `user_${phone.slice(-4)}`,
password: "admin@123"
});
this.messageLabel.string = '注册成功!';
console.log('注册成功');
} catch (error) {
this.messageLabel.string = `注册失败: ${error.message}`;
console.error('注册失败:', error);
}
}
}
使用 邮箱验证码注册 请先前往 身份认证/登录方式 开启 邮箱验证码
调用方式:
import cloudbase from "./services/CloudbaseService";
const auth = cloudbase.auth();
// 发送验证码
const res = await auth.getVerification({ email });
const verificationId = res.verification_id;
// 验证验证码
const verifyRes = await auth.verify({
verification_id: verificationId,
verification_code: code
});
// 注册
await auth.signUp({
email,
verification_code: code,
verification_token: verifyRes.verification_token,
name: `user_${email.slice(-4)}`,
password: "admin@123"
});
完整示例:
import { _decorator, Component, Node, EditBox, Label } from 'cc';
import cloudbase from './services/CloudbaseService';
const { ccclass, property } = _decorator;
@ccclass('EmailRegister')
export class EmailRegister extends Component {
@property(EditBox)
emailInput: EditBox = null;
@property(EditBox)
codeInput: EditBox = null;
@property(Label)
messageLabel: Label = null;
private verificationId: string = '';
// 发送验证码
async onSendCodeButtonClick() {
const email = this.emailInput.string;
if (!email) {
this.messageLabel.string = '请输入邮箱';
return;
}
try {
const auth = cloudbase.auth();
const res = await auth.getVerification({ email });
this.verificationId = res.verification_id;
this.messageLabel.string = '验证码已发送!';
} catch (error) {
this.messageLabel.string = `发送失败: ${error.message}`;
}
}
// 注册
async onRegisterButtonClick() {
const email = this.emailInput.string;
const code = this.codeInput.string;
if (!this.verificationId || !code) {
this.messageLabel.string = '请先发送验证码';
return;
}
try {
const auth = cloudbase.auth();
// 验证验证码
const verifyRes = await auth.verify({
verification_id: this.verificationId,
verification_code: code,
});
// 注册(如用户已存在则自动登录)
await auth.signUp({
email,
verification_code: code,
verification_token: verifyRes.verification_token,
name: `user_${email.slice(-4)}`,
password: "admin@123"
});
this.messageLabel.string = '注册成功!';
console.log('注册成功');
} catch (error) {
this.messageLabel.string = `注册失败: ${error.message}`;
console.error('注册失败:', error);
}
}
}
使用 账号密码登录 请先前往 身份认证/登录方式 开启 用户名密码登录
调用方式:
import cloudbase from "./services/CloudbaseService";
const auth = cloudbase.auth();
await auth.signIn({
username, // 可以是用户名、手机号或邮箱
password
});
完整示例:
import { _decorator, Component, Node, EditBox, Label } from 'cc';
import cloudbase from './services/CloudbaseService';
const { ccclass, property } = _decorator;
@ccclass('PasswordLogin')
export class PasswordLogin extends Component {
@property(EditBox)
usernameInput: EditBox = null;
@property(EditBox)
passwordInput: EditBox = null;
@property(Label)
messageLabel: Label = null;
async onLoginButtonClick() {
const username = this.usernameInput.string;
const password = this.passwordInput.string;
if (!username || !password) {
this.messageLabel.string = '请输入账号和密码';
return;
}
try {
const auth = cloudbase.auth();
await auth.signIn({
username, // 可以是用户名、手机号或邮箱
password,
});
this.messageLabel.string = '登录成功!';
console.log('登录成功');
} catch (error) {
this.messageLabel.string = `登录失败: ${error.message}`;
console.error('登录失败:', error);
}
}
}
使用 短信验证码登录 请先前往 身份认证/登录方式 开启 短信验证码登录
调用方式:
import cloudbase from "./services/CloudbaseService";
const auth = cloudbase.auth();
// 发送验证码
const res = await auth.getVerification({ phone_number: `+86 ${phone}` });
const verificationInfo = res;
// 登录
await auth.signInWithSms({
verificationInfo: verificationInfo,
verificationCode: code,
phoneNum: `+86 ${phone}`
});
完整示例:
import { _decorator, Component, Node, EditBox, Label } from 'cc';
import cloudbase from './services/CloudbaseService';
const { ccclass, property } = _decorator;
@ccclass('SmsLogin')
export class SmsLogin extends Component {
@property(EditBox)
phoneInput: EditBox = null;
@property(EditBox)
codeInput: EditBox = null;
@property(Label)
messageLabel: Label = null;
private verificationInfo: any = null;
// 发送验证码
async onSendCodeButtonClick() {
const phone = this.phoneInput.string;
if (!phone) {
this.messageLabel.string = '请输入手机号';
return;
}
try {
const auth = cloudbase.auth();
const res = await auth.getVerification({ phone_number: `+86 ${phone}` });
this.verificationInfo = res;
this.messageLabel.string = '验证码已发送!';
} catch (error) {
this.messageLabel.string = `发送失败: ${error.message}`;
}
}
// 登录
async onLoginButtonClick() {
const phone = this.phoneInput.string;
const code = this.codeInput.string;
if (!this.verificationInfo || !code) {
this.messageLabel.string = '请先发送验证码';
return;
}
try {
const auth = cloudbase.auth();
await auth.signInWithSms({
verificationInfo: this.verificationInfo,
verificationCode: code,
phoneNum: `+86 ${phone}`
});
this.messageLabel.string = '登录成功!';
console.log('登录成功');
} catch (error) {
this.messageLabel.string = `登录失败: ${error.message}`;
console.error('登录失败:', error);
}
}
}
使用 邮箱验证码登录 请先前往 身份认证/登录方式 开启 邮箱验证码
调用方式:
import cloudbase from "./services/CloudbaseService";
const auth = cloudbase.auth();
// 发送验证码
const res = await auth.getVerification({ email });
const verificationInfo = res;
// 登录
await auth.signInWithEmail({
verificationInfo: verificationInfo,
verificationCode: code,
email
});
完整示例:
import { _decorator, Component, Node, EditBox, Label } from 'cc';
import cloudbase from './services/CloudbaseService';
const { ccclass, property } = _decorator;
@ccclass('EmailLogin')
export class EmailLogin extends Component {
@property(EditBox)
emailInput: EditBox = null;
@property(EditBox)
codeInput: EditBox = null;
@property(Label)
messageLabel: Label = null;
private verificationInfo: any = null;
// 发送验证码
async onSendCodeButtonClick() {
const email = this.emailInput.string;
if (!email) {
this.messageLabel.string = '请输入邮箱';
return;
}
try {
const auth = cloudbase.auth();
const res = await auth.getVerification({ email });
this.verificationInfo = res;
this.messageLabel.string = '验证码已发送!';
} catch (error) {
this.messageLabel.string = `发送失败: ${error.message}`;
}
}
// 登录
async onLoginButtonClick() {
const email = this.emailInput.string;
const code = this.codeInput.string;
if (!this.verificationInfo || !code) {
this.messageLabel.string = '请先发送验证码';
return;
}
try {
const auth = cloudbase.auth();
await auth.signInWithEmail({
verificationInfo: this.verificationInfo,
verificationCode: code,
email
});
this.messageLabel.string = '登录成功!';
console.log('登录成功');
} catch (error) {
this.messageLabel.string = `登录失败: ${error.message}`;
console.error('登录失败:', error);
}
}
}
调用方式:
import cloudbase from "./services/CloudbaseService";
const auth = cloudbase.auth();
await auth.signInAnonymously();
完整示例:
import { _decorator, Component, Node, Label } from 'cc';
import cloudbase from './services/CloudbaseService';
const { ccclass, property } = _decorator;
@ccclass('AnonymousLogin')
export class AnonymousLogin extends Component {
@property(Label)
messageLabel: Label = null;
async onLoginButtonClick() {
try {
const auth = cloudbase.auth();
await auth.signInAnonymously();
this.messageLabel.string = '匿名登录成功!';
console.log('匿名登录成功');
} catch (error) {
this.messageLabel.string = `登录失败: ${error.message}`;
console.error('登录失败:', error);
}
}
}
文档型数据库
- 查询数据
- 新增数据
- 更新数据
- 删除数据
调用方式:
import cloudbase from "./services/CloudbaseService";
const db = cloudbase.database();
const res = await db.collection("{%TABLE_NAME%}").limit(10).get();
完整示例:
import { _decorator, Component, Node, Label } from 'cc';
import cloudbase from './services/CloudbaseService';
const { ccclass, property } = _decorator;
@ccclass('QueryDocData')
export class QueryDocData extends Component {
@property(Label)
resultLabel: Label = null;
async onLoad() {
try {
const db = cloudbase.database();
const res = await db.collection("{%TABLE_NAME%}").limit(10).get();
this.resultLabel.string = `查询成功:${JSON.stringify(res.data)}`;
console.log('查询结果:', res.data);
} catch (error) {
this.resultLabel.string = `查询失败: ${error.message}`;
console.error('查询失败:', error);
}
}
}
调用方式:
import cloudbase from "./services/CloudbaseService";
const db = cloudbase.database();
const res = await db.collection("{%TABLE_NAME%}").add({ title: "示例标题" });
完整示例:
import { _decorator, Component, Node, EditBox, Label } from 'cc';
import cloudbase from './services/CloudbaseService';
const { ccclass, property } = _decorator;
@ccclass('AddDocData')
export class AddDocData extends Component {
@property(EditBox)
titleInput: EditBox = null;
@property(Label)
resultLabel: Label = null;
async onAddButtonClick() {
const title = this.titleInput.string;
if (!title) {
this.resultLabel.string = '请输入标题';
return;
}
try {
const db = cloudbase.database();
const res = await db.collection("{%TABLE_NAME%}").add({ title });
this.resultLabel.string = `新增成功! id: ${res.id}`;
this.titleInput.string = '';
console.log('新增成功:', res);
} catch (error) {
this.resultLabel.string = `新增失败: ${error.message}`;
console.error('新增失败:', error);
}
}
}
调用方式:
import cloudbase from "./services/CloudbaseService";
const db = cloudbase.database();
await db.collection("{%TABLE_NAME%}").doc(dataId).update({ title: "新标题" });
完整示例:
import { _decorator, Component, Node, EditBox, Label } from 'cc';
import cloudbase from './services/CloudbaseService';
const { ccclass, property } = _decorator;
@ccclass('UpdateDocData')
export class UpdateDocData extends Component {
@property(EditBox)
idInput: EditBox = null;
@property(EditBox)
titleInput: EditBox = null;
@property(Label)
resultLabel: Label = null;
async onUpdateButtonClick() {
const dataId = this.idInput.string;
const newTitle = this.titleInput.string;
if (!dataId || !newTitle) {
this.resultLabel.string = '请输入数据ID和新标题';
return;
}
try {
const db = cloudbase.database();
await db.collection("{%TABLE_NAME%}").doc(dataId).update({ title: newTitle });
this.resultLabel.string = '更新成功';
this.idInput.string = '';
this.titleInput.string = '';
console.log('更新成功');
} catch (error) {
this.resultLabel.string = `更新失败: ${error.message}`;
console.error('更新失败:', error);
}
}
}
调用方式:
import cloudbase from "./services/CloudbaseService";
const db = cloudbase.database();
await db.collection("{%TABLE_NAME%}").doc(dataId).remove();
完整示例:
import { _decorator, Component, Node, EditBox, Label } from 'cc';
import cloudbase from './services/CloudbaseService';
const { ccclass, property } = _decorator;
@ccclass('DeleteDocData')
export class DeleteDocData extends Component {
@property(EditBox)
idInput: EditBox = null;
@property(Label)
resultLabel: Label = null;
async onDeleteButtonClick() {
const dataId = this.idInput.string;
if (!dataId) {
this.resultLabel.string = '请输入要删除的数据ID';
return;
}
try {
const db = cloudbase.database();
await db.collection("{%TABLE_NAME%}").doc(dataId).remove();
this.resultLabel.string = '删除成功';
this.idInput.string = '';
console.log('删除成功');
} catch (error) {
this.resultLabel.string = `删除失败: ${error.message}`;
console.error('删除失败:', error);
}
}
}
云存储
- 上传文件
- 获取文件链接