Giter Club home page Giter Club logo

nativescript-in-app-purchase's Introduction

nativescript-in-app-purchase

NativeScript plugin to handle in app purchases and subscriptions on Android and iOS.

Compatibility

  • Version 1.x build for Google Billing Api 2.1.0
  • Version 2.x build for Google Billing Api 4.x

(Optional) Prerequisites / Requirements

Refer to the mobile ecosystem provider on how to
test in app purchases.

For Apple head to developer.apple.com

For Android Google Play Store head over to developer.android.com

Installation

Installing the plugin

tns plugin add nativescript-in-app-purchase

Usage

Use this typings definition for Typescript and adding IntelliSense support.

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

Initialization

First of all it is required to create an instance of InAppPurchaseManager.

    import { OnInit } from '@angular/core'
    import { InAppPurchaseManager, InAppPurchaseResultCode, InAppPurchaseStateUpdateListener, InAppPurchaseTransactionState, InAppPurchaseType } from 'nativescript-in-app-purchase'
    export class Test implements OnInit {
        private inAppPurchaseManager: InAppPurchaseManager
        constructor() { }
        ngOnInit(): void {
            const purchaseStateUpdateListener: InAppPurchaseStateUpdateListener = {
                onUpdate: (purchaseTransactionState: InAppPurchaseTransactionState): void => {
                    if (purchaseTransactionState.resultCode === InAppPurchaseResultCode.Purchased) {
                        // Item has been purchased, sync local items list ...
                    }
                },
                onUpdateHistory: (purchaseTransactionState: InAppPurchaseTransactionState): void => {
                    if (purchaseTransactionState.resultCode === InAppPurchaseResultCode.Restored) {
                        // Item has been  restored, sync local items list ...
                    }
                }
            }
            InAppPurchaseManager.bootStrapInstance(purchaseStateUpdateListener).then(inAppPurchaseManager => {
                this.inAppPurchaseManager = inAppPurchaseManager
            })
        }
    }

Product list

Get the list of in app products.
To retrieve the list of in app products you must query a known amount of product IDs.

    // additional imports required
    import { InAppPurchaseType, InAppListProductsResult, InAppProduct } from 'nativescript-in-app-purchase'

    // query products
    queryProducts() {
        const myProductIds = ['product_1', 'product_2']
        // For subscriptions change to `InAppPurchaseType.Subscription`
        const myProductType = InAppPurchaseType.InAppPurchase 

        this.inAppPurchaseManager.list(myProductIds, myProductType)
            .then((result: InAppListProductsResult) => {
                const products: InAppProduct[] = result.products
                for (const product of products) {
                    // get the products ...
                    console.log(product.title, product)
                }
            })
    }

Buy a product

When buying a product the result InAppOrderResult is only related to the order transaction it self.
The purchase state of the product will be called on the InAppPurchaseStateUpdateListener#onUpdate method.
This is where you have to confirm the purchase to finish the whole purchasing transaction.
The App Store and Google Play Store will automatically refund orders that haven't been confirmed.

Buying a product

    // additional imports required
    import { InAppOrderResult } from 'nativescript-in-app-purchase'

    // by product
    buy() {
        const myProducts: InAppProduct[] = []//...

        const productToBuy: InAppProduct = myProducts[0]
        this.inAppPurchaseManager.order(productToBuy)
            .then((result: InAppOrderResult) => {
                if (result.success) {
                    // order has been processed
                    // ... expecting confirmation ...
                    // handle confirmation in `InAppPurchaseStateUpdateListener.onUpdate(...)`
                }
            })
    }

Confirming a product

    // additional imports required
    import { InAppOrderConfirmResult } from 'nativescript-in-app-purchase'

    ngOnInit(): void {
        const purchaseStateUpdateListener: InAppPurchaseStateUpdateListener = {
            onUpdate: (purchaseTransactionState: InAppPurchaseTransactionState): void => {
                if (purchaseTransactionState.resultCode === InAppPurchaseResultCode.Purchased) {
                    // Item has been purchased, sync local items list ...
                    this.confirmOrder(purchaseTransactionState)
                }
            },
            onUpdateHistory: (purchaseTransactionState: InAppPurchaseTransactionState): void => {
                if (purchaseTransactionState.resultCode === InAppPurchaseResultCode.Restored) {
                    // Item has been  restored, sync local items list ...
                }
            }
        }
        // ...
    }

    confirmOrder(purchaseTransactionState: InAppPurchaseTransactionState) {
        const isConsumable = (productId: string): boolean => { 
            /* determine if is consumable and can be purchased more then once */
            return false }

        // only purchased products can be confirmed
        if (purchaseTransactionState.resultCode === InAppPurchaseResultCode.Purchased) {
            const consumable: boolean = isConsumable(purchaseTransactionState.productIdentifier)
            this.inAppPurchaseManager.orderConfirm(purchaseTransactionState, consumable)
                .then((result: InAppOrderConfirmResult) => {
                    if (result.success) {
                        // order confirmation has been processed
                    }
                })

        }
    }

Restore purchases

Restore purchases will get you all items the user already purchased.
The purchase state of the restored product will be called on the InAppPurchaseStateUpdateListener#onUpdateHistory method.

    // additional imports required
    import { InAppOrderHistoryResult } from 'nativescript-in-app-purchase'

    restoreProducts() {
        this.inAppPurchaseManager.purchaseHistory()
            .then((result: InAppOrderHistoryResult) => {
                if (result.success) {
                    // purchase history requested
                    // handle it in `InAppPurchaseStateUpdateListener.onUpdateHistory(...)`
                }
            })
    }

API

  • list(productIds: string[], productType?: InAppPurchaseType): Promise<InAppListProductsResult>
    List all products
  • order(product: InAppProduct): Promise<InAppOrderResult>
    Order a product
  • orderConfirm(purchaseTransaction: InAppPurchaseTransactionState, consumable: boolean): Promise<InAppOrderConfirmResult>
    Confirm the buy of a product to make it final
  • purchaseHistory(): Promise<InAppOrderHistoryResult>
    Load user's owned products
  • canMakePayment(): boolean
    Check wether billing is enabled or not
  • static bootStrapInstance(purchaseStateUpdateListener?: InAppPurchaseStateUpdateListener): Promise<InAppPurchaseManager>
    Create a new instance of the in app purchase manager
  • getStoreReceipt(): string
    Returns the application's Base64 encoded store receipt for the currently logged in iOS App Store user. For Android, this function always returns undefined.
  • refreshStoreReceipt(): Promise<void>
    On iOS, request a new receipt if the receipt is invalid or missing.
    On Android, the promise just completes.
  • shutdown()
    Close connection to the underlying OS billing API

DEMO App

There is a demo angular app project included.
Checkout this repo and read the DEMO Readme

License

Apache License Version 2.0, January 2020

Donation

Donate with Bitcoin
3GFxvCK4nnTvHcLpVtFDQhdjANzRGBV6G6
Open in Wallet
Open in Wallet

nativescript-in-app-purchase's People

Contributors

daniele-pecora avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

nativescript-in-app-purchase's Issues

Doesn't build on Android with NS 8

If the demo apps cannot help and there is no issue for your problem, tell us about it

This plugin doesn't build on Android when using NS8. When including the plugin in my project and importing it, it generates this build error:

ERROR in ./node_modules/nativescript-in-app-purchase/in-app-purchase.android.js 3:18-57
Module not found: Error: Can't resolve 'tns-core-modules/application' in '/Users/justintoth/Dev/housters/UI/node_modules/nativescript-in-app-purchase'
resolve 'tns-core-modules/application' in '/Users/justintoth/Dev/housters/UI/node_modules/nativescript-in-app-purchase'
  Parsed request is a module
  using description file: /Users/justintoth/Dev/housters/UI/node_modules/nativescript-in-app-purchase/package.json (relative path: .)
    resolve as module
      looking for modules in /Users/justintoth/Dev/housters/UI/node_modules
        /Users/justintoth/Dev/housters/UI/node_modules/tns-core-modules doesn't exist
      /Users/justintoth/Dev/housters/UI/node_modules/nativescript-in-app-purchase/node_modules doesn't exist or is not a directory
      /Users/justintoth/Dev/housters/UI/node_modules/node_modules doesn't exist or is not a directory
      looking for modules in /Users/justintoth/Dev/housters/UI/node_modules
        /Users/justintoth/Dev/housters/UI/node_modules/tns-core-modules doesn't exist
      /Users/justintoth/Dev/housters/node_modules doesn't exist or is not a directory
      /Users/justintoth/Dev/node_modules doesn't exist or is not a directory
      /Users/justintoth/node_modules doesn't exist or is not a directory
      /Users/node_modules doesn't exist or is not a directory
      /node_modules doesn't exist or is not a directory
 @ ./src/app/shared/services/billing.service.ts 7:0-62 89:12-64
 @ ./src/app/components/main-login/settings/billing/form/form.component.ts 5:0-74 10:0-63 136:169-186
 @ ./src/app/app.module.ts 134:0-92
 @ ./src/main.ts 4:0-45 6:69-78

I saw a similar ticket about the firebase plugin so tried their solution of importing as * but the same error occurs.

Which platform(s) does your issue occur on?

  • Android
  • Android 11
  • Android emulator

Please, provide the following version numbers that your issue occurs with:

  • CLI: (run tns --version to fetch it) 8.1.4

