Coder Social home page Coder Social logo

chargebee / chargebee-react-native Goto Github PK

View Code? Open in Web Editor NEW
8.0 22.0 13.0 2.89 MB

License: MIT License

JavaScript 1.50% TypeScript 39.96% Ruby 2.45% Kotlin 24.00% Java 5.67% Objective-C 1.96% Objective-C++ 4.60% Swift 19.86%
critical mobile-subscription

chargebee-react-native's Introduction

Latest Release

Introduction

This is Chargebee’s React Native Software Development Kit (SDK). This SDK makes it efficient and comfortable to build a seamless subscription experience in your React Native App.

Post-installation, initialization, and authentication with the Chargebee site, this SDK will support the following process.

  • Sync In-App Subscriptions with Chargebee: Integrate your App developed on React Native with Chargebee to process and track in-app subscriptions of the Apple App Store and Google Play Store on your Chargebee account. Thus you can create a single source of truth for subscriptions across Apple, Google, and Web stores. Use this if you are selling digital goods or services or are REQUIRED to use Apple's and Google's in-app purchases as per their app review guidelines (Apple and Google). For SDK methods to work, ensure that prerequisites (Apple and Google) are configured in Chargebee.

Note: If you are using the React native wrapper for performing web checkouts for physical goods, follow the set up for our 1.x SDK here.

Requirements

The following requirements must be set up before installing Chargebee’s React Native SDK.

Installation

To use Chargebee SDK in your React Native app, follow the below step.

yarn add @chargebee/react-native-chargebee

For iOS, perform pod install after adding the SDK, to install the corresponding cocoapod package.

Permissions

  1. For Android include the BILLING permission in your AndroidManifest.xml file.
<uses-permission android:name="com.android.vending.BILLING" />
  1. For iOS enable In-App Purchase capability in Xcode by going to Signing & Capabilities and adding the In-App Purchase capability.

Example project

This is an optional step that helps you to verify the SDK implementation using this example project. You can download or clone the example project via GitHub.

To run the example project, follow these steps.

  • Clone the repo - https://github.com/chargebee/chargebee-react-native.

  • To install the base dependencies, run yarn bootstrap in the root directory

  • To run the example app on Android, run yarn example android.

  • To run the example app on iOS, run yarn example ios.

Configuring SDK

Prerequisites Before configuring the Chargebee ReactNative SDK for syncing In-App Purchases, follow these steps.

  1. iOS: Integrate the Apple App Store account with your Chargebee site. Android: Integrate Google Play Store account with your Chargebee site.
  2. iOS: On theSync Overview pageof theweb app, click View Keys and use the value of generated App ID as the SDK Key. Android: On the Sync Overview page of the web app, click Set up notifications and use the generated App ID value as the SDK Key.
  3. On the Chargebee site, navigate to Configure Chargebee > API Keys to create a new Publishable API Key or use an existing Publishable API Key.

Note: During the publishable API key creation you must allow read-only access to plans/items otherwise this key will not work in the following snippet. Read more.

Initialize the Chargebee ReactNative SDK with your Chargebee site, Publishable API Key, and SDK Keys by including the following snippets in your app delegate during app startup.

import Chargebee from '@chargebee/react-native-chargebee';

Chargebee.configure({
      site: "SITE_NAME",
      publishableApiKey: "API-KEY",
      androidSdkKey: "Android SDK Key",
      iOsSdkKey: "iOS SDK Key",
    });

Integrating In-App Purchases

This section describes how to use the SDK to integrate In-App Purchase information. For details on In-App Purchase, read more.

Get all IAP Product Identifiers from Chargebee

Every In-App Purchase subscription product that you configure in your account, can be configured in Chargebee as a Plan. Start by retrieving the IAP Product IDs from your Chargebee account using the following function.

import Chargebee from '@chargebee/react-native-chargebee';

