跳到主要内容

微信小游戏 (Cocos) 快速开始

准备工作

在开始之前,请确保您已完成以下准备:

  1. 开通云开发环境开通云开发环境
  2. 开发工具:下载并安装 微信开发者工具
  3. 小程序账号注册微信小程序,获取小程序的 AppID

更多详情请参考:微信小游戏 (Cocos) 完整文档

添加 CloudBase AI 开发插件

可选:如果你使用 AI 编程助手(如 Cursor、Claude Code、CodeBuddy 等)进行开发,建议先完成本步骤,让 AI 具备 CloudBase 开发能力。

复制 AI Prompt 粘贴到 AI IDE

在 AI 对话中输入:

帮我把 CloudBase 接好,按下面做:
1. 打开 https://docs.cloudbase.net/skill.md,按说明完成接入。
2. 接入完成后告诉我,并建议最相关的下一步。

查看 skill.md →

使用 Skills 开发

对 AI 说:

使用 CloudBase Skills:在微信小游戏 (Cocos)中集成云开发,包括数据库和云存储功能

Skills 使用文档 →

也可以手动安装 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 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 res = await cloudbase.uploadFile({
cloudPath: `images/${Date.now()}.png`,
filePath: filePath
});

完整示例:

import { _decorator, Component, Node, Label } from 'cc';
import cloudbase from './services/CloudbaseService';

const { ccclass, property } = _decorator;

@ccclass('UploadFile')
export class UploadFile extends Component {
@property(Label)
resultLabel: Label = null;

async onUploadButtonClick() {
try {
// 注意:实际使用中需要从用户选择或游戏资源中获取文件路径
const filePath = 'path/to/your/file.png';
const cloudPath = `images/${Date.now()}-${Math.random()}.png`;

const res = await cloudbase.uploadFile({
cloudPath: cloudPath,
filePath: filePath
});

this.resultLabel.string = `上传成功!文件ID: ${res.fileID}`;
console.log('上传成功:', res);
} catch (error) {
this.resultLabel.string = `上传失败: ${error.message}`;
console.error('上传失败:', error);
}
}
}

云函数

调用方式:

import cloudbase from "./services/CloudbaseService";

const res = await cloudbase.callFunction({
name: "{%FUNCTION_NAME%}",
data: {}
});

完整示例:

import { _decorator, Component, Node, Label } from 'cc';
import cloudbase from './services/CloudbaseService';

const { ccclass, property } = _decorator;

@ccclass('CallFunction')
export class CallFunction extends Component {
@property(Label)
resultLabel: Label = null;

async onCallButtonClick() {
try {
const res = await cloudbase.callFunction({
name: "{%FUNCTION_NAME%}",
data: {}
});

this.resultLabel.string = `调用成功:${JSON.stringify(res.result)}`;
console.log('调用结果:', res.result);
} catch (error) {
this.resultLabel.string = `调用失败: ${error.message}`;
console.error('调用失败:', error);
}
}
}

大模型

调用方式:

import cloudbase from "./services/CloudbaseService";

const ai = cloudbase.ai();
const model = ai.createModel("{%AI_MODEL_NAME%}");

// 确保已登录
const loginState = await cloudbase.auth().getLoginState();
if (!loginState) {
await cloudbase.auth().signInAnonymously();
}

const res = await model.streamText({
model: "{%AI_SUB_MODEL_NAME%}",
messages: [
{ role: "system", content: "系统提示词" },
{ role: "user", content: "用户输入" }
]
});

for await (let str of res.textStream) {
// 处理流式响应
}

完整示例:

import { _decorator, Component, Node, EditBox, Label } from 'cc';
import cloudbase from './services/CloudbaseService';

const { ccclass, property } = _decorator;

@ccclass('CallAIModel')
export class CallAIModel extends Component {
@property(EditBox)
inputBox: EditBox = null;

@property(Label)
resultLabel: Label = null;

@property(Label)
statusLabel: Label = null;

async onGenerateButtonClick() {
const input = this.inputBox.string;
if (!input) {
this.statusLabel.string = '请输入主题';
return;
}

this.statusLabel.string = '生成中...';
this.resultLabel.string = '';

try {
const ai = cloudbase.ai();
const model = ai.createModel("{%AI_MODEL_NAME%}");

// 确保已登录
const loginState = await cloudbase.auth().getLoginState();
if (!loginState) {
await cloudbase.auth().signInAnonymously();
}

const res = await model.streamText({
model: "{%AI_SUB_MODEL_NAME%}",
messages: [
{ role: "system", content: "请严格按照七言绝句或七言律诗的格律要求创作,平仄需符合规则,押韵要和谐自然,韵脚字需在同一韵部。" },
{ role: "user", content: input }
]
});

let fullText = '';
for await (let str of res.textStream) {
fullText += str;
this.resultLabel.string = fullText;
}

this.statusLabel.string = '生成完成';
console.log('生成完成:', fullText);
} catch (err) {
this.statusLabel.string = '生成失败';
this.resultLabel.string = `错误: ${err.message}`;
console.error('生成失败:', err);
}
}
}