You're Invited:Meet the Socket Team at RSAC and BSidesSF 2026, March 23–26.RSVP
Socket
Book a DemoSign in
Socket

capacitor-plugin-purchase

Package Overview
Dependencies
Maintainers
1
Versions
24
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

capacitor-plugin-purchase

consumable products purchase

latest
Source
npmnpm
Version
0.1.0
Version published
Weekly downloads
147
-30.33%
Maintainers
1
Weekly downloads
 
Created
Source

Capacitor In-App Purchase Plugin

A Capacitor plugin for handling in-app purchases (both consumable and non-consumable products) on iOS and Android.

Version 0.1.0 Changes - Major Update

Breaking Changes - iOS 15+ Required

  • Minimum iOS version is now 15.0
  • Complete migration from StoreKit 1 to StoreKit 2
  • Uses modern Swift async/await patterns
  • Improved transaction verification and security

StoreKit 2 Migration Benefits

  • Automatic transaction verification: All transactions are automatically verified for authenticity
  • Built-in transaction persistence: StoreKit 2 handles transaction state management
  • Simplified API: Less boilerplate code with modern async/await
  • Better error handling: More descriptive error types and recovery options
  • Enhanced receipt handling: Transaction IDs are used instead of base64 receipts
  • Improved subscription support: Better handling of subscription periods and renewal info

Technical Improvements

  • Replaced deprecated APIs with iOS 15+ equivalents
  • Removed redundant iOS version checks
  • Updated to use modern Swift error handling with typed errors
  • Enhanced date formatting using iOS 15+ APIs
  • Better support for consumable vs non-consumable product handling

Version 0.0.22 Changes

  • Added userId support to restorePurchases and getActivePurchases methods
  • iOS now uses restoreCompletedTransactions(withApplicationUsername:) when userId is provided
  • Fixed Android restorePurchases to return list of restored purchases
  • Improved API consistency between iOS and Android platforms

Version 0.0.21 Changes

  • Added support for non-consumable products
  • Added productType parameter to distinguish between consumable and non-consumable products
  • Added finishTransaction method for iOS to manually finish consumable transactions
  • Improved handling of product types on both iOS and Android platforms

Installation

npm install capacitor-plugin-purchase
npx cap sync

Requirements

  • iOS 15.0 or later (uses StoreKit 2)
  • Android API level 21 or later
  • Capacitor 5.0 or later

Configuration

iOS Configuration

  • Minimum iOS Version: Ensure your app's minimum deployment target is set to iOS 15.0 or later in Xcode.

  • Capabilities: Enable the "In-App Purchase" capability in your app's Xcode project:

    • Select your project in Xcode
    • Go to the "Signing & Capabilities" tab
    • Click "+ Capability" and add "In-App Purchase"
  • StoreKit Configuration (for testing):

    • Create a StoreKit Configuration file in Xcode for local testing
    • Add your products to the configuration file
    • Select the configuration file in your scheme's options

Android Configuration

Add the following to your app's build.gradle:

dependencies {
    // ... other dependencies
    implementation 'com.android.billingclient:billing:5.0.0'
}

Usage

Import the plugin

import { InAppPurchase } from 'capacitor-plugin-purchase';
import { Capacitor } from '@capacitor/core';

Check if purchases are allowed

const checkPurchases = async () => {
  const { allowed } = await InAppPurchase.canMakePurchases();
  if (allowed) {
    console.log('In-app purchases are allowed');
  } else {
    console.log('In-app purchases are not allowed');
  }
};

Get available products

const getProducts = async () => {
  try {
    const result = await InAppPurchase.getProducts({
      productIds: ['product_id_1', 'product_id_2'],
      productType: 'consumable' // optional: 'consumable' or 'non-consumable'
    });
    
    console.log('Products:', result.products);
    // Products will contain details like title, description, price, etc.
  } catch (error) {
    console.error('Error fetching products:', error);
  }
};

Purchase a product

For Consumable Products

const purchaseConsumable = async (productId: string, userId?: string) => {
  try {
    const result = await InAppPurchase.purchaseProduct({
      productId: productId,
      productType: 'consumable',
      userId: userId // optional: associate purchase with user
    });
    
    if (result.transactionId) {
      console.log('Purchase successful!');
      console.log('Transaction details:', result);
      
      // On iOS, you need to finish the transaction after consuming the item
      if (Capacitor.getPlatform() === 'ios') {
        // Consume your item here (update game state, add coins, etc.)
        // Then finish the transaction
        await InAppPurchase.finishTransaction({
          transactionId: result.transactionId
        });
      }
      // On Android, consumable products are automatically consumed
    }
  } catch (error) {
    console.error('Error during purchase:', error);
  }
};

For Non-Consumable Products