const queryParams = new Map<string, string>();
queryParams.set('limit', '100');
try {
    const result: Array<string> = await Chargebee.retrieveProductIdentifiers(queryParams);
    console.log(result);
} catch (error) {
    console.error(error);
}

For example, query parameters can be passed as "limit": "100".

Get IAP Products

Retrieve the IAP Product objects with Product IDs using the following function.

import Chargebee, { Product } from '@chargebee/react-native-chargebee';

try {
      const result: Array<Product> = await Chargebee.retrieveProducts(["Product ID from Google or Apple"]);
      console.log(result);
    } catch (error) {
      console.error(error);
    }

You can present any of the above products to your users for them to purchase.

Buy or Subscribe Product

Pass the product and customer to the following function when your customer chooses the product to purchase.

id - Optional parameter. Although this is an optional parameter, we recommend passing it if available, before the user subscribes to your App. Passing this parameter ensures that the customer id in your database matches that in Chargebee. In case this parameter is not passed, then the id will be the same as the SubscriptionId created in Chargebee.

firstName - Optional parameter. Contains the first name of the customer.

lastName - Optional parameter. Contains the last name of the customer.

email - Optional parameter. Contains the email of the customer.

import Chargebee, {
    Purchase,
    Customer
} from '@chargebee/react-native-chargebee';
const customer: Customer = {
    id: 'id',
    firstName: 'fname',
    lastName: 'lname',
    email: '[email protected]',
};
try {
    const result: Purchase = await Chargebee.purchaseProduct("product-id", customer);
    console.log(result);
} catch (error) {
    console.error(error);
}

The above function will handle the purchase against Apple App Store or Google Play Store and send the in-app purchase receipt for server-side receipt verification to your Chargebee account. Use the Subscription ID returned by the above function to check for Subscription status on Chargebee and confirm the access - granted or denied.

One-Time Purchases

The purchaseNonSubscriptionProduct function handles the one-time purchase against Apple App Store and Google Play Store and then sends the IAP receipt for server-side receipt verification to your Chargebee account. Post verification a Charge corresponding to this one-time purchase will be created in Chargebee. The Apple App Store supports three types of one-time purchases consumable, non_consumable and non_renewing_subscription. The Google Play Store supports two types of one-time purchases consumable and non_consumable.

import Chargebee, {
    OneTimePurchase,
    Customer
} from '@chargebee/react-native-chargebee';
const customer: Customer = {
    id: 'id',
    firstName: 'fname',
    lastName: 'lname',
    email: '[email protected]',
};
const productType = ProductType.NON_CONSUMABLE
try {
    const result: OneTimePurchase = await Chargebee.purchaseNonSubscriptionProduct("product-id", productType, customer);
    console.log(result);
} catch (error) {
    console.error(error);
}

The given code defines a function named purchaseNonSubscriptionProduct in the Chargebee class, which takes three input parameters:

  • product: An instance of Product class, representing the product to be purchased from the Apple App Store or Google Play Store.
  • customer: Optional. An instance of CBCustomer class, initialized with the customer's details such as customerId, firstName, lastName, and email.
  • productType: An enum instance of productType type, indicating the type of product to be purchased. It can be either consumable, or non_consumable, or non_renewing_subscription. Note that non_renewing_subscription is supported only in Apple App Store.

The function is called asynchronously, and it returns a Result object with a success or failure case, as mentioned are below.

  • If the purchase is successful, it returns OneTimePurchase object. which includes the invoiceId, chargeId, and customerId associated with the purchase.
  • If there is any failure during the purchase, it returns error object that can be used to handle the error.

Get Subscription Status for Existing Subscribers using Query Parameters

Use the method, retrieveSubscriptions to check the subscription status of a subscriber who has already purchased the product.

Use SubscriptionsRequest with query parameters- Subscription ID, Customer ID, or Status for checking the subscription status on Chargebee and confirming the access - *_granted or denied_*.

import Chargebee, { SubscriptionsRequest, Subscription } from '@chargebee/react-native-chargebee';