Please, tell us how to recreate the issue in as much detail as possible.

Describe the steps to reproduce it.

Is there any code involved?

import { EventEmitter, Injectable } from '@angular/core';
import { UserView } from '@src/sdk/models';
import { CreditCardView, Stripe } from '@triniwiz/nativescript-stripe';
import { environment } from '@src/environments/environment';
import { UserService } from '@src/sdk/services';
import { AuthService } from '@src/app/shared/services/auth.service';
import { DeviceService } from '@src/app/shared/services/device.service';
import * as inAppPurchase from 'nativescript-in-app-purchase';

@Injectable({
    providedIn: 'root',
})
export class BillingService {
    private inAppPurchaseManager: inAppPurchase.InAppPurchaseManager;
    public iosProduct: inAppPurchase.InAppProduct;
    public iosProductUpdated = new EventEmitter<boolean>();
    private stripe: Stripe;
    private processedTransactionUpdates = {};

    constructor(
        private authService: AuthService,
        private userService: UserService,
        private deviceService: DeviceService
    ) {
    }

    private iosProductName(user: UserView): string {
        const productName = `housters${user.unitCount || 1}`;
        if (user.billingPromotion?.monthlyDiscountPercentage) {
            return `${productName}_${Math.round(user.billingPromotion?.monthlyDiscountPercentage * 100)}`;
        }
        return productName;
    }

    public subscriptionOutOfSync(user: UserView): boolean {
        if (!this.deviceService.isIos) {
            return false;
        }
        if (user.enteredBillingInfo) {
            return false;
        }
        const actualProduct = user?.iosSettings?.productId;
        if (!actualProduct) {
            return false;
        }
        const expectedProduct = this.iosProductName(user);
        if (actualProduct === expectedProduct) {
            return false;
        }
        console.log(`Expected product name: ${expectedProduct}, but received: ${actualProduct}`);
        return true;
    }

    public initIosSubscriptions(user: UserView) {
        console.log('Initializing iOS subscriptions...');
        const productName = this.iosProductName(user);
        console.log(`Product name: ${productName}`);

        // Get iOS subscription product, based on number of units and discounts.
        this.inAppPurchaseManager.list([ productName ], inAppPurchase.InAppPurchaseType.Subscription)
            .then((result: inAppPurchase.InAppListProductsResult) => {
                if (!result.products?.length) {
                    console.warn(`Could not find iOS subscription product with name: ${productName}`);
                    alert('Purchasing a subscription is not available on this device! Please try our website.');
                    return;
                }
                this.iosProduct = result.products[0];
                // Found iOS subscription product, set up listener for when we purchase a product.
                console.log('Setting up listener for purchasing products...');
                const purchaseStateUpdateListener: inAppPurchase.InAppPurchaseStateUpdateListener = {
                    onUpdate: (purchaseTransactionState: inAppPurchase.InAppPurchaseTransactionState): void => {
                        // Item has been purchased, sync local items list ...
                        console.log('In transaction updated event! purchaseTransactionState: ', purchaseTransactionState);
                        const key = `${purchaseTransactionState.productIdentifier}-${purchaseTransactionState.resultCode}`;
                        if (!this.processedTransactionUpdates[key]) {
                            this.processedTransactionUpdates[key] = true;
                            if (purchaseTransactionState.resultCode === inAppPurchase.InAppPurchaseResultCode.Failed)
                                alert(`Purchase of ${purchaseTransactionState.productIdentifier} failed!`);
                            // TODO:[JT] How do we access the transaction receipt???
                            /*else if (purchaseTransactionState.transactionReceipt)
                                // Purchase succeeded, store receipt so we can check if the iOS subscription is active from a nightly job.
                                this.userService
                                    .updateIOSSettings({ input: { receiptData: purchaseTransactionState.transactionReceipt } })
                                    .subscribe(updatedUser => {
                                        this.authService.save(updatedUser);
                                        this.iosProductUpdated.emit(purchaseTransactionState.resultCode === inAppPurchase.InAppPurchaseResultCode.Purchased);
                                    });*/
                        }
                    },
                    onUpdateHistory: (purchaseTransactionState: inAppPurchase.InAppPurchaseTransactionState): void => {
                        if (purchaseTransactionState.resultCode === inAppPurchase.InAppPurchaseResultCode.Restored) {
                            // Item has been  restored, sync local items list ...
                        }
                    }
                };
                inAppPurchase.InAppPurchaseManager.bootStrapInstance(purchaseStateUpdateListener).then(inAppPurchaseManager => {
                    this.inAppPurchaseManager = inAppPurchaseManager
                });
            })
    }

