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

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.

Related

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.

Java Client for HMS Product Management Service API

More information like this, you can visit HUAWEI Developer Forum​
Let’s say that you need to create an in-app product on Huawei AppGallery Connect. To do this, you sign in to AppGallery Connect, browse to your application, go to In-App Purchase, specify product information, and release the product. However, in reality, an application never have one but ten or twenty in-app products instead. In other words, you have to repeat the boring procedure mentioned above ten or twenty times! Don’t panic yet. This article will show you how to automate such mundane work using Product Management Service API.
The Product Management Service (PMS) API is a part of AppGallery Connect API, a HUAWEI’s alternative to Google Play Developer API. It provides RESTful APIs that can be used to create and update in-app product and promotion information. Utilizing this API, the automation tool (in Java) provided in this article will help you manage in-app product fast and precisely. Let’s examine how this tool works and its features.
Creating an API client
Accessing PMS API, as well as any other Connect APIs, requires authorization from the AppGallery Connect server in advance using either of the following modes:
API client mode: In this mode, an API client is used to authenticate and get access to AppGallery Connect APIs
OAuth client mode: In this mode, access to AppGallery Connect APIs is authorized by Huawei developer accounts. This mode is appropriate for developing a third-party IDE or development tool that needs to be connected to AppGallery Connect. This mode will not be discussed in this article
The tool I created utilized API client mode to call the AppGallery Connect API. Therefore, to be able to use the tool, you need an API client. The procedure of creating an API client is as follows:
Sign in AppGallery Connect and select Users and Permissions
Go to API Key > Connect API from the navigation tree on the left and click Create.
Set Name to a customized client name, set Roles to the corresponding role, and click Confirm. For details about roles and permissions, please refer to Roles and Permissions
After the client is successfully created, record the values of Client ID and Key in the client information list. You will need these values to run the tool later.
How to use the automation tool?
The automation tool is a Maven project, developed in Eclipse IDE. You will need to download and install Eclispe IDE for Java Developers (https://www.eclipse.org/downloads/packages/release/2020-06/r/eclipse-ide-java-developers) if you haven’t already. Then, download the tool from the github repos (https://github.com/buiquanghuy23103/PMS-demo). Once you had the tool and the IDE, let’s run it by following the instructions below:
Open Eclipse IDE. Go to File > Import > Maven > Existing Maven Projects. Then click Next.
Browse to the directory of the sample project
Select pom.xml in the Projects box and click Finish.
Open Package Explorer (Window > Show View > Package Explorer) and navigate to src > test > PmsApiDemo.java. In this file, provide Client ID, Client Key and App ID
To run the tool, from the app bar of Eclipse IDE, go to Run > Run
Creating a product
You can create new in-app products in few seconds with PMS. Go to projectDirectory > src > test > CreateProducts.java to specify product information, and then call CreateProducts.createNewProducts() in PmsApiDemo.java. Please note that product information has to follow the rules in ProductImportInfo. Otherwise, the tool will throw an exception.
Code:
public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
String token = GetToken.getToken(domain, clientId, clientSecret);
CreateProducts.createNewProducts(domain, clientId, token, appId);
}
Get product information
You can easily view information of any in-app products in AppGallery Connect through PMS. All you need to do is calling GetIapProductInfo.getProductInfoDetail() in PmsApiDemo.java.
Code:
public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
String token = GetToken.getToken(domain, clientId, clientSecret);
GetIapProductInfo.getProductInfoDetail(domain, clientId, token, appId, productNo);
}
The response will be in JSON format as follow:
{
"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"
}
Update product information
You can also update product information in the AppGallery through PMS. Go to UpdateProduct. generateUpdateRequest() to update your product information, and then call UpdateProduct.update() in PmsApiDemo.java.
Code:
public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
String token = GetToken.getToken(domain, clientId, clientSecret);
UpdateProduct.update(domain, clientId, token, appId, productNo);
}
Apart from these endpoints I integrate, you can also check out the other features of the PMS API here:
https://developer.huawei.com/consumer/en/doc/development/AppGallery-connect-Guides/agcapi-pms-api-manage_product_promotion