try {
    const queryParams: SubscriptionsRequest = {customer_id : 'customer_id', subscription_id : 'subscription_id', status: 'active'}
    const subscriptions: Subscription[] = await Chargebee.retrieveSubscriptions(queryParams);
    console.log(subscriptions);
} catch (error) {
    console.error(error);
}

Retrieve Entitlements of a Subscription

Use the Subscription ID for fetching the list of entitlements associated with the subscription.

const request: EntitlementsRequest = {
    subscriptionId: 'subscription-id',
};
try {
    const entitlements: Array<Entitlement> = await Chargebee.retrieveEntitlements(request);
} catch (error) {
    console.log(error);
}

Note: Entitlements feature is available only if your Chargebee site is on Product Catalog 2.0.

Restore Purchases

The restorePurchases() function helps to recover your app user's previous purchases without making them pay again. Sometimes, your app user may want to restore their previous purchases after switching to a new device or reinstalling your app. You can use the restorePurchases() function to allow your app user to easily restore their previous purchases.

To retrieve inactive purchases along with the active purchases for your app user, you can call the restorePurchases() function with the includeInactivePurchases parameter set to true. If you only want to restore active subscriptions, set the parameter to false. To associate the restored purchases to an existing customer, it is recommended to pass the necessary customer details, such as customerId, firstName, lastName, and email. This ensures that the customer details in your database match the customer details in Chargebee. If the customerId is not passed in the customer’s details, then the value of customerId will be the same as the SubscriptionId created in Chargebee. Here is an example of how to use the restorePurchases() function in your code with the includeInactivePurchases parameter set to true.

import Chargebee, { RestoredSubscription } from '@chargebee/react-native-chargebee';
const customer: Customer = {
    id: 'id',
    firstName: 'fname',
    lastName: 'lname',
    email: '[email protected]',
};
try {
    const restoredSubscriptions: RestoredSubscription[] = await Chargebee.restorePurchases(true, customer);
    console.log(restoredSubscriptions);
} catch (error) {
    console.error(error);
}
Return Subscriptions Object

The restorePurchases() function returns an array of subscription objects and each object holds three attributes subscriptionId, planId, and storeStatus. The value of storeStatus can be used to verify subscription status.

Error Handling

In the event of any errors/failures, the React native SDK will return an error object, which has the below format. code - number. Chargebee Error code. message - string. Error description. userInfo - (ChargebeeErrorDetail) Optional Object. Contains additional error information.

The ChargebeeErrorDetail object is the below format: apiErrorCode - string Optional. Error code from Chargebee backend. httpStatusCode - number Optional. Http status code from Chargebee backend. message - string Optional. Error description.

Example
{
    "code": "1000",
    "message": "Sorry, we couldn't find the site abc-test",
    "userInfo": {
        "apiErrorCode": "site_not_found",
        "httpStatusCode": 404,
        "message": "Sorry, we couldn't find the site abc-test"
    }
}
Error Codes

These are the possible error codes and their descriptions:

Error Code Description
1000 INVALID_SDK_CONFIGURATION
1001 INVALID_CATALOG_VERSION
1002 CANNOT_MAKE_PAYMENTS
1003 NO_PRODUCT_TO_RESTORE
1004 INVALID_RESOURCE
2001 INVALID_OFFER
2002 INVALID_PURCHASE
2003 INVALID_SANDBOX
2004 NETWORK_ERROR
2005 PAYMENT_FAILED
2006 PAYMENT_NOT_ALLOWED
2007 PRODUCT_NOT_AVAILABLE
2008 PURCHASE_NOT_ALLOWED
2009 PURCHASE_CANCELLED
2010 STORE_PROBLEM
2011 INVALID_RECEIPT
2012 REQUEST_FAILED
2013 PRODUCT_PURCHASED_ALREADY
3000 SYSTEM_ERROR
0 UNKNOWN

