cocos creator 3.7 WeChat small game development cloud function and cloud hosting deployment

      Cocos Creator has a good ability to develop cross-platform games. It can be developed for multiple platforms at one time, such as andriod, ios native, web pages, various small programs, etc. As far as the actual situation is concerned, it is not easy to be able to cross 1 or 2 platforms. This is because in cross-platform development, there are inevitable parts that need to be customized for specific platforms. If there are too many, the workload of platform maintenance will be too large. . As far as WeChat mini-games are concerned, it is usually necessary to consider whether to use WeChat’s built-in cloud functions or cloud hosting. Otherwise, you can only build your own server, which has many restrictions, such as: must be filed, domain name, certificate, etc. For personal development It is too long-winded for readers, and it takes too much energy to maintain it. Let's compare the two:

1. Application Architecture

    The same thing between the two is serverless, that is, serverless architecture. Users do not need to build their own servers, do not need to maintain themselves, and even do not need to worry too much about the security part. WeChat basically takes it into account, which saves time and cost for enterprises and individuals. . But there are still differences:

1. Deployment method

The cloud function uses node.js as the server and js as the development language. The deployment method is to synchronize the cloud function to the cloud; but the cloud hosting is different, it is to create a docker image by itself, and then publish it to the cloud, which does not limit your use The server environment and development language are more flexible.

2. Access port

Cloud functions do not involve this problem, just access them directly according to the function name and environment parameters; cloud hosting will have ports in the service image you develop yourself, and you can set the corresponding relationship in the cloud hosting parameters, so that the cloud will automatically link to your service port , the client access is similar to the network method, using the callContainer of WeChat, the parameters are path, method, header and data, but there are no parameters such as port. In this part, cloud functions are simpler, and cloud hosting is more complete (users can operate more).

3. Value-added services

This part of the content is similar to the two, including databases, object storage, resource monitoring, static websites, etc.; but the two are independent of each other and are in their own environments. Generally speaking, they need to be deployed separately.

2. Deployment process

1. Cloud function deployment

1. Enter the WeChat developer tool, select "Cloud Development" in the left menu bar, and enter the cloud development console.

2. In the cloud development console, select the "Cloud Function" tab, and click "New Cloud Function".

 3. On the new cloud function page, fill in the corresponding information, including the name of the cloud function, operating environment, execution method, etc.

4. Create and edit cloud function code locally. Create a cloud function directory (such as cloud) in WeChat developer tools

Then edit the project.config.json file to add the root directory of the cloud function


Right-click the cloud directory to create a cloud function with the same name, such as test 

 

 WeChat developer tools will automatically create default cloud function files

 Edit the function code by yourself, right click and upload after completion.

 5. Test the cloud function. You can use the local and cloud testing tools provided by the cloud development console to test whether the cloud function is running normally.

2. Cloud hosting deployment

1. Website deployment

Cloud hosting deployment is relatively free, one way to choose website deployment,

Log in to the website WeChat cloud hosting , scan the code and log in, select the service list, create if there is no

 You can deploy templates and create services, and choose to deploy and publish after completion

 You can choose from the mirror, and the port is determined according to the port number of your service.

2. docker file command line deployment

This method is more practical and flexible. Taking creating a hello world as an example, the following steps are introduced:

1) Build your own development environment and install it with npm

mkdir test
cd test
npm init -y

2) Install typesript, node.js and express

npm install node --save
npm install express --save
npm install @types/express --save
npm ls

3) Write hello world code, create and edit index.ts

import express, { Application } from 'express';
export class Test {
	private app: Application = express();
	constructor() {
		// 允许跨域
		this.app.all('*', function (req, res, next) {
			res.header("Access-Control-Allow-Origin", req.headers.origin);
			res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
			res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
			res.header("Access-Control-Allow-Credentials", "true");
			if (req.method === "OPTIONS") res.sendStatus(200);/*让options请求快速返回*/
			else next();
		});
        this.app.use(express.json());
		this.app.get('/', function (req, res) {
			res.send('Hello World');
			console.log("Hello World!");
		});

		let server = this.app.listen(8080, function () {
			let host = server.address();
			console.log("应用实例访问地址为 %s", host)
		});
	}

};
export const test: Test = new Test();

4) Edit the package.json file

{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "index.ts",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "./node_modules/.bin/ts-node ./index.ts"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@types/express": "^4.17.17",
    "express": "^4.18.2",
    "ts-node": "^10.9.1"
  }
}

In fact, the main thing is to add the start line and run:

npm run start

5) Use curl to access the test to see if it is successful

curl 127.0.0.1:8080

 The hello world appears to indicate success! At this point, the hello world node.js service built by my own typescript is completed.

6) Install cloud hosting cli

First of all, we need to install WeChat's cloud hosting cli, which is the command line tool

npm i -g @wxcloud/cli

If the permissions are insufficient, use sudo to obtain permissions

sudo npm i -g @wxcloud/cli

7) Set the key

