Integration of Huawei IAP Kit in Cocos - Huawei Developers

Introduction:
In this article, we will cover the Integration of IAP kit in Cocos Project using Official Plugin (Huawei HMS Core App Services).
Requirements:
1. Cocos Creator
Make sure to configure NDK Root and Android SDK Root in Cocos Creator under File>Settings>Select Native Develop.
2. Huawei device
3. Visual Studio Code
Follow the steps.
Step 1. Create Cocos project.
· Click on CocosDashboard, click New.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
· Select empty Name and then click Create and Open.  
 Step 2: Enable Cocos SDKHub
  Choose Panel > Service in the menu bar to open the Service panel. After setting Cocos AppID, select Cocos SDKHub to enter the Cocos SDKHub service panel.
 Click the Enable button on the upper right to activate the Cocos SDKHub service, as shown below.
 Click on IAP option to enable IAP, as shown below.
  Step 3: Create an app in Huawei AppGallery Connect.
1. Configure IAP in Huawei AGC Console and place agconnect-services.json file in game project under setting folder.
2. Choose Project settings > Manage APIs, and enable In-App Purchases.
· Configure IAP products in AGC Console.
Step 4: Open Cocos creator.
1. Right-click on the assets folder and select Scene under File and name it. This file will contain all information inside your scene.
2. Right-click on the assets folder and select JavaScript under File and name it. This file will contain functions to perform some operation.
Step 5: Open the IapScript file and add a function to call the equivalent method of createPurchaseIntent() of java in Cocos and save the file. Use the below code.
Code:
payForProduct() {
var params = {
Product_Id: "product_id", // Product ID. Each product must have a unique ID
EXT: "Cocos Consumables Product 1", //Information stored on the merchant side, which is passed by the app when the payment API is called
};
sdkhub.getFeePlugin().feeForProduct(params);
},
Add below code inside onLoad() function. Call to the above function will give a callback to onFeeResult method that we need to define in the IapScript file.
Code:
onLoad(){
sdkhub.getFeePlugin().setListener(this.onFeeResult, this);
},
Step 6: Drag a Button from the Node Library panel to canvas and increase the Click Events to 1.
Step 7: Drag the script file to the Node tree.
Step 8: Select the button and drag the script file from the Node tree to cc.Node under Properties and select function which needs to be called from the script file.
Step 9: Once the product is purchased, they need to be consumed after that consumable product is successfully delivered.
  When sdkhub.getFeePlugin().feeForProduct(params) is called gives a callback to onFeeResult.
Code:
onFeeResult: function (code, msg) {
if (code == 30104) {
console.log("Product consumed - "+ msg) // product consumed successfully
}
var params = JSON.parse(msg);
switch (code) {
// Process the "consumeOwnedPurchase" method logic, pay succeed
case sdkhub.FeeResultCode.kFeeSucceed:
sdkhub.getFeePlugin().callFuncWithParam("consumeOwnedPurchase", params.inAppPurchaseData); // consume Owned product Purchase
break;
}
},
Step 10: Click on Build under the Project tab to generate APK file. Build project, and then click Compile. Once code compile is done, click Play to run APK on connected phone.
Make sure to keep the same package name as kept in the Huawei AppGallery Connect project.
Conclusion:
In-app purchases are one of the main sources of revenue for game apps and is a very important feature that aggregates global mainstream payment methods, covering more than 178 countries and regions. In-app purchase provides a product management system (PMS) for managing the prices and languages of products in apps (including gaming apps) in multiple locations.
References:
https://docs.cocos.com/creator/manual/en/cocos-service/sdkhub-plugins/sdkhub-hms.html
https://developer.huawei.com/consumer/en/hms/huawei-iap/

Can the public payment key be exposed on the app?

Related

Huawei Wallet Kit -Server Side Tickets and All-in-one pass Creation