const purchaseNonConsumable = async (productId: string, userId?: string) => {
  try {
    const result = await InAppPurchase.purchaseProduct({
      productId: productId,
      productType: 'non-consumable',
      userId: userId // optional: associate purchase with user
    });
    
    if (result.transactionId) {
      console.log('Purchase successful!');
      console.log('Transaction details:', result);
      
      // Non-consumable products are automatically finished/acknowledged
      // Just update your app state to reflect the purchase
    }
  } catch (error) {
    console.error('Error during purchase:', error);
  }
};

Restore purchases for a specific user

const restoreUserPurchases = async (userId: string) => {
  try {
    const result = await InAppPurchase.restorePurchases({ userId });
    console.log('Restored purchases:', result.purchases);
    
    // Note: On iOS, this will only return purchases associated with the userId
    // On Android, this returns all purchases for the Google account
  } catch (error) {
    console.error('Error restoring purchases:', error);
  }
};

Get active purchases for a specific user

const getActiveUserPurchases = async (userId: string) => {
  try {
    const result = await InAppPurchase.getActivePurchases({ userId });
    console.log('Active purchases:', result.purchases);
    
    // Note: On iOS, this will only return purchases associated with the userId
    // On Android, this returns all purchases for the Google account
  } catch (error) {
    console.error('Error getting active purchases:', error);
  }
};

Web Implementation

The web implementation provides mock responses as in-app purchases are not supported in web environments. This allows you to develop and test your app in a web browser without errors, but actual purchases will only work on iOS and Android devices.

API

canMakePurchases()

Check if the user/device can make purchases.

Returns: Promise<{ allowed: boolean }>

getProducts(options: { productIds: string[]; productType?: 'consumable' | 'non-consumable' })

Get product information from the app store.

Parameters:

  • options.productIds: Array of product identifiers
  • options.productType (optional): Product type filter - 'consumable' or 'non-consumable'

Returns: Promise<{ products: Product[] }>

Where Product has the following properties:

  • productId: string
  • title: string
  • description: string
  • price: string (formatted price with currency symbol)
  • priceAsDecimal: number (price as a decimal number)
  • currency: string (currency code)
  • productType: string (optional) - 'consumable' or 'non-consumable'

purchaseProduct(options: { productId: string; userId?: string; productType?: 'consumable' | 'non-consumable' })

Initiate a purchase for a specific product.

Parameters:

  • options.productId: Product identifier to purchase
  • options.userId (optional): User identifier to associate with the purchase
  • options.productType (optional): Product type - 'consumable' or 'non-consumable'

Returns: Promise

Where TransactionDetails has the following properties:

  • transactionId: string (transaction identifier)
  • productId: string (purchased product identifier)
  • receipt: string (purchase receipt - base64 encoded on iOS, JSON string on Android)
  • date: string (ISO 8601 formatted date)
  • userId: string (optional) - user identifier if provided

restorePurchases(options?: { userId?: string })

Restore previously purchased products.

Parameters:

  • options.userId (optional): User identifier to filter restored purchases (iOS only, Android returns all purchases for the account)

Returns: Promise<{ purchases: TransactionDetails[] }>

getActivePurchases(options?: { userId?: string })

Get list of active purchases (owned items).

Parameters:

  • options.userId (optional): User identifier to filter active purchases (iOS only, Android returns all purchases for the account)

Returns: Promise<{ purchases: TransactionDetails[] }>

finishTransaction(options: { transactionId: string }) (iOS only)

Finish a transaction for consumable products on iOS. This should be called after the consumable item has been delivered to the user.

Parameters:

  • options.transactionId: Transaction identifier to finish

Returns: Promise

Notes for Web Usage

When using this plugin in a web application, all methods will return mock responses:

  • canMakePurchases() will return { allowed: false }
  • getProducts() will return an empty array of products
  • purchaseProduct() will throw an error

This allows you to develop and test your app in a web browser without errors, but actual purchases will only work on iOS and Android devices.

Testing In-App Purchases

iOS Testing

For iOS, you can use the Sandbox environment to test purchases without actual charges. Make sure to:

  • Create a Sandbox tester account in App Store Connect
  • Sign out of your regular Apple ID on the test device
  • Sign in with the Sandbox tester account when prompted during testing

Android Testing

For Android, you can use test accounts and test cards:

  • Upload your app to the internal testing track in Google Play Console
  • Add test accounts in the Google Play Console
  • Use the test accounts to make purchases

Troubleshooting

iOS Issues

  • Make sure your app has the proper capabilities enabled in Xcode
  • Verify that your product IDs are correctly configured in App Store Connect
  • Check that your app is properly signed with a valid provisioning profile

Android Issues

  • Ensure your app is properly signed with the same key used in Google Play Console
  • Verify that your product IDs are correctly configured in Google Play Console
  • Make sure the Google Play Billing Library is properly implemented

License

MIT

Keywords

capacitor

FAQs

Package last updated on 04 Jul 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts