> ## Documentation Index
> Fetch the complete documentation index at: https://cashfreepayments-d00050e9-theme-update.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Subscription Flutter Integration

> Learn more about the subscription flutter sdk integration in your app

### Setting Up SDK

The Flutter SDK is hosted on [https://pub.dev/](https://pub.dev/) you can get the sdk [here](https://pub.dev/packages/flutter_cashfree_pg_sdk). The example app is located [here](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.2.9
```

##### iOS

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

```shell
<key>LSApplicationCategoryType</key>
<string></string>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>phonepe</string>
<string>tez</string>
<string>paytmmp</string>
<string>bhim</string>
<string>amazonpay</string>
</array>
```

```shell
cd ios
pod install --repo-update
```

### Step 1: Creating a Subscription

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-python/blob/master/cashfree_pg/api_client.py#L8502)
  </Accordion>
</AccordionGroup>

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

### Step 2: Opening the Subscription Checkout Payment Page

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
    <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
try {
    var subscriptionSession = CFSubscriptionSessionBuilder().setEnvironment(environment).setSubscriptionId(subscriptionId).setSubscriptionSessionId(subscriptionSessionId).build();
    return subsriptionSession;
} on CFException catch (e) {
    print(e.message);
}
```

#### Customize Theme (Optional)

You can customize 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 color for status bar & cashfree loader

```dart
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
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
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);
}
```

### Step 3: Sample Code

```dart
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 4: Confirming the Payment

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