[Huawei Developers] Freemind R:
While working with Ionic, it is recommended to use the Capacitor for new Ionic apps but sometimes you need to use some Cordova or Ionic Native plugins. In this guide you will learn how to use HMS IAP Cordova Plugin with an Ionic Capacitor application.

In order to use IAP Plugin with any application, you have to create an application on Huawei Developer Console and add some products.

You can read this guide for further details to create an application and add purchasable products to work with.

Huawei In-App Purchases

Huawei In-App Purchases (IAP) provides multiple payment methods for global payments and can be easily integrated into your application to help increase your revenue. Users can purchase a variety of products and services, including popular virtual products and subscriptions, from within your direct application.

Create an Application with Ionic

Install the Ionic CLI with npm if you haven’t already.

ionic start HMS-IAP-Demo blank --capacitor
cd HMS-IAP-Demo
npm run build

Add your agconnect-services.json and keystore files to project folder as explained in the guide I mentioned above.

Add the AppID you got from the Huawei Developer console to the AndroidManifest.xml file. (inside application tag)

<meta-data
android:name="com.huawei.hms.client.appid"
android:value="appid=102461279">
</meta-data>

Add HMS IAP Cordova Plugin & Ionic Native

npm i @hmscore/cordova-plugin-hms-iap --save
npm i @ionic-native/core --save-dev

Copy the “ionic/dist/hms-in-app-purchases” folder from library in node_modules to the “node_modules/@ionic-native” folder in your ionic project.

ionic capacitor add add android
ionic capacitor sync
ionic capacitor build android

Run the project on a connected device

Run the Ionic application with the command below to try the application with a Huawei device. We’re using the --livereload and --external options to see changes on tthe device when changes in the app are detected.

ionic capacitor run android --livereload --external

Exploring IAP Library

You have to login with your Huawei ID on the device you’re going to install application. Otherwise, you will get an error. (Error Code: 60050). You can check the error details and other error codes here.

Adding Library to Providers

You have to add library to the providers section in app.module.ts before using it.

import { HMSInAppPurchases } from '@ionic-native/hms-in-app-purchases/ngx';

@NgModule({
...
providers: [
HMSInAppPurchases,
],
bootstrap: [AppComponent]
})

export class AppModule {}

Checking Environment

Before fetching the products, you should check the environment is ready.

import { Component } from '@angular/core';
import { HMSInAppPurchases } from '@ionic-native/hms-in-app-purchases/ngx';

@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss']
})
export class HomePage {
constructor(public iap: HMSInAppPurchases) { }

async ngOnInit() {
try {
let message = await this.iap.isEnvReady();
console.log(message);
} catch (error) {
console.error(error);
}
}
}

Fetching Products

If you have configured products in AppGallery Connect, you need to use the obtainProductInfo API to obtain details of these products.

Perform the following steps:

Construct a ProductInfoReq object and pass the product ID that has been defined and taken effect in AppGallery Connect to the ProductInfoReq object, and specify priceType for a product. “priceType” is type of the product. Check the code below for price types and their integer equivalents.

If the operation is successful, obtainProductInfo will return a ProductInfoResult object that contains productInfoList. You can use it to display the product information within your application.

import { Component } from '@angular/core';
import { HMSInAppPurchases } from '@ionic-native/hms-in-app-purchases/ngx';
import { HMSAppLinking } from '@ionic-native/hms-applinking/ngx';

const DEVELOPERPAYLOAD = "HMSCoreDeveloper"
const DEVELOPERCHALLENGE = "HMSCoreDeveloperChallenge"
const PRICETYPE = {
CONSUMABLE : 0,
NONCONSUMABLE : 1,
SUBSCRIPTION : 2,
}

const PRODUCTS = {
consumable: {
type: PRICETYPE.CONSUMABLE,
products: [{
id: 'test',
name: 'Consumable Item'
}]
},
nonconsumable: {
type: PRICETYPE.NONCONSUMABLE,
products: [{
id: 'non_consumable_item_1',
name: 'Non Consumable Item'
}, ]
},
subscription: {
type: PRICETYPE.SUBSCRIPTION,
products: [{
id: 'subscription_item_1',
name: 'Subscription Item'
}, ]
},
}

@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {

constructor(private iap: HMSInAppPurchases) {}

ngOnInit() {
...
this.getProductsInformation();
}

getProductsInformation = () => {
Object.keys(PRODUCTS).map(async product_type=> {
await this.obtainProductInfoFromType(product_type);
});
}

obtainProductInfoFromType = async (product_type) => {
try {
let products = await this.iap.obtainProductInfo({
priceType: PRODUCTS[product_type].type,
productList: PRODUCTS[product_type].products.map(p=>p.id)
});
console.log(products);
} catch (err) {
console.log(err);
}
}
}

Initiating a Purchase

Your app can display the purchase screen through the createPurchaseIntent API.

Call createPurchaseIntent with required parameter. Parameter is an object includes productId, priceType and developerPayload. If parameters are correct it automatically brings the checkout page. If a problem occurs the createPurchaseIntent API will return a Status object describing the error.

import { Component } from '@angular/core';
import { HMSInAppPurchases } from '@ionic-native/hms-in-app-purchases/ngx';
import { HMSAppLinking } from '@ionic-native/hms-applinking/ngx';

@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
constructor(private iap: HMSInAppPurchases) {}

ngOnInit() {
...
}

createPurchaseIntent = async (product) => {
try {
let message = await this.iap.createPurchaseIntent({
priceType: product.priceType,
productId: product.productId,
developerPayload: DEVELOPERPAYLOAD
});
if (message.returnCode === 0) {// if successful
console.log(message);
} else {
alert('Purchase was not successful.');
console.log(message);
}
} catch (err) {
console.log(err);
}
}
}

Auto-renewable Subscriptions

Users can purchase access to value-added functions or content in a specified period of time. The subscriptions are automatically renewed on a recurring basis until users decide to cancel.

You can use the createPurchaseIntent API like the example above to display the subscription purchase page. HMS IAP Plugin provides startIapActivity API to display subscription management and subscription editing pages.

Simply call the startIapActivity API to display the subscription management page. If you want to display display the subscription editing page you just need to pass the ID of the product as a parameter.

import { Component } from '@angular/core';
import { HMSInAppPurchases } from '@ionic-native/hms-in-app-purchases/ngx';
import { HMSAppLinking } from '@ionic-native/hms-applinking/ngx';

@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {

constructor(private iap: HMSInAppPurchases) {}

async ngOnInit() {
...
}

editSubscription = (product_id) => {
this.iap.startIapActivity(product_id).then(() => {
console.log('Subscription editing page is displayed');
}).catch(error => {
console.log(error);
})
}

manageSubscriptions = () => {
this.iap.startIapActivity().then(() => {
console.log('Subscription management page is displayed');
}).catch(error => {
console.log(error);
});
}
}

In this article, I tried to explain to you the use of the In-App Purchases Cordova Plugin through code examples.