cashfree 0.1.1

  • Readme
  • Changelog
  • Example
  • Installing
  • 68

Cashfree Flutter SDK #

author #

zhaolongzhaoyuen123@126.com

Integration Steps #

Step 1: Add Dependency #

  cashfree: 0.0.1

<br/>

Step 2: Add permissions (Android) #

The Cashfree PG SDK requires that you add the INTERNET permission in your Android Manifest file.

<manifest ...>
    <uses-permission android:name="android.permission.INTERNET" />
<application ...>

Step 3: Add plist value (iOS) #

Opt-in to the embedded views preview by adding a boolean property to the app's Info.plist file with the key io.flutter.embedded_views_preview and the value YES. This is required by the flutter_webview plugin.

    <key>io.flutter.embedded_views_preview</key>
    <true/>

Step 4: Generate Token (From Backend) #

You will need to generate a token from your backend and pass it to app while initiating payments. For generating token you need to use our token generation API. Please take care that this API is called only from your as it uses secretKey. Thus this API should never be called from App.

Request Description #

You need to send orderId, orderCurrency and orderAmount as a JSON object to the API endpoint and in response a token will received. Please see the description of request below.

curl -XPOST -H 'Content-Type: application/json' 
-H 'x-client-id: <YOUR_APP_ID>' 
-H 'x-client-secret: <YOUR_SECRET_KEY>' 
-d '{
  "orderId": "<ORDER_ID>",
  "orderAmount":<ORDER_AMOUNT>,
  "orderCurrency": "INR"
}' 'https://test.cashfree.com/api/v2/cftoken/order'

<br/>

Request Example #

Replace YOUR_APP_ID and YOUR_SECRET_KEY with actual values.

curl -XPOST -H 'Content-Type: application/json' -H 'x-client-id: YOUR_APP_ID' -H 'x-client-secret: YOUR_SECRET_KEY' -d '{
  "orderId": "Order0001",
  "orderAmount":1,
  "orderCurrency":"INR"
}' 'https://test.cashfree.com/api/v2/cftoken/order'

Response Example #

{
"status": "OK",
"message": "Token generated",
"cftoken": "v79JCN4MzUIJiOicGbhJCLiQ1VKJiOiAXe0Jye.s79BTM0AjNwUDN1EjOiAHelJCLiIlTJJiOik3YuVmcyV3QyVGZy9mIsEjOiQnb19WbBJXZkJ3biwiIxADMwIXZkJ3TiojIklkclRmcvJye.K3NKICVS5DcEzXm2VQUO_ZagtWMIKKXzYOqPZ4x0r2P_N3-PRu2mowm-8UXoyqAgsG"
}

The "cftoken" is the token that is used authenticate your payment request that will be covered in the next step.

Step 5: Initiate Payment #

  • App passes the order info and the token to the SDK
  • Customer is shown the payment screen where he completes the payment
  • Once the payment is complete SDK verifies the payment
  • App receives the response from SDK and handles it appropriately

How to integrate #

For both the modes (normal and seamless) you need to invoke the doPayment() method. However, there are a few extra parameters you need to pass incase of seamless mode.

doPayment #

    var options = {
      'token': "token",
      'stage': "you stage",
      'appId': "you appId",
      'orderId': "you orderId",
      'orderAmount': 100,
      'orderNote': "TestNote",
      'orderCurrency': "INR",
      'customerName': "Test",
      'customerPhone': "15264328733",
      'customerEmail': "test@126.com",
      'notifyUrl': 'notifyUrl',
      "paymentModes": 'paymentModes'
    };
    _cashfree.doPayment(options);

Initiates the payment in a webview. The customer will be taken to the payment page on cashfree server where they will have the option of paying through any payment option that is activated on their account. Once the payment is done the webview will close and the response will be delivered in the callback.

options:

  • token: The token generated from Step 4.

  • stage: Value should be either "TEST" or "PROD" for testing server or production server respectively.

  • color1: Toolbar background color

  • color2: Toolbar text and back arrow color

  • hideOrderId: Whether to show the order number is hidden by default [bool]

    var options = {
      'token': "token",
      'stage': "you stage",
      'appId': "you appId",
      'orderId': "you orderId",
      'orderAmount': 100,
      'orderNote': "TestNote",
      'orderCurrency': "INR",
      'customerName': "Test",
      'customerPhone': "15264328733",
      'customerEmail': "test@126.com",
      'notifyUrl': 'notifyUrl',
      "paymentModes": 'paymentModes'
    };
    _cashfree.upiPayment(options);

