> ## Documentation Index
> Fetch the complete documentation index at: https://www.cashfree.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# React Native Integration

> Integrate the Cashfree Subscription React Native SDK in your app to authorise mandates and run recurring payments across UPI, cards, and netbanking smoothly.

### Setting up SDK <Badge color="orange">Client-side</Badge>

The React Native SDK is available on [npm.org](https://www.npmjs.com/package/react-native-cashfree-pg-sdk). You can [get the latest SDK 2.4.0 from npm](https://www.npmjs.com/package/react-native-cashfree-pg-sdk).<br />
The SDK supports Android SDK version 19 and later, and iOS 10.3 and later.

To install the SDK, run the following command in your project directory:

<CodeGroup>
  ```npm npm theme={"dark"}
  npm install react-native-cashfree-pg-sdk
  ```

  ```yarn yarn theme={"dark"}
  yarn add react-native-cashfree-pg-sdk
  ```

  ```expo expo theme={"dark"}
  npx expo install react-native-cashfree-pg-sdk
  npx expo install expo-dev-client
  npx expo prebuild  //mandatory for expo
  npx expo run:android
  npx expo run:ios
  ```
</CodeGroup>

#### iOS

Add this to your application's `info.plist` file.

```shell theme={"dark"}
<key>LSApplicationQueriesSchemes</key>
<array>
  <string>phonepe</string>
  <string>tez</string>
  <string>paytmmp</string>
  <string>bhim</string>
  <string>amazonpay</string>
  <string>credpay</string>
</array>
```

```shell theme={"dark"}
cd ios
pod install --repo-update
```

### Step 1: Creating a subscription <Badge color="green">Server-side</Badge>

Before you can process payments, you must create a subscription. Create an API endpoint on your server that generates the subscription and communicates with your frontend.

<Tip>Always create subscriptions from your backend. This API requires your secret key. Never call it directly from your mobile app. </Tip>
Use any of the following backend SDKs:

<AccordionGroup>
  <Accordion title="Node">
    [Creating Subscription from Node SDK](https://github.com/cashfree/cashfree-pg-sdk-nodejs/blob/main/api.ts#L31393)
  </Accordion>

  <Accordion title="Java">
    [Creating Subscription from Java SDK](https://github.com/cashfree/cashfree-pg-sdk-java/blob/main/src/main/java/com/cashfree/pg/Cashfree.java)
  </Accordion>

  <Accordion title="Golang">
    [Creating Subscription from Golang SDK](https://github.com/cashfree/cashfree-pg/blob/main/api_subscription.go#L1288)
  </Accordion>

  <Accordion title="Dotnet">
    [Creating Subscription from Dotnet SDK](https://github.com/cashfree/cashfree-pg-sdk-dotnet/blob/master/src/cashfree_pg/Client/ApiClient.cs#L9375)
  </Accordion>

  <Accordion title="Python">
    [Creating Subscription from Python SDK](https://github.com/cashfree/cashfree-pg-sdk-python/blob/master/cashfree_pg/api_client.py#L8502)
  </Accordion>

  <Accordion title="PHP">
    [Creating Subscription from PHP SDK](https://github.com/cashfree/cashfree-pg-sdk-php)
  </Accordion>
</AccordionGroup>

After you create the subscription, you receive a `subscription_id` and a `subscription_session_id`.

### Step 2: Opening the subscription checkout payment page <Badge color="orange">Client-side</Badge>

After creating the subscription, open the payment page so the customer can complete the payment.

To complete the payment:

1. Enable Subscription flow flag in Android Manifest
2. Create a `CFSubscriptionSession` object.
3. Set payment callback.
4. Initiate the payment

#### Enable subscription flow flag

Add the following entry inside the `<application>` tag in your Android manifest file. If you do not enable the `cashfree_subscription_flow_enable` flag, the SDK will not provide a payment callback.
<Note>Add this entry inside the `<application>` tag, not inside the `<activity>` tag.</Note>

<CodeGroup>
  ```java java theme={"dark"}
    <application
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name">

        <meta-data
            android:name="cashfree_subscription_flow_enable"
            android:value="true"
            tools:replace="android:value"/>
    </application>
  ```
</CodeGroup>

#### Create a subscription session

This object contains essential information about the subscription, including the subscription session ID (`subscription_session_id`) and subscription ID (`subscription_id`) obtained from creation step. It also specifies the environment (sandbox or production).

```typescript theme={"dark"}
import {
  CFEnvironment,
  CFSubscriptionSession,
} from 'cashfree-pg-api-contract';

try {
      const session = new CFSubscriptionSession(
        'subscription_session_id',
        'subscription_id',
        CFEnvironment.SANDBOX
      );
}
catch (e: any) {
      console.log(e.message);
}
```

#### Setup payment callback

You need to set up callback handlers to handle events after payment processing. This must be set before calling `doSubscriptionPayment`.

```typescript theme={"dark"}
onVerify(orderID: string)
onError(error: CFErrorResponse, orderID: string)
```

<Note>Make sure to set the callback at componentDidMount and remove the callback at componentWillUnmount as this also handles the activity restart cases and prevents memory leaks.</Note>

<Tip>Always call setCallback before calling `doSubscriptionPayment` method of SDK</Tip>

```typescript theme={"dark"}
import {
  CFErrorResponse,
  CFPaymentGatewayService,
} from 'react-native-cashfree-pg-sdk';

export default class App extends Component {
  constructor() {
    super();
  }

  componentDidMount() {
    console.log('MOUNTED');
    CFPaymentGatewayService.setCallback({
      onVerify(orderID: string): void {
        this.changeResponseText('orderId is :' + orderID);
      },
      onError(error: CFErrorResponse, orderID: string): void {
        this.changeResponseText(
          'exception is : ' + JSON.stringify(error) + '\norderId is :' + orderID
        );
      },
    });
  }

  componentWillUnmount() {
    console.log('UNMOUNTED');
    CFPaymentGatewayService.removeCallback();
  }
}
```

#### Initiate the payment

Call `doSubscriptionPayment()` to open the Cashfree subscription checkout screen. This will present the user with the payment options and handle the payment process.

```typescript theme={"dark"}
async _startSubscriptionCheckout() {
    try {
        const session = CFSubscriptionSession(
            'subscription_session_id',
            'subscription_id',
            CFEnvironment.PRODUCTION/SANDBOX,
        );
        CFPaymentGatewayService.doSubscriptionPayment(session);

    } catch (e: any) {
        console.log(e.message);
    }
}
```

### Sample code

```typescript theme={"dark"}
import * as React from 'react';
import {Component} from 'react';

} from 'react-native';
import {
  CFErrorResponse,
  CFPaymentGatewayService,
  CFCard,
} from 'react-native-cashfree-pg-sdk';
import {
  CFEnvironment,
  CFSubscriptionSession,
} from 'cashfree-pg-api-contract';


export default class App extends Component {
  componentWillUnmount() {
    console.log('UNMOUNTED');
    CFPaymentGatewayService.removeCallback();
  }

  componentDidMount() {
    console.log('MOUNTED');
    CFPaymentGatewayService.setCallback({
      onVerify(orderID: string): void {
        console.log('orderId is :' + orderID);
      },
      onError(error: CFErrorResponse, orderID: string): void {
        console.log(
          'exception is : ' +
            JSON.stringify(error) +
            '\norderId is :' +
            orderID,
        );
      },
    });
  }

  async _startSubscriptionCheckout() {
    try {
      const session = CFSubscriptionSession(
            'subscription_session_id',
            'subscription_id',
            CFEnvironment.PRODUCTION/SANDBOX,
        );
      CFPaymentGatewayService.doSubscriptionPayment(session);
    } catch (e: any) {
      console.log(e.message);
    }
  }

  render() {
    return (
      <ScrollView>
          <View style={styles.button}>
            <Button
              onPress={() => this._startSubscriptionCheckout()}
              title="Start Subscription Checkout"
            />
      </ScrollView>
    );
  }
}
```

<Note>This SDK is compatible with expo framework.
[Sample Expo framework](https://github.com/kishan-cashfree/Expo-RN_Cashfree_SDK)</Note>

### Step 3: Confirming the payment <Badge color="green">Server-side</Badge>

After the payment is completed, confirm the subscription status to verify whether the payment was successful. The user will return to your activity after checkout.

<Note>You must always verify payment status from your backend. Before delivering the goods or services, please ensure you check the subscription status from your backend. Ensure you check the subscription status from your server endpoint.</Note>

### Testing

To test your integration:

1. Open the Network tab in your browser’s developer tools.
2. Click the button and check the console logs.
3. Use console.log(session) inside your button click listener to confirm the correct error returned.
