PeterStaev / nativescript-purchase

:moneybag: A NativeScript plugin for making in-app purchases!
Apache License 2.0
83 stars 28 forks source link
android iap ios nativescript purchase transaction

This repo only supports NativeScript pre-6.0. The latest version of the plugin supporting NS 6+ is availble as part of ProPlugins.

NativeScript In-App Purchases plugin

Build Status npm downloads npm downloads npm

A NativeScript plugin for making in-app purchases.

Installation

Run the following command from the root of your project:

tns plugin add nativescript-purchase

This command automatically installs the necessary files, as well as stores nativescript-purchase as a dependency in your project's package.json file.

In order to get IntelliSense and make TypeScript compile without problems, add the following to your references.d.ts:

/// <reference path="./node_modules/nativescript-purchase/nativescript-purchase.d.ts" />

Configuration

In order for your in-app purchases to be recognized by the plugin, you must configure those on the Google/iTunes side. You can check the in-depth tutorials at the bottom of the page to see how to do it step-by-step.

API

Static Properties

Static methods

Events

Product properties

Transaction properties

Usage

First we need to initialize the plugin with a list for product identifier that will be available for purchase. This is best to be done before the application starts.

Note that it is possible that the initialization of the plugin takes more time than the application to boot. So especially in the cases that you load the products on your landing page, it is best that to save the Promise returned by the init() method and then check it before trying to get your products.

import *  as purchase from "nativescript-purchase";
(global as any).purchaseInitPromise = purchase.init(["com.sample.purchase.coolproduct1", "com.sample.purchase.coolproduct2"]);

To get the actual products with details (like title, price, currency, etc.) you should use:

import { Product } from "nativescript-purchase/product";

(global as any).purchaseInitPromise.then(() => {
    purchase.getProducts().then((products: Array<Product>) => {
        products.forEach((product: Product) => {
            console.log(product.productIdentifier);
            console.log(product.localizedTitle);
            console.log(product.priceFormatted);
        });
    });
});

Before proceeding with buying items you should hook up to the transactionUpdated event. This way you will receive information about the transaction state while it is executing and take necessary action when the transaction completes:

import { Transaction, TransactionState } from "nativescript-purchase/transaction";
import * as applicationSettings from "application-settings";

purchase.on(purchase.transactionUpdatedEvent, (transaction: Transaction) => {
    if (transaction.transactionState === TransactionState.Purchased) {
        alert(`Congratulations you just bought ${transaction.productIdentifier}!`);
        console.log(transaction.transactionDate);
        console.log(transaction.transactionIdentifier);
        applicationSettings.setBoolean(transaction.productIdentifier, true);
    }
    else if (transaction.transactionState === TransactionState.Restored) {
        console.log(`Purchase of ${transaction.originalTransaction.productIdentifier} restored.`);
        console.log(transaction.originalTransaction);
        console.log(transaction.originalTransaction.transactionDate);
        applicationSettings.setBoolean(transaction.originalTransaction.productIdentifier, true);
    }
    else if (transaction.transactionState === TransactionState.Failed) {
        alert(`Purchase of ${transaction.productIdentifier} failed!`);
    }    
});

Now let's buy a product!

if (purchase.canMakePayments()) {
    // NOTE: 'product' must be the same instance as the one returned from getProducts()
    purchase.buyProduct(product);
}
else {
    alert("Sorry, your account is not eligible to make payments!");
}

NOTE: Because of the difference between iOS and Android in terms of consuming purchases - for iOS this is defined in the product you add in iTunes Connect and it is consumed automatically, where for Android it has to be done manually - if you will be supporting Android you will have to manually consume the purchase by calling the consumePurchase method. The methods takes a single parameter that is the receipt from the transaction:

purchase.on(purchase.transactionUpdatedEvent, (transaction: Transaction) => {
    if (transaction.transactionState === TransactionState.Purchased && transaction.productIdentifier.indexOf(".consume") >= 0) {
        purchase.consumePurchase(transaction.transactionReceipt)
            .then((responseCode) => console.log(responseCode)) // If responseCode === 0 the purchase has been successfully consumed
            .catch((e) => console.log(e));
    }    
});

And to restore previous purchases to the user's device:

purchase.restorePurchases();

Demo

This repository includes a plain NativeScript demo. Note that in order to set up and run the demo you need to have the Grunt CLI installed globally. If you don't have it installed, you can do it by running the following in your shell:

$ npm install -g grunt-cli

Once you have Grunt CLI set up in order to set it up the demo run the following in your shell:

$ git clone https://github.com/peterstaev/nativescript-purchase
$ cd nativescript-purchase
$ npm install
$ grunt compile
$ cd demo

You will not be able to directly run the demo, becuase you need to add your purchases to the stores. Also since I already registered the application ID you will have to change that in the package.json file located in the demo folder. So make sure you read and follow the in-depth tutorials below in order to get started with the demo.

In-depth Tutorial

  1. Adding the plugin to your application and creating a purchase workflow
  2. Configuring iTunes Connect and making purchases on iOS
  3. Configuring Google Play Store and making purchases on Android

Donate

Donate

bitcoin:14fjysmpwLvSsAskvLASw6ek5XfhTzskHC

Donate