Synchronization of Apple App Store/Google Play Store Purchases with Chargebee through Receipt Validation

Receipt validation is crucial to ensure that the purchases made by your users are synced with Chargebee. In rare cases, when a purchase is made at the Apple App Store/Google Play Store, and the network connection goes off or the server was not responding, the purchase details may not be updated in Chargebee. In such cases, you can use a retry mechanism by following these steps:

  • Save the product identifier in the cache once the purchase is initiated and clear the cache once the purchase/retry validation is successful.
  • When the purchase is completed at Apple App Store/Google Play Store but not synced with Chargebee, retrieve the product from the cache and initiate validateReceipt() by passing productId and Customer as input. This will validate the receipt and sync the purchase in Chargebee as a subscription.

Use the function available for the retry mechanism.

Function for validating the Subscriptions receipt
import Chargebee from '@chargebee/react-native-chargebee';

try {
    const purchase = await Chargebee.validateReceipt(productId, customer)
} catch (error) {
    console.log("error", error);
}
Function for validating the One-Time Purchases receipt
import Chargebee, {
    OneTimePurchase,
    Customer
} from '@chargebee/react-native-chargebee';
const customer: Customer = {
    id: 'id',
    firstName: 'fname',
    lastName: 'lname',
    email: '[email protected]',
};
const productType = ProductType.NON_CONSUMABLE
try {
    const result: OneTimePurchase = await Chargebee.validateReceiptForNonSubscriptions(productId, productType, customer)
} catch (error) {
    console.log("error", error);
}

Contributing

See the contributing guide to learn how to contribute to the repository and the development workflow.

License

Chargebee is available under the MIT license. See the LICENSE file for more info.

chargebee-react-native's People

Contributors

cb-amutha avatar cb-anurags avatar cb-bharathvaj avatar cb-dinesh avatar cb-haripriyan avatar cb-harishbharadwaj avatar cb-imayaselvan avatar cb-pravinrajmohan avatar cb-prem avatar cb-seenivasan avatar cb-sriramthiagarajan avatar cb-vinay avatar dependabot[bot] avatar lovubuntu avatar zhulduz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

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

chargebee-react-native's Issues

Chargebee.retrieveProductIdentifiers crash even within try-catch block

Chargebee.retrieveProducts with specific identifiers work perfectly, but Chargebee.retrieveProductIdentifiers crashes even in try-catch block with message "Signal 6 was raised".

 const test = async () => {
    try {
      console.log('>>>>>test>>>> configure')
      await Chargebee.configure({
        site: 'secret',
        publishableApiKey: 'secret',
        androidSdkKey: 'secret',
        iOsSdkKey: 'secret',
      })
      console.log('>>>>>test>>>> configure done')
      console.log('>>>>>test>>>> start')
      const results = await Chargebee.retrieveProductIdentifiers({
        limit: 10,
      })
      // const results = await Chargebee.retrieveProducts(['specific_product_id']) // working
      console.log('>>>>>test>>>> end', results)
    } catch (err) {
      console.log('>>>test err', err)
    }
  }

IMG_81549959FE9F-1

Environment:
iPhone Xs
iOS 16.6
React Native 0.72.7

I can not retrieve products even though i can retrieve the product identifiers

I have an issue retrieving products on my iOS platform even though I can retrieve their identifiers.
this is how i fetch the product identifiers and i get them back:
const fetchProductsIdentifiers = async () => {
const queryParams = new Map();
queryParams.set("limit", "10");
try {
const result = await Chargebee.retrieveProductIdentifiers(queryParams);
console.log("product identifiers:", result);
} catch (error) {
console.log("Error when fetching product identifiers", error);
console.log(
"=========================",
Platform.OS,
"========================="
);
}
};