This is originally from HUAWEI Developer Forum
Forum link: https://forums.developer.huawei.com/forumPortal/en/home​
Introduction
HUAWEI Wallet Kit providing users to claim passes of merchants, like loyalty cards, gift cards, coupons, boarding passes, event tickets, and transit passes. It provides easy-to-access digital passes on an integrated platform. It enables user save their cards into mobile phones for convenient. The interaction between apps and users via location based notifications.
Integration Process.
The Wallet Kit integration process consists following steps
1. Generating Public and Private Keys
2. Adding Pass type on the AGC
3. Running the Server Demo code
4. Running the Client Demo code
5. View card adding status
Step-1: Check Below Link to generate keys & App Configuration in AGC:
LINK: https://forums.developer.huawei.com...d=0201242460338530108&fid=0101187876626530001
· Let’s see how to apply new wallet.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
· Now will see how to create Flight ticket.
· Service type consists 3 types
1. Card
2. Coupon
3. Ticket
· Service item will change based on service type
· Service name should be Unique
· Service Id should be unique it will start will always hwpass
· Public key we need to get it from RSAUtils
· Click next button and save details. The service application procedure is now complete. After applying for the service, you can view, edit, and delete it on the HUAWEI Wallet Kit service application page
Step-2: Server Side Integration:
Download server demo code check below link.
Link: https://developer.huawei.com/consumer/en/doc/development/HMS-Examples/wallet-sample-code
1. Download maven dependency.
2. Configure your project into IntelliJ IDEA
3. Download required dependencies and import
4. Sync your project
5. Open release.config.properties and replace appId & secret Key
6. Compile project using terminal mvn clean compile
7. After completion of compilation automatically Target folder will generate
Follow below steps
Copy hmspass folder in the config directory, paste into the target/classes directory.
You can run the source code, you can run mainly java files in the Test folder.
Check below steps and modify accordingly.
· The file ends with ModelTest provides the examples of adding, modifying and pass models.
· The file name ends with InstanceTest provides the examples of adding, modifying and pass instances.
Step-3: Generate Pass Model:
· Open FlightModel.json file
· PassTypeIdentifier is unique which you mentioned service Id in AGC both needs to match
· You have to modify passTypeIdentifier and passStyleIdentifier when we add card types on the AGC PassStyleIdentifier field is unique.
· After completion of modify execute createFlightModel()
· Open the HwFlightModelTest file and Run CreateFlightModel() method
Code:
Test
public void createFlightModel() {
System.out.println("createFlightModel begin");
// Read an example flight model from a JSON file.
String objectJson = CommonUtil.readWalletObject("FlightModel.json");
HwWalletObject hwWalletObject = JSONObject.parseObject(objectJson, HwWalletObject.class);
String modelId = hwWalletObject.getPassStyleIdentifier();
System.out.println("modelId is: " + modelId);
String instanceId = hwWalletObject.getSerialNumber();
// Set parameters of the flight model you want to create. Flight instances belong to this model share these
// parameters.
WalletBuildService walletBuildService = new WalletBuildServiceImpl();
HwWalletObject requestData = walletBuildService.createHwWalletObject(objectJson, instanceId, modelId);
// Validate the parameters.
boolean validateModel = HwWalletObjectUtil.validateWalletModel(requestData);
if (validateModel) {
// Post the new flight model to the wallet server.
String urlParameter = "flight/model";
HwWalletObject flightModel = walletBuildService.postHwWalletObjectToWalletServer(urlParameter, requestData);
System.out.println("createFlightModel JSON is: " + CommonUtil.toJson(flightModel));
System.out.println("createFlightModel end");
}
}
This is not all. For full content, you can visit https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201254289105300220&fid=0101187876626530001
This is a great solution for wallet and loyalty apps that want to stay away from GMS.

Unity and HMSCore Getting started with Auth Kit