Initiate the payment in a webview. The customer will be taken to the payment page on cashfree server where they will have the option of paying through any payment option that is activated on their account. Once the payment is done the webview will close and the response will be delivered in the callback.

option:

  • token: The token generated from Step 4.

  • stage: Value should be either "TEST" or "PROD" for testing server or production server respectively.

example #

    final Cashfree _cashfree = Cashfree();
    _cashfree.on(Cashfree.EVENT_PAYMENT_SUCCESS, _handleCashfreePaymentSuccess);
    _cashfree.on(Cashfree.EVENT_PAYMENT_ERROR, _handleCashfreePaymentError);
    _cashfree.on(Cashfree.EVENT_ERROR, _handleCashfreeError);
    
    // 支付成功处理
    void _handleCashfreePaymentSuccess(
      CashfreePaymentSuccessResponse response) async {
      print("Cashfree payment success orderId:${response.orderId}");
    }
    
    // 支付失败事件处理
    void _handleCashfreePaymentError(
      CashfreePaymentFailureResponse response) async {
        print("Cashfree payment error msg:${response.txMsg}, status: ${response.txStatus}");
    }
    
    // 错误事件处理
    void _handleCashfreeError(CashfreeError cashfreeError) async {
        print("Cashfree error:${cashfreeError.message}");
    }

Request Parameters #

ParameterRequiredDescription
appIdYesYour app id
orderIdYesOrder/Invoice Id
orderAmountYesBill amount of the order
orderNoteNoA help text to make customers know more about the order
orderCurrencyYesCurrency code of the order. Default is INR.
customerNameNoName of the customer
customerPhoneYesPhone number of customer
customerEmailYesEmail id of the customer
notifyUrlNoNotification URL for server-server communication. Useful when user’s connection drops after completing payment.
paymentModesNoAllowed payment modes for this order. Available values: cc, dc, nb, paypal, upi, wallet. Leave it blank if you want to display all modes

Response parameters #

These parameters are sent as extras to the onActivityResult(). They contain the details of the transaction.

ParameterDescription
orderIdOrder id for which transaction has been processed. Ex: GZ-212
orderAmountAmount of the order. Ex: 256.00
paymentModePayment mode of the transaction.
referenceIdCashfree generated unique transaction Id. Ex: 140388038803
txStatusPayment status for that order. Values can be : SUCCESS, FLAGGED, PENDING, FAILED, CANCELLED.
paymentModePayment mode used by customer to make the payment. Ex: DEBIT_CARD, MobiKwik, etc
txMsgMessage related to the transaction. Will have the reason, if payment failed
txTimeTime of the transaction
typeFixed value : CashFreeResponse. To identify the response is from cashfree SDK.
signatureResponse signature, more here.

NOTE #

There can be scenarios where the SDK is not able to verify the payment within a short period of time. The status of such orders will be PENDING

0.0.1 #

Android version completed

0.1.1 #