The command line access must use the key of WeChat. The key is set in the WeChat cloud hosting platform--settings--global settings--cli key, click "generate key", remember to copy and save in time, WeChat cloud hosting does not Responsible for storage, if forgotten or lost, it can only be regenerated once.

 8) Log in to the command line

In the project directory, enter the command line and enter:

wxcloud login --appId <微信 AppId> --privateKey <秘钥>

For appId, use the appid of your own game. In the upper right corner of the cloud hosting, click your icon to see it; use the key you just generated for the key. After successful login, you can proceed to the next step.

9) Create a WeChat cloud hosting environment , execute migrate in the project directory, and press Enter to generate the default dockerfile.

wxcloud migrate
# 由 Dockerpacks 自动生成
# 本 Dockerfile 可能不能完全覆盖您的项目需求,若遇到问题请根据实际情况修改或询问客服

# 使用基于 alpine 的 node 官方镜像
FROM node:lts-alpine

# 设置容器内的当前目录
WORKDIR /app

# 使用速度更快的国内镜像源
RUN npm config set registry https://registry.npmmirror.com

# 将这些文件拷贝到容器中
COPY package.json package-lock.json ./

# 安装依赖
RUN npm ci

#安装curl方便调试
RUN apk add curl

# 将包括源文件在内的所有文件拷贝到容器中(在 .dockerignore 中的文件除外)
COPY . .

# 设置环境变量
ENV NODE_ENV=production HOST=0.0.0.0

# 运行项目
CMD ["npm", "run", "start"]

# 服务暴露的端口
EXPOSE 8080

10) Create a service

Before the official deployment, you should create your own service on the WeChat Cloud Hosting web page, WeChat Cloud Hosting--Service Management--Service List--Create Service, enter the name, and set the relevant parameters. (Note that it does not need to be deployed directly on the web page, just create a service name, if you need to set the container parameters, you can set it in the service settings.

11) Command line release

Execute the command wxcloud deploy in the project directory, follow the prompts, and pay attention to select the correct service name.

pjxxlpsj@pj-MAC test % wxcloud deploy
Wxcloud CLI 2.1.2
? 请选择环境 prod (prod-xxxxxxx)
? 请选择服务 test
请输入端口号(大部分前端框架端口号为 3000,官方模板为 80) [3000]: 8080
ℹ 部署模式 云托管
读取到 .dockerignore, 将忽略其中的文件
[
  '.git',
  '.gitignore',
  '.dockerignore',
  '**/LICENSE',
  '**/LICENSE/**',
  '*.md',
  '**/node_modules',
  '**/node_modules/**'
]
✔ 打包云托管产物
✔ 云托管产物上传成功
✔ 云托管 版本创建成功

After about a few minutes, the upgrade release is successful! That's it for a complete cloud-hosted deployment, but what if the test was deployed correctly? You can test in the cloud on the cloud hosting webpage, set the parameters, and if the hello world is fed back, it proves that the service is running normally.

3. cocos creator main points

 In the development of cocos creator, because wechat publishing is to compile the typescript code and publish it to the wechat directory of build, because the code is dynamically converted from typescript to js code, you need to pay attention to:

1. Every time the code is modified and rebuilt, the code directory published to the WeChat developer tool will be rewritten, and the local code of the cloud function will disappear. Therefore, in principle, it is not appropriate to put the original code in the build directory. Instead, copy should be used.

2. Due to the size limit of the WeChat mini-program package, sub-package processing is generally necessary (as described in my previous article). After testing, the speed of using the sub-package solution is extremely slow, and the waiting time is more than 20 seconds when the total program size is about 10m. Therefore, It is recommended to adopt the main package + remote package solution, deploy the remote package to the static website, and solve the problem in a few seconds.

3. Cocos creator accesses cloud functions and cloud hosting

After the access code is created, you need to pay attention to building and publishing it to the WeChat mini game in cocos creator, and then testing and debugging in the WeChat developer tool. See my previous article for details.

1. Cloud function access

The main thing is to pay attention to judging the current environment. Only in the WeChat environment can the wx code be called. The specific examples are as follows:

if (sys.platform === "WECHAT_GAME") {
			//微信小游戏环境下才执行
			//第1次运行需要初始化
			if (!this.isWxInit) {
    			wx.cloud.init({env:'xxxxxxxxx'});
				this.isWxInit = true;
			}
			//云函数调用
			let cloudData = {'command': path,
  			'body': JSON.parse(data)};
			wx.cloud.callFunction({
					// 要调用的云函数名称
					name: 'test',
					// 传递给云函数的event参数
					data: cloudData
				  }).then((res: any) => {
					console.log(res);
					if (successCallback != null) {
						successCallback( {'data':res.result});
						console.log({'data':res.result});
					}
				  }).catch((err: any) => {
					// handle error
					if (errorCallBack != null) {
						errorCallBack(err);
					}
				  });
			}
}

2. Cloud hosted access

The access methods are similar, but the specific function names are different.