Integration of Huawei IAP Kit in Cocos

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?

Smart Shopping Cart using Scan Kit (Native iOS Swift)

{
"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"
}
Article Introduction
In this article we will show how to integrate Huawei Scan Kit in iOS using native language (swift) and barcode lookup APIs to search and add items with information in your list. The use case has been created to make Smart Shopping Cart with HMS open capabilities.
Huawei Scan Kit
Huawei Scan Kit supports 13 mainstream formats including QR Code, Data Matrix, PDF417, Aztec, EAN-8, EAN-13, UPC-A, UPC-E, Codabar, Code 39, Code 93, Code 128, and ITF. It detects barcodes despite low visibility, glare, damage, distortion, or blur. It also supports Auto Zoom into small and distant barcodes. It can easily processes up to 5 barcodes simultaneously.
Scan Kit can be called in three ways, from which you can choose as needed.
For this article, we implemented Default View for iOS with native Swift language. In Default View mode, Scan Kit scans barcodes using the camera or from images in the album, and also provides a complete scanning UI that can be directly used. You do not need to worry about designing a UI as Scan Kit provides one.
Pre-Requisites
Before getting started, following are the requirements:
Xcode (During this tutorial, we used latest version 12.3)
iOS 9.0 or later (Scan Kit supports iOS 9.0 and above)
Apple Developer Account
iOS device for testing
Development
Following are the major steps of development for this article:
Step 1: Importing the SDK in Pod Mode
1.1: Check whether Cocoapods has been installed:
gem -v
If not, run the following commands to install Cocoapods:
Code:
sudo gem install cocoapods
pod setup
1.2: Run the pod init command in the root directory of the Xcode project and add the current version number to the generated Podfile file.
pod 'ScanKitFrameWork', '~> 1.0.2.300' # Huawei Scan Kit dependency
pod 'Alamofire', '~> 5.2' # Optional: Swift Network call lib dependency
pod 'AlamofireImage', '~> 4.1' # Optional: Swift Image loading lib dependency
pod 'SwiftyJSON', '~> 4.0' # Optional: Swift JSON parsing lib dependency
pod "TTGSnackbar" # Optional: Swift Snackbar lib dependency
pod 'lottie-ios' # Optional: Swift Lottie animation lib dependency
1.3: Run the following command in the same directory of the Podfile file to integrate the HMS Core Scan SDK:
pod install
If you have used Cocoapods, run the following command to update Cocoapods:
pod update
1.4: After the execution is successful, open the project directory, find the .xcworkspace file, and execute it.
Step 2: Assigning Permissions
You need to assign permissions required by your app to call Scan Kit.
To scan barcodes using the camera, you need to add Camera Usage Description (camera permission).
To scan barcodes from images in the album, you need to add Photo Library Usage Description (image read permission).
Open the info.plist file and add the following content:
Step 3: Building Layout
We used Auto Layout. Auto Layout defines your user interface using a series of constraints. Constraints typically represent a relationship between two views. Auto Layout then calculates the size and location of each view based on these constraints. This produces layouts that dynamically respond to both internal and external changes.
In this article, we also used Lottie animation for empty cart list and for the searching animation when user scan barcodes.
Code:
// This extension is responsible to manage all the lottie animation methods
extension HomeViewController {
func setDefaultAnimation(){
if(self.addedItems.count > 0){
showResults()
} else {
noItemFound()
}
}
func noItemFound(){
DispatchQueue.main.async {
self.homeTableView.isHidden = true
self.animationView.isHidden = false
self.animationView.animation = Animation.named("empty_view")
self.animationView.contentMode = .scaleAspectFit
self.animationView.loopMode = .loop
self.animationView.animationSpeed = 1.5
self.animationView.play()
}
}
func showLoading(){
DispatchQueue.main.async {
self.homeTableView.isHidden = true
self.animationView.isHidden = false
self.animationView.animation = Animation.named("not_found")
self.animationView.contentMode = .scaleAspectFit
self.animationView.loopMode = .loop
self.animationView.animationSpeed = 1.5
self.animationView.play()
}
}
func showResults(){
DispatchQueue.main.async {
self.homeTableView.isHidden = false
self.animationView.isHidden = true
}
}
}
More information, you can check https://forums.developer.huawei.com/forumPortal/en/topic/0203446609479290092
It will support all languages ?
Very nice and useful for many applications with an online database.
how can i use customised API in the application?

