> ## 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.

# Flutter Integration

> Integrate the Cashfree Subscription Flutter SDK in your Flutter app to authorise mandates and process recurring payments across UPI, cards, and netbanking.

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

The Flutter SDK is hosted on [https://pub.dev/](https://pub.dev/) you can get the SDK [2.4.0+52](https://pub.dev/packages/flutter_cashfree_pg_sdk). View the [example app on GitHub](https://github.com/cashfree/flutter-cashfree-pg-sdk/blob/00cd08f3d9657702bbad2c4fa12044e2a3117678/example/lib/main.dart#L296).

Our Flutter SDK supports Android SDK version 19 and above and iOS minimum deployment target of 11 and above. Open your project's `pubspec.yaml` and add the following under dependencies:

```
dependencies:
  flutter_cashfree_pg_sdk: 2.4.0+52
```

#### 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>

The first step in the Subscription Checkout integration is to create a subscription. You need to do this before any payment can be processed. You can add an endpoint to your server which creates this subscription and is used for communication with your frontend.

<Tip>Subscription creation must happen from your backend (as this API uses your secret key). Please do not call this directly from your mobile application. You can use below-mentioned backend SDKs</Tip>

<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>

Once you create subscription, you will get the `subscription_id` and `subscription_session_id`

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

Once the subscription is created, the next step is to open the payment page so the customer can make the payment.

To complete the payment, we can follow the following steps:

1. Enable Subscription flow flag in Android Manifest
2. Create a `CFSubscriptionSession` object.
3. Create a `CFTheme` object (Optional).
4. Create a `CFSubscriptionPayment` object.
5. Set payment callback.
6. Initiate the payment using the payment object created from \[step 3]

We go through these step by step below.

#### Enable subscription flow flag

Add the Below entry to your Android manifest file. If you don't enable `cashfree_subscription_flow_enable` flag, SDK won't provide a payment callback.
<Note>It should be added inside application tag, not inside 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).

```dart theme={"dark"}
try {
    var subscriptionSession = CFSubscriptionSessionBuilder().setEnvironment(environment).setSubscriptionId(subscriptionId).setSubscriptionSessionId(subscriptionSessionId).build();
    return subsriptionSession;
} on CFException catch (e) {
    print(e.message);
}
```

#### Customise theme (optional)

You can customise the appearance of the checkout screen using `CFTheme`. This step is optional but can help maintain consistency with your app's design.
You can set the `NavigationBarBackgroundColor` which will set the colour for status bar and cashfree loader

```dart theme={"dark"}
var theme = CFThemeBuilder()
          .setNavigationBarBackgroundColorColor("#ffffff")
          .setNavigationBarTextColor("#ffffff")
          .build();
```

#### Create subscription payment object

Use `CFSubscriptionPaymentBuilder` to create the payment object. This object accepts a `CFSubscriptionSession`, like the one created in the previous step.

```dart theme={"dark"}
var cfSubscriptionCheckout = CFSubscriptionPaymentBuilder()
  .setSession(subscriptionSession!)
  .setTheme(theme)
  .build();
```

#### Setup payment callback

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

```dart theme={"dark"}
void onSubscriptionVerify(String subscriptionId) {
    print("Verify Subscription ===> $subscriptionId");
 }

void onSubscriptionFailure(CFErrorResponse errorResponse, String data) {
    print("Failure in subscription flow");
}

var cfPaymentGatewayService = CFPaymentGatewayService();
@override
void initState() {
  super.initState();
  cfPaymentGatewayService.setCallback(onSubscriptionVerify, onSubscriptionFailure);
}
```

#### Sample code

```dart theme={"dark"}
import 'package:flutter/material.dart';
import 'package:flutter_cashfree_pg_sdk/api/cferrorresponse/cferrorresponse.dart';
import 'package:flutter_cashfree_pg_sdk/api/cfpayment/cfsubscriptioncheckoutpayment.dart';
import 'package:flutter_cashfree_pg_sdk/api/cfpaymentgateway/cfpaymentgatewayservice.dart';
import 'package:flutter_cashfree_pg_sdk/api/cfsession/cfsubssession.dart';
import 'package:flutter_cashfree_pg_sdk/api/cftheme/cftheme.dart';
import 'package:flutter_cashfree_pg_sdk/utils/cfenums.dart';
import 'package:flutter_cashfree_pg_sdk/utils/cfexceptions.dart';

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  var cfPaymentGatewayService = CFPaymentGatewayService();
  CFEnvironment environment = CFEnvironment.SANDBOX;
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Column(
            children: [
              TextButton(
                  onPressed: () => susbcriptionCheckout(),
                  child: const Text("Subscription Web Checkout Flow")),
            ],
          ),
        ),
      ),
    );
  }

  susbcriptionCheckout() async {
    try {
      cfPaymentGatewayService.setCallback(onSubscriptionVerify, onSubscriptionFailure);
      var subsriptionSession = CFSubscriptionSessionBuilder()
            .setEnvironment(environment)
            .setSubscriptionId(subscriptionId)
            .setSubscriptionSessionId(subscriptionSessionId)
            .build();
      
      var theme = CFThemeBuilder()
          .setNavigationBarBackgroundColorColor("#ffffff")
          .setNavigationBarTextColor("#ffffff")
          .build();
      var cfsubscriptionCheckout = CFSubscriptionPaymentBuilder()
          .setSession(subsriptionSession)
          .setTheme(theme)
          .build();
      cfPaymentGatewayService.doPayment(cfsubscriptionCheckout);
    } on CFException catch (e) {
      print(e.message);
    }
  }

  void onSubscriptionVerify(String subscriptionId) {
    print("Verify Subscription ===> $subscriptionId");
  }

  void onSubscriptionFailure(CFErrorResponse errorResponse, String data) {
    print(errorResponse.getMessage());
  }
}

```

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

After the payment is completed, you need to confirm whether the payment was successful by checking the subscription status. Once the payment finishes, the user will be redirected back to your activity.

<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

You should now have a working checkout button that redirects your customer to Cashfree Subscription Checkout. If your integration isn’t working:

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.