More information like this, you can visit HUAWEI Developer Forum​
Intro
In this article I would like to address the HMS topic in Unity Engine. Unity is widely used in the world of video game development. With the help of the plugin developed by EvilMindDevs the integration of the HMS sdk is easier. Although the documentation of the plugin is quite explicit in this tutorial i want to review the implementation within a game. The game is very simple, A car which we must control by swiping to right or left. When losing, a menu where we can login to our HMS account with the help of the plugin. Without further introduction let's go to the article.
Steps
1. Download the code from the repository
2. Create our application in AGC
3. Creating Keystore whitin Unity
4. Obtaining the SHA256 number
5. Finishing the configuration in AGC
6. Let's download the plugin
7. Setting up json Services
8. Adding data of our App to the Plugin
9. Adding the Account Manager prefab to the scene
10.Adding a button to the "End of Game" Canvas
11. Adding neccesary objects
12. Creating an AuthPara class to manage Authentication
1.-Download the repository code
https://github.com/ADX2099/Unity-HMSAUTH
2.- Create our application in AGC
To implement the plugin we must create an App on our console
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Click on My apps
Choose New app and fill App data, this time we must select Game in App Category. Once the App is created, what we will do is go to the develop tab and place the name of our package. Choose the one that suits you best, within this tab is where we will find the necessary data to implement the plugin.
3.-Creating the Keystore in Unity
Now we have to open Unity and start to configure the project, to achieve this we must go to File -> Build Settings -> Player Settings
Within Player Settings we must look for the Publishing Settings tab and open the KeystoreManager
Create our keystore in the desired place
Fill the fields for our key
Done! We have generated our Key locate it in your Explorer
4.-Obtaining the number of SHA256
To obtain the SHA256 by console we must follow the following link
https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides-V5/signing-fingerprint-0000001050071709-V5
Remember that it is also recommended that you adjust your java PATH in the Windows environment variables if your computer has this system.
5.-Finishing setup in AGC
Once we have obtained our fingerprint, place it in the corresponding section in AGC
6.- Let's download the plugin
Our AGC App has been configured now we must download the Unity plugin. Let's go to the next link and download the ZIP.
https://github.com/EvilMindDevs/hms-unity-plugin
Once the plugin is downloaded, locate it in your File Explorer, because now we must import it into Unity. go to Assets-> Import Package->CustomPackage
Once the plugin is imported we will have the following folder structure
7.-Setting the json Services
Let's download the JSON Services of our App from AGC
Open the agconnect file and replace the information downloaded from your agconnect-services.json
8.-Adding data of our App to the Plugin we have to go to the Huawei menu -> App Gallery
As said in the beggining this information will be found in your App properties on AGC
We have to set up our parameters in the following fields.
9.- Adding the Account Manager prefab to the scene.
As mentioned in the documentation we must drag the desired prefab to our scene in Unity in this case we will use Account Manager so we add it to the root of our scene
10.- Add a button to the End of Game Canvas
For this example of how to use Account HMS service We will add a UI button within the canvas that is displayed at the end of the game, the purpose of this menu will be to display the authentication to Huawei.
11.-Add necessary objects in the inspector
12.-Creating an Auth class to manage the login.
Within the game scripts I have created a class called AuthLogin where we will add the following code. This code will be necessary to call the AccountManager object. Don't forget to add it to the Button object too. As shown in the image above.
Code:
using HmsPlugin;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class AuthLogin : MonoBehaviour
{
public Button btnLogin;
public AccountManager myAccountManager;
// Start is called before the first frame update
void Start()
{
myAccountManager = GameObject.Find("AccountManager").GetComponent<AccountManager>();
Button btn = btnLogin.GetComponent<Button>();
btn.onClick.AddListener(TaskOnClick);
}
public void TaskOnClick()
{
if (myAccountManager)
{
myAccountManager.SignIn();
}
else
{
myAccountManager = GameObject.Find("AccountManager").GetComponent<AccountManager>();
}
}
// Update is called once per frame
void Update()
{
}
Documentation mentions that you execute the login method to start with the authentication but reviewing the class the only methods we have are Sign In and SignOut
Conclusion
With this little exercise we have learned how to implement the HMS plugin and start using HMS in Unity, I hope it helps you, the plugin also has the following Kits.

Sending Messages by Push Kit in Cocos

Cocos Creator has supported HMS Core and HUAWEI AppGallery Connect, through which you can quickly release your games with one click, reducing such complex operations as the SDK integration and app upload during development. In this way, you can build high-quality and innovative apps to improve game experience.
Based on this guide, you can learn how to send messages by Push Kit in Cocos step by step.
Procedure Overview
1. Create a game on the Cocos website, and create the game project in Cocos Creator.
2. Create an app and configure the app information in AppGallery Connect, configure Cocos SDKHub and the building flow, and add the HUAWEI_HMS (Push) plugin and select HUAWEI AppGallery Connect from SDKHub Configuration.
3. Perform coding to obtain a token and build an APK.
4. Test the function of sending notification messages and data messages.
Procedure Details
Step 1: Create a game on the Cocos website, and create the game project in Cocos Creator.
1. Visit https://passport.cocos.com/auth/signup, and sign in with a Cocos developer account. (If you have no account, register one.) Then create a game.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
2. Visit http://www.cocos2d-x.org/products#creator, and download and install Cocos Creator.
3. Start Cocos Creator, choose Project, and click New. In the window that is displayed, configure project information, and click Save. The project creation is completed.
If the following error occurs during creation, download Editor.
In Cocos Creator, choose Editor, select version 2.4.2 on the right, and click Download.
Step 2: Create an app and configure the app information in AppGallery Connect, configure Cocos SDKHub and the building flow, and add the HUAWEI_HMS (Push) plugin and select HUAWEI AppGallery Connect from SDKHub Configuration.
1. Create an app and configure the app information in AppGallery Connect by referring to the guide in https://developer.huawei.com/consum...re-Guides/android-config-agc-0000001050170137.
The key steps include:
Generating a signing certificate fingerprint
Configuring the signing certificate fingerprint
Setting a data storage location
Enabling required services
Downloading the agconnect-services.json file
After the app information configuration, perform configuration in Cocos Creator.
2. Choose Panel > Service.
3. Select your project.
Select Cocos SDKHub on the page that is displayed.
4. Click Plugin Manage.
5. Select Push and click OK. The page shown in the preceding figure is displayed.
6. Move the cursor to Not Configured in Params. The editing icon is displayed. Click it.
7. Select a required JSON file, and click OK.
8. Choose Project > Build.
The Build panel is displayed on the right.
9. Set SDKHub Configuration to HUAWEI AppGallery Connect, and click Build.
If the following error occurs during building, install NDK.
After the installation, click Compile. The progress status becomes completed.
Step 3: Perform coding to obtain a token and build an APK.
The following figure shows the project structure.
In Cocos Creator, select js-sdkhub.js file from Assets at the lower left corner.
1. Compile the following code in the js-sdkhub.js file:
Code:
var onPushResult = function (code, msg) {
console.log("on push result action.");
console.log("code: " + code);
console.log("msg: " + msg);
}
var init = function () {
let _global = global || window;
_global.sdkhub = _global.sdkhub || {};
sdkhub.getPushPlugin = () => null;
if (typeof SDKHub === 'undefined')
return;
sdkhub.getPushPlugin = () => SDKHub.AgentManager.getInstance().getPushPlugin();
sdkhub.getPushPlugin().startPush();
sdkhub.getPushPlugin().setListener(onPushResult, this);
}
init();
2. Click Build and then Compile to generate an APK, and install the APK to your device for testing.
The following error will occur during app running if you do not configure a correct certificate fingerprint.
Obtain the device token based on tag jswrapper|HUB_LOG in the logs.
Step 4: Test the function of sending notification messages and data messages.
1. Sign in to AppGallery Connect and select Push Kit by referring to the guide in https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/msg-sending-0000001050042119.
a. Configure notification message information.
The testing result is as follows.
b. Configure data message information.
The testing result is as follows.
Congratulations! Your game can send messages by Push Kit in Cocos.
For more details, please refer to the following documents.
HMS Core overview: https://developer.huawei.com/consumer/en/hms
HMS Core sample code on GitHub: https://github.com/HMS-Core
HMS Core Stack Overflow: https://stackoverflow.com/questions/tagged/huawei-mobile-services?tab=Newest

Push Kit Integration with Cocos

Introduction:
This article will demonstrate to Integrate Push kit in Cocos using Huawei HMS Core App Services Plugin. Huawei Push Kit is a messaging service. It establishes a messaging channel from the cloud to devices. By integrating Push Kit, you can send messages to your apps on users devices in real time. This helps to maintain closer ties with users and increases user awareness and engagement with your apps.
Note: Cocos is free but not open source.
Requirements:
1. Cocos Creator tool
2. Notepad++ for editing and writing script
3. HMS Device
4. Android Studio for Analyzing APK and Checking Log
Output:
Push Notification, Data Message.
Steps to Integrate:
1. Install and launch cocos creator.
2. Make sure to configure NDK Root and Android SDK Root in Cocos Creator, choose File> Settings>Select Native Develop.
3. Click in Cocos Dashboard, click New.
Create project name in Name section and click on hello-world and then Create and open.
Click on Project tab and then Build.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Enter Platform, Build Path and Package Name in build window.
Note: The package name should be same in app gallery connect.
In the same build popup, in the keystore section we can use default keystore (default location is /Users/<username>/.android/debug.keystore) and we can generate SHA key or we can create custom keystore and can generate SHA key.In Command line terminal execute the command below and get SHA key:
Code:
keytool -list -v -keystore keystorepath\keystorename.keystore
Steps to create custom key store file:
a) Uncheck use debug keystore
b) In keystore path section click on New button.
c) Enter all the details in New Keystore details and then click Save.
4. Step 1: Create a project in AppGallery using created SHA key
Step 2: Configure the signing certificate fingerprint
Choose Project settings > General information. In the App information area, click the icon next to SHA 256 certificate fingerprint, and enter the obtained SHA-256 certificate fingerprint.
Step 3: Download agconnect-services.json file and put in setting folder in cocos project.
Example:
Right click on Assets folder and then select Open in Explorer
Place agconnect-services.json file inside settings folder
5. Click Enable for Cocos SDKHub in Service tab.
Click on Association button and register project in Cocos Console
Associating a Game in Cocos Creator You can enable third-party services for your app in Cocos Creator. But first, you need to set a Cocos AppID. Select a created game, and click Association, as shown in the following figures.
Select Plugin Manage under Service tab.
Select Push option in Plugin Manage under Service tab.
Place mouse cursor over the "Configured" text so that "Edit" and "Delete" icons will be appeared. Click on edit icon.
Put public key(from AppGallery connect) in the "Payment Public key" field and select "en" option for "Support language" field and then click OK.
Script code for Notification and Data message:
onLoad: function () {
sdkhub.getPushPlugin().startPush();
sdkhub.getPushPlugin().setListener(this.onPushResult, this);
},
onPushResult: function (code, msg) {
console.log("on push result action.");
console.log("code: " + code);
console.log("massage: " + msg);
this.label.string=msg;
this.showToast(code, msg);
switch (code) {
case sdkhub.PushResultCode.kStartPushSucceed:
console.log("kStartPushSucceed", msg);
break;
}
},
6. Click on Build, Compile, Play under the Project tab to generate APK file.
Tips & Tricks:
Make sure to keep the same package name as kept in the Huawei AppGallery Connect project.
Conclusion:
To promote products and launch marketing activities, games, e-commerce apps, and utility apps can call Push Kit APIs to select target audiences by tag and push messages to them, attracting more users and improving the marketing activity conversion rate.
References:
> Note: this version of the documentation has been archived and is no longer maintained. Please move to the latest version. · Cocos Creator
docs.cocos.com