Using the Cloud DB JavaScript Server SDK in Cloud Functions

With Cloud Functions, you can configure a CLOUDDB trigger to call a function when data is entered, deleted, or modified in Cloud DB.
The Cloud DB service has been released with a JavaScript Server SDK, which can be used in the Node.js environment that the Cloud Functions service supports. In this article, I will elaborate on how to enter and query data with the Cloud DB JavaScript Server SDK in Cloud Functions.
{
"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"
}
Enabling Required Services​You need to enable two services.
First of all, sign in to AppGallery Connect and perform the following operations:
Enable Cloud Functions. Click My projects, click your project card, and go to Build > Cloud Functions. On the Cloud Functions page, click Enable now. Click + New Function to create a function.
Enable Cloud DB. Click My projects, click your project card, and go to Build > Cloud DB. On the Cloud DB page, click Enable now and then create an object type and a Cloud DB zone.
Configuring the JavaScript Server SDK of Cloud DB​Here, I will use the src file in the Huawei service demo to demonstrate how the JavaScript Server SDK is configured. You can also download the file and use it for your own file from GitHub.
Then you need to do the following in AppGallery Connect:
Export an object type.​On the Cloud DB page, export the BookInfo object type to a JS file, and then add it to the model directory of your project.
Download the authentication credential.​Go to Project settings > Server SDK. On the Server SDK tab page, click Create for API client first, and then click Download credential to download the authentication credential. Finally, add it to the model directory of your project
Modify the path to the credential.​You need to modify the path to the credential as it was saved to the model directory. In the CloudDBZoneWrapper.js file (use the _dirname method to obtain the file), modify the initialization code as follows:
Code:
let api_client_name = "agc-apiclient-testDB.json";
let path = require('path');
let api_client_path = path.join(_dirname,api_client_name);
agconnect.AGCClient.initialize(agconnect.CredentialParser.toCredential(api_client_path));
Configure a handler.​You can either use the Start.js file as the handler by default or create a new one. For example, the inde.js file is created as a handler. The sample code is as follows:
Code:
const CloudDBZoneWrapper = require("./model/CloudDBZoneWrapper.js");
let myHandler = async function(event, context, callback, logger) {
logger.info(JSON.stringify(event));
logger.info("event start");
const cloudDBZoneWrapper = new CloudDBZoneWrapper();
const bookInfo = cloudDBZoneWrapper.getSingleBook();
// Update and insert a list of books.
await cloudDBZoneWrapper.upsertBookInfos(bookInfo);
let result = {"message":"Run Success"}
callback(result);
}
module.exports.myHandler = myHandler;
Packaging Your Project and Configuring a Trigger​You need to package your project, upload it to Cloud Functions, and test it with events. The handler file should be saved in the root directory.
Sign in to AppGallery Connect and go to the Cloud Functions page. Upload your package and set the name of the handler to index.myHandler
Configure a CLOUDDB trigger. Click + Add Trigger and configure the type, Cloud DB zone, and object type for the trigger.
Testing the Function​In AppGallery Connect, go to Cloud Functions > Test.
Configure a trigger event according to the documentation
If you need to configure a data insertion event, add the following sample code.
Code:
{
"records": [{
"before": null,
"after": {
"id": "11111",
"bookName": "user1"
}
}],
"objectTypeName": "BookInfo",
"naturalStoreName": "QuickStartDemo"
}
Check the test result.
Reference​Cloud Functions
Defining a programming model
Cloud DB JavaScript Server SDK

Categories

Resources