    public saveIosSubscription(): Promise<boolean> {
        return this.inAppPurchaseManager.order(this.iosProduct)
            .then((result: inAppPurchase.InAppOrderResult) => {
                if (!result.success)
                    alert('Purchasing a subscription is not available on this device! Please try our website.');
                // Order has been processed, expect confirmation in onUpdate listener...
                return result.success;
            });
    }
}

How do we get iOS subscription receipt data?

Which platform(s) does your issue occur on?

  • iOS
  • iOS 15
  • iOS Simulator

Please, provide the following version numbers that your issue occurs with:

  • CLI: (run tns --version to fetch it) 8.1.4

Please, tell us how to recreate the issue in as much detail as possible.

Thanks for making this plugin, it's really helpful since the nativescript-purchase plugin doesn't build on Android with the latest version of NativeScript! Question... I'm integrating this plugin for iOS in-app purchases, however the one thing I can't figure out how to do is to retrieve the receipt data for an iOS subscription. The nativescript-purchase plugin had a receiptData property on their transaction object, however InAppPurchaseTransactionState doesn't seem to have this.

Is there any code involved?

public initIosSubscriptions(user: UserView) {
        console.log('Initializing iOS subscriptions...');
        const productName = this.iosProductName(user);
        console.log(`Product name: ${productName}`);

        // Get iOS subscription product, based on number of units and discounts.
        this.inAppPurchaseManager.list([ productName ], InAppPurchaseType.Subscription)
            .then((result: InAppListProductsResult) => {
                if (!result.products?.length) {
                    console.warn(`Could not find iOS subscription product with name: ${productName}`);
                    alert('Purchasing a subscription is not available on this device! Please try our website.');
                    return;
                }
                this.iosProduct = result.products[0];
                // Found iOS subscription product, set up listener for when we purchase a product.
                console.log('Setting up listener for purchasing products...');
                const purchaseStateUpdateListener: InAppPurchaseStateUpdateListener = {
                    onUpdate: (purchaseTransactionState: InAppPurchaseTransactionState): void => {
                        // Item has been purchased, sync local items list ...
                        console.log('In transaction updated event! purchaseTransactionState: ', purchaseTransactionState);
                        const key = `${purchaseTransactionState.productIdentifier}-${purchaseTransactionState.resultCode}`;
                        if (!this.processedTransactionUpdates[key]) {
                            this.processedTransactionUpdates[key] = true;
                            if (purchaseTransactionState.resultCode === InAppPurchaseResultCode.Failed)
                                alert(`Purchase of ${purchaseTransactionState.productIdentifier} failed!`);
                            else if (purchaseTransactionState.transactionReceipt)
                                // Purchase succeeded, store receipt so we can check if the iOS subscription is active from a nightly job.
                                this.userService
                                    .updateIOSSettings({ input: { receiptData: purchaseTransactionState.transactionReceipt } })
                                    .subscribe(updatedUser => {
                                        this.authService.save(updatedUser);
                                        this.iosProductUpdated.emit(purchaseTransactionState.resultCode === InAppPurchaseResultCode.Purchased);
                                    });
                        }
                    },
                    onUpdateHistory: (purchaseTransactionState: InAppPurchaseTransactionState): void => {
                        if (purchaseTransactionState.resultCode === InAppPurchaseResultCode.Restored) {
                            // Item has been  restored, sync local items list ...
                        }
                    }
                };
                InAppPurchaseManager.bootStrapInstance(purchaseStateUpdateListener).then(inAppPurchaseManager => {
                    this.inAppPurchaseManager = inAppPurchaseManager
                });
            })
    }

Google Play billing library deprecation

If you've recently visited your Google Play console, you might have seen this message. It appears on a NativeScript app and as it states - the app was detected to use an old version of the Google Play Billing library and it's about to get deprecated very soon.
I wonder if this plugin is going to receive such update?

@daniele-pecora

Quantity support for iOS

Hi,

how hard would it be to implement support for specifying the quantity of a product when calling order()?
The quantity attribute has to be set on the SKPayment object as described. Inside this add on, the native payment object appears to held in the nativeValue field of the product InAppProduct class, but it is unclear where this native object exactly came from and how it is constructed.

TS2369: A parameter property is only allowed in a constructor implementation.

Thanx for great plugin,

I am getting warning (see bellow) when i am using typing reference for ./node_modules/nativescript-in-app-purchase/index.d.ts" without using the plugin in the app.

ERROR in node_modules/nativescript-in-app-purchase/index.d.ts(93,15): error TS2369: A parameter property is only allowed in a constructor implementation.
node_modules/nativescript-in-app-purchase/index.d.ts(106,15): error TS2369: A parameter property is only allowed in a constructor implementation.

Nativescript _6.4.1
Typescript: 3.4.5
Node: 12.16.1
Npm: 6.13.4

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.