How Can I Quickly Integrate Cloud Functions of AppGallery Connect into My Cocos-based App?

1. Environment
SDK Version:agconnect-storage:1.3.0.300
Platform:Cocos Creator
Device:HUAWEI P40 Pro
AppGallery Connect:
https://developer.huawei.com/consumer/en/service/josp/agc/index.html
2. Enabling and Configuring Cloud Functions in AppGallery Connect
Note: Currently, Cloud Functions is still under beta state. To use the service, you need to send an email for application. For details, check:
https://developer.huawei.com/consum...allery-connect-Guides/agc-cloudfunction-apply
1. Create an app first and add it to a project, or select an app from the project list on the My projects page in AppGallery Connect.
Under the project, go to Build > Cloud Functions, and click Enable now.
2. Create a function based on the description in the following codelab.
https://developer.huawei.com/consumer/en/codelab/CloudFunctions/index.html#4
3. Create an HTTP trigger and save the suffix of the value of Trigger URL in the Details area as the trigger identifier of future client requests.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
3. Integrating the Cloud Functions SDK in Cocos Creator
1. Integrate the SDK.
Official documentation:
https://docs.cocos.com/creator/manual/en/cocos-service/agc-applinking.html
1. On the Service panel of Cocos Creator, find Cloud Functions. Currently, the Cloud Functions SDK supports only the Android platform.
2. Before integrating a service, you need to associate the service with an app. Click Association. In the dialog box that is displayed, click Create. The Cocos console is displayed.
3. On the Cocos console, create a game.
4. Go back to Cocos Creator and create, refresh, or select an association.
5. Return to the Cloud Functions page, and enable the service.
2. Download the JSON file.
1. Go to Project settings in AppGallery Connect and download the latest agconnect-services.json file.
2. Save the downloaded agconnect-services.json file to the settings directory in your Cocos project.
4. Configuring the UI Layout
Configure buttons for triggering a cloud function, obtaining the timeout interval, and setting the timeout interval separately.
5. Cloud Functions Development
1. Initialize Cloud Functions in the start block.
Code:
start () {
this._func = huawei.agc.func.funcService;
},
2. Call Cloud Functions with input parameters.
Code:
callWithParam:function() {
this._func.wrap("testcodelab-$latest").call((err, data) => {
if (err !== null) {
console.log("Cloud Function", `error: ${JSON.stringify(err)}`);
}
console.log("Cloud Function", `result: ${JSON.stringify(data)}`);
}, {
year: "2020",
}
);
},
3. Call Cloud Functions without input parameters.
JavaScript:
callWithoutParam:function() {
this._func.wrap("testcodelab-$latest").call((err, data) => {
if (err !== null) {
console.log("Cloud Function", `error: ${JSON.stringify(err)}`);
}
console.log("Cloud Function", `result: ${JSON.stringify(data)}`);
});
},
4. Obtain and set the timeout interval of a function.
JavaScript:
setTime:function() {
this._func.wrap("testcodelab-$latest").setTimeout(100,3);
console.log("Cloud Function", `setTime: ` + 100);
},
getTime:function() {
let currTime = this._func.wrap("testcodelab-$latest").getTimeout();
console.log("Cloud Function", `currTime: ` + currTime);
},
6. Packaging and Testing
In Cocos Creator, go to Project > Build…, package an Android app, and install it to your device. To verify the functions, click the buttons from top to bottom.
If the following information is displayed in JavaScript logs, the integration is successful.
7. Summary
Cloud Functions allows you to keep all functions and related code on the cloud side. You only need to call the wrap.call method to trigger the functions, which reduces the code amount and package size of your APK package.
For more details, please check:
Cloud Functions development guide:
https://developer.huawei.com/consum...connect-Guides/agc-cloudfunction-introduction
Cocos documentation:
https://docs.cocos.com/creator/manual/en/cocos-service/agc-cloudfunc.html

Categories

Resources