aar maven

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:cashfree/cashfree.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final Cashfree _cashfree = Cashfree();

  @override
  void initState() {
    super.initState();

    // 初始化Cashfree
    _cashfree.on(Cashfree.EVENT_PAYMENT_SUCCESS, _handleCashfreePaymentSuccess);
    _cashfree.on(Cashfree.EVENT_PAYMENT_ERROR, _handleCashfreePaymentError);
    _cashfree.on(Cashfree.EVENT_ERROR, _handleCashfreeError);
  }

  @override
  void dispose() {
    super.dispose();
    _cashfree.clear();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: SizedBox(
            height: 150,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                RaisedButton(
                  onPressed: _doPayment,
                  child: Text("doPayment"),
                ),
                RaisedButton(
                  onPressed: _upiPayment,
                  child: Text("upiPayment"),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }

  void _doPayment() {

    var options = {
      'token': "y99JCN4MzUIJiOicGbhJCLiQ1VKJiOiAXe0Jye.Gm0nIwQWO4QjNyUDOwQWZ1IiOiQHbhN3XiwCO3gTNxMzM5UTM6ICc4VmIsISOyUDMwIDMyQ3clRlI6ICZJJXZkJ3biwiIS5USiojI5NmblJnc1NkclRmcvJCLwATM6ICduV3btFkclRmcvJye.MTKRzp9dPtKos6ZgZtqn_03qR259hYti-hXb6om86YAlQTETO6ZVDOxRsSx-YAayRI",
      'stage': "TEST",
      'appId': "14375168c50ba084d18e92a3e57341",
      'orderId': "Test20200529",
      'orderAmount': 100,
      'orderNote': "TestNote",
      'orderCurrency': "INR",
      'customerName': "Test",
      'customerPhone': "15264328733",
      'customerEmail': "test@126.com",
      'notifyUrl': '',
      "paymentModes": ''
    };
    _cashfree.doPayment(options);
  }

  void _upiPayment() {
    var options = {
      'token': "639JCN4MzUIJiOicGbhJCLiQ1VKJiOiAXe0Jye.rPQficTZxMDMjRTY5ADZlVjI6ICdsF2cfJCLykjMxIzMzkTNxojIwhXZiwiIxETOyUDMwIDMyQ3clRlI6ICZJJXZkJ3biwiIS5USiojI5NmblJnc1NkclRmcvJCLwATM6ICduV3btFkclRmcvJye.g7ldJ_Oo7Ea-F2cHU87S_tIP5spAwNCc0xKMH_SiySeuz33JPlQhjkUEyCx7lnwHXT",
      'stage': "TEST",
      'appId': "14375168c50ba084d18e92a3e57341",
      'orderId': "Test2020052911",
      'orderAmount': 100,
      'orderNote': "TestNote",
      'orderCurrency': "INR",
      'customerName': "Test",
      'customerPhone': "15264328733",
      'customerEmail': "test@126.com",
      'notifyUrl': '',
      "paymentModes": ''
    };
    _cashfree.upiPayment(options);
  }

  // 支付成功处理
  void _handleCashfreePaymentSuccess(
      CashfreePaymentSuccessResponse response) async {
    print("Cashfree payment success orderId:${response.orderId}");
  }

  // 支付失败事件处理
  void _handleCashfreePaymentError(
      CashfreePaymentFailureResponse response) async {
    print(
        "Cashfree payment error msg:${response.txMsg}, status: ${response.txStatus}");
  }

  // 错误事件处理
  void _handleCashfreeError(CashfreeError cashfreeError) async {
    print("Cashfree error:${cashfreeError.message}");
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  cashfree: ^0.1.1

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:cashfree/cashfree.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
44
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
80
Overall:
Weighted score of the above. [more]
68
Learn more about scoring.

We analyzed this package on Jul 2, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.8.4
  • pana: 0.13.13
  • Flutter: 1.17.5

Analysis suggestions

Package does not support Flutter platform ios

Because of import path [package:cashfree/cashfree.dart] that declares support for platforms: android

Package does not support Flutter platform linux

Because of import path [package:cashfree/cashfree.dart] that declares support for platforms: android

Package does not support Flutter platform macos

Because of import path [package:cashfree/cashfree.dart] that declares support for platforms: android

Package does not support Flutter platform web

Because of import path [package:cashfree/cashfree.dart] that declares support for platforms: android

Package does not support Flutter platform windows

Because of import path [package:cashfree/cashfree.dart] that declares support for platforms: android

Package not compatible with SDK dart

because of import path [cashfree] that is in a package requiring null.

Health issues and suggestions

Document public APIs. (-0.25 points)

38 out of 39 API elements have no dartdoc comment.Providing good documentation for libraries, classes, functions, and other API elements improves code readability and helps developers find and use your API.

Maintenance suggestions

The package description is too short. (-20 points)

Add more detail to the description field of pubspec.yaml. Use 60 to 180 characters to describe the package, what it does, and its target use case.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.7.0 <3.0.0
eventify ^0.1.4 0.1.4
flutter 0.0.0
Transitive dependencies
collection 1.14.12 1.14.13
meta 1.1.8
sky_engine 0.0.99
typed_data 1.1.6 1.2.0
vector_math 2.0.8
Dev dependencies
flutter_test