if (sys.platform === "WECHAT_GAME") {
			//微信小游戏环境下才执行
			//第1次运行需要初始化
			if (!this.isWxInit) {
				wx.cloud.init({env:'xxxxxxxxx'});
				this.isWxInit = true;
			}
			//云托管
				wx.cloud.callContainer({
					config: {
						env: 'xxxxxxxx', // 微信云托管的环境ID
					},
					path: '/' + path, // 填入业务自定义路径和参数,根目录,就是 / 
					method: 'GET', // 按照自己的业务开发,选择对应的方法
					header: {
						"X-WX-SERVICE": "test", // 填入服务名称
						"content-type": "application/json"
						// 其他 header 参数
					},
					data: data,
					success: (res: any) => {
						if (successCallback != null) {
							successCallback(res);
						}
					},
					fail: (err: any) => {
						if (errorCallBack != null) {
							errorCallBack(err);
						}
					}
				});
		}

 4. Cost comparison

Cloud Function has a monthly subscription package, basically 20 yuan/month, including various visits. For general applications, the quantity is enough, if not enough, it can only be billed by access. Cloud hosting gives users a lot of space, and they can freely adjust the parameters of cloud deployment, such as cpu memory, multiple instances, etc., but the cost is also increasing sequentially.

Generally speaking, the cost of cloud functions is lower, which is more suitable for individuals and small businesses; cloud hosting provides more flexibility, and may have more choices for enterprises.

5. Others                       

1. The cloud function adopts typescript problem

Because all game codes are typescript, it is natural to hope that all codes are typescript, so that readability and maintenance will be easier. If cloud hosting is okay, it can be seen from the above example that there is no problem at all; for cloud functions In other words, it seems that only js code is supported, so how to solve it? A feasible idea is to use typescript to edit locally. After the completion, the ts code is automatically compiled into js code by compilation, and copied to the WeChat developer directory, and the developer submits it to the cloud.

1) Create a project directory and initialize the cloud function project.

mkdir test
cd test
npm init -y
npm install typescript  --save
npm install ts-node --save

2) Writing cloud functions

Here is the simplest hello world example.

import  ICloudService  from 'wx-server-sdk';

ICloudService.init();
export async function main(event: any, context: any) {
	console.log(event);
    return "hello world!"
}

3) Edit tsconfig.json

The most important thing is to select the output directory, just replace it with your own WeChat developer tool directory.

{
	"compilerOptions": {
	 "target": "es2016",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
	  "module": "commonjs",                                /* Specify what module code is generated. */
	   "outDir": "../build/xxxx/cloud/api",                /* 指定你的输出目录 */
	  "esModuleInterop": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
	  "forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. */
	  "allowSyntheticDefaultImports": true,
	  "strict": false,                                     /* Enable all strict type-checking options. */
	  "skipLibCheck": true                                 /* Skip type checking all .d.ts files. */
  
	},
	"include": [
	  "./**/*.ts"
	  ],
	  "exclude": [
	  "node_modules"
	  ]
  }
  

4) Compile and copy

npx tsc

You will see that the file is compiled into js code and copied to the specified directory, so that the goal of writing cloud functions in typescript can be achieved. How to submit to the server later see the instructions in the front of the article.

2. Cloud function debugging

Cloud function debugging can be tested locally and in the cloud. The local speed is fast, but it requires the installation of node.js environment in the directory; the cloud test represents the final result, but the speed is obviously slower. Each test will wait for more than 10 seconds , this is just a test speed, not the actual deployment speed. As can be seen in the figure below, the call is successful and returns "hello world!"

3. Cloud hosting billing pit

The flexibility of cloud hosting is very high, there are no restrictions on language and development tools, and there are even free quotas available, but it is easy to run out of resources after the actual opening, because in cloud hosting - service list - select service - service settings You can adjust container parameters such as cpu, memory, number of instances, etc. At the beginning, you did not pay attention to the issue of charging. It is easy to increase the parameters, and the resources will be exhausted quickly, and all resource access will be charged in the future.

On the other hand, the visits given away by cloud hosting are one-time! This needs to be repeatedly emphasized, because there is still a three-month deadline. It is easy for everyone to understand that there are so many visits or resource volumes every month, and I use up all the visits in a little more than a month, resulting in all subsequent visits. TOLL!

The resource statistics of cloud hosting are calculated on a monthly basis, so even if your quota has been used up, the statistics every other month still show that there is a lot of vacancy, which is easy for users to misunderstand and think that the resources are still sufficient. Therefore, we must pay attention to the actual access situation of resources, do what we can, and set parameters appropriately.

6. References

1. WeChat Cloud HostingWeChat  Cloud Hosting | WeChat Open Documentation

2. WeChat cloud function WeChat open document

3. cocos creator api manual CocosCreatorAPI

4. cocos creator user manual Introduction · Cocos Creator

5. Overview of WeChat Cloud Hosting Command Line | WeChat Cloud Hosting CLI

The following is my WeChat mini-game 24:00 Battle of the Century, everyone is welcome to download it.

Guess you like

Origin blog.csdn.net/a17432025/article/details/130386269