but when i call the fetchProducts api with the array returned from the endpoint, i get an [Error: Products not found.]
const fetchProducts = async () => {
try {
const productList = await Chargebee.retrieveProducts([
"Gold_999_1m",
"Silver_199_1m",
"Gold_999_1y",
"Half_yearly_plan_1",
"Yearly_plan_1",
"Monthly_plan_1",
"Weekly_plan_1",
"Daily_plan_1",
]);
setProductIds(productList);
console.log("products:", productList);
} catch (error) {
console.log("Error when fetching product", error);
console.log(
"=========================",
Platform.OS,
"========================="
);
}
};

I have the products i have called all setup on app store connect
So I don't know what might be wrong.

Issue with TypeScript Purchases and OneTime Purchase

Hi! 👋

Firstly, thanks for your work on this project! 🙂

Today I used patch-package to patch @chargebee/[email protected] for the project I'm working on.

Here is the diff that solved my problem:

diff --git a/node_modules/@chargebee/react-native-chargebee/lib/typescript/Purchases.d.ts b/node_modules/@chargebee/react-native-chargebee/lib/typescript/Purchases.d.ts
index 06a1e22..407a0e0 100644
--- a/node_modules/@chargebee/react-native-chargebee/lib/typescript/Purchases.d.ts
+++ b/node_modules/@chargebee/react-native-chargebee/lib/typescript/Purchases.d.ts
@@ -24,9 +24,9 @@ export interface Purchase {
     readonly status: string;
 }
 export interface OneTimePurchase {
-    readonly invoiceId: string;
-    readonly chargeId: string;
-    readonly customerId: string;
+    readonly invoice_id: string;
+    readonly charge_id: string;
+    readonly customer_id: string;
 }
 export declare enum ProductType {
     UNKNOWN = "unknown",
diff --git a/node_modules/@chargebee/react-native-chargebee/src/Purchases.ts b/node_modules/@chargebee/react-native-chargebee/src/Purchases.ts
index 4c339d2..e10bfe5 100644
--- a/node_modules/@chargebee/react-native-chargebee/src/Purchases.ts
+++ b/node_modules/@chargebee/react-native-chargebee/src/Purchases.ts
@@ -30,9 +30,9 @@ export interface Purchase {
 }
 
 export interface OneTimePurchase {
-  readonly invoiceId: string;
-  readonly chargeId: string;
-  readonly customerId: string;
+  readonly invoice_id: string;
+  readonly charge_id: string;
+  readonly customer_id: string;
 }
 
 export enum ProductType {

This issue body was partially generated by patch-package.

Error with Using ChargeBee API's 2.0

Initially, I was using 1 Version APIs to fetch and Subscribe, I haven't faced any issues, but now I am Using 2 Version APIs to fetch the response and Tried to implement it with @chargebee/Chargebee-react-native. I am facing the error as
Error :
"Subscription with New Item Model cannot be created using this Endpoint, Please use create a subscription with item endpoint to create subscription "

Screenshot at Jul 14 18-53-58

Attaching Screenshot for Ref: :
https://lh6.googleusercontent.com/hbin13_kfMjYCveOVgAwpswJmGGsq11unmhdSkPhSSlwou0Ei44AJKxXnmRQERuxlwaV_gn2ReU7F9dKzKJONL_HbnrkvRfHVSMRvfe9VBEWkuc_D8eNrNEF9mYJ-lJtDqL_L3yx-Vis1_WnBfzJf-w3pUydOj6x5b4FYJ9mBBB8DgjRzllDaEdQ4ltMo9-co9Z3HZOMRNSx=w319-h639

<CheckoutCart success={(hostedPageId: string) => successfulPurchase(hostedPageId)} step={(stepName: string) => handleStep(stepName)} site={site} // site Name planName={name} // Plan Name planId={id}. // I am Passing plan Id />

  • Attaching Postman Response screenshot.
  • Thanks in Advance.
    Screenshot at Jul 14 18-35-08

restorePurchases doesn't work

Hi guys, I found out that in 2.4.4 version API restorePurchases doesn't work,
I also tried an example with own config credentials.

Could you please try also, maybe something missing in docs.

Get a `Product Family` field in retrieveSubscriptions API

Hello guys,
I am curious it is possible to get Product Family Chargebee.retrieveSubscriptions end-point?

It would be great to identify on each platform whether the subscription is from appstore/googlestore?

or maybe extra provide filter query for retrieveSubscriptions with platform field.

Getting an error while retrieving all product identifiers

Error: Invalid catalog version
at Object.promiseMethodWrapper [as retrieveProductIdentifiers] (NativeModules.js:105:51)
at Function. (Chargebee.ts:68:33)
at Generator.next ()
at asyncGeneratorStep (asyncToGenerator.js:3:16)
at _next (asyncToGenerator.js:25:9)
at asyncToGenerator.js:32:7
at tryCallTwo (core.js:45:5)
at doResolve (core.js:200:13)
at new Promise (core.js:66:3)
at Function. (asyncToGenerator.js:21:12)

following is the code:
const queryParams = new Map();
queryParams.set("limit", "1");
try {
const result = await Chargebee.retrieveProductIdentifiers(queryParams);
console.log(result);
} catch (error) {
console.log(error);
}

'ChargebeeReactNative-Swift.h' file not found

Hi, I added "@chargebee/react-native-chargebee": "^2.4.5" to my project and now all builds fail with the the following error:

node_modules/@chargebee/react-native-chargebee/ios/ChargebeeReactNative.mm:2:9)

1 | #import "ChargebeeReactNative.h"

2 | #import <ChargebeeReactNative-Swift.h>
| ^ 'ChargebeeReactNative-Swift.h' file not found
3 |
4 | @implementation ChargebeeReactNative
5 | RCT_EXPORT_MODULE()
The following build commands failed:
▸ CompileC /Users/expo/Library/Developer/Xcode/DerivedData/Tallio-bbielmlrqyffaodyqcvcjhdlhgly/Build/Intermediates.noindex/ArchiveIntermediates/Tallio/IntermediateBuildFilesPath/Pods.build/Debug-iphoneos/ChargebeeReactNative.build/Objects-normal/arm64/ChargebeeReactNative.o /Users/expo/workingdir/build/node_modules/@chargebee/react-native-chargebee/ios/ChargebeeReactNative.mm normal arm64 objective-c++ com.apple.compilers.llvm.clang.1_0.compiler (in target 'ChargebeeReactNative' from project 'Pods')
▸ (1 failure)
** ARCHIVE FAILED **
The following build commands failed:
CompileC /Users/expo/Library/Developer/Xcode/DerivedData/Tallio-bbielmlrqyffaodyqcvcjhdlhgly/Build/Intermediates.noindex/ArchiveIntermediates/Tallio/IntermediateBuildFilesPath/Pods.build/Debug-iphoneos/ChargebeeReactNative.build/Objects-normal/arm64/ChargebeeReactNative.o /Users/expo/workingdir/build/node_modules/@chargebee/react-native-chargebee/ios/ChargebeeReactNative.mm normal arm64 objective-c++ com.apple.compilers.llvm.clang.1_0.compiler (in target 'ChargebeeReactNative' from project 'Pods')
(1 failure)

Adding @chargebee/react-native-chargebee to a new project doesn't cause and failed builds, so I am wondering if this has to do with another library that I imported for my project. One of the other libraries I am using (@react-native-firebase/app) uses static frameworks. Here is the implementation instructions from that package:

Open the file ./ios/Podfile and add this line inside your targets (right before the use_react_native line in current react-native releases that calls the react native Podfile function to get the native modules config):

use_frameworks! :linkage => :static
To use Static Frameworks on iOS, you also need to manually enable this for the project with the following global to your /ios/Podfile file:

right after use_frameworks! :linkage => :static

$RNFirebaseAsStaticFramework = true

Would static frameworks be causing the compatibility issues? If not, have you ran into this problem in any other scenarios?

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.