Debug School

rakesh kumar
rakesh kumar

Posted on

How to integrate All-in-One SDK in flutter app

To integrate Paytm All-in-One SDK in a Flutter app with a Laravel backend using the paytm_allinonesdk dependency, follow these steps. Here we will use paytm_allinonesdk dependency for Flutter.

Step 1: Set up your Flutter project

Create a new Flutter project if you don't already have one.

flutter create paytm_integration
cd paytm_integration
Enter fullscreen mode Exit fullscreen mode

Step 2: Add necessary dependencies

Add the following dependencies to your pubspec.yaml file.

dependencies:
  flutter:
    sdk: flutter
  http: ^0.14.0
  paytm_allinonesdk: ^0.1.6 # Add this dependency for Paytm All-in-One SDK
Enter fullscreen mode Exit fullscreen mode

Step 3: Modify Android files

a. Add the Paytm dependency to android/app/build.gradle

dependencies {
    implementation 'com.paytm.appinvokesdk:appinvokesdk:1.1.1'
    implementation 'com.paytm.appinvoke:appinvoke:1.2.0'
}
Enter fullscreen mode Exit fullscreen mode

b. Add internet permission to android/app/src/main/AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/>
Enter fullscreen mode Exit fullscreen mode

Step 4: Implement the Paytm transaction flow in Flutter

Create a new Dart file, e.g., paytm_service.dart, to handle the Paytm transaction flow.

import 'package:flutter/material.dart';
import 'package:paytm_allinonesdk/paytm_allinonesdk.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;

class PaytmService {
  static const String mid = "YOUR_MERCHANT_ID"; // Replace with your Paytm MID
  static const String website = "WEBSTAGING"; // Use "WEBSTAGING" for testing, "DEFAULT" for production
  static const String industryTypeId = "Retail"; // Your industry type
  static const String callbackUrl = "https://securegw-stage.paytm.in/theia/paytmCallback?ORDER_ID="; // Paytm callback URL

  Future<void> startTransaction(BuildContext context, String orderId, String custId, String amount) async {
    // Generate Checksum
    String checksum = await _generateChecksum(orderId, custId, amount);

    // Initiate Transaction
    _initiateTransaction(context, orderId, custId, amount, checksum);
  }

  Future<String> _generateChecksum(String orderId, String custId, String amount) async {
    String url = "http://your-server-url/api/generate-checksum"; // Replace with your server URL
    Map<String, String> body = {
      'MID': mid,
      'ORDER_ID': orderId,
      'CUST_ID': custId,
      'INDUSTRY_TYPE_ID': industryTypeId,
      'CHANNEL_ID': 'WAP',
      'TXN_AMOUNT': amount,
      'WEBSITE': website,
      'CALLBACK_URL': callbackUrl + orderId,
    };

    http.Response response = await http.post(Uri.parse(url), body: body);
    if (response.statusCode == 200) {
      var jsonResponse = json.decode(response.body);
      return jsonResponse['CHECKSUMHASH'];
    } else {
      throw Exception('Failed to generate checksum');
    }
  }

  void _initiateTransaction(BuildContext context, String orderId, String custId, String amount, String checksum) {
    PaytmAllInOneSdk.startTransaction(
      mid,
      orderId,
      amount,
      'TRANSACTION_TOKEN',
      callbackUrl + orderId,
      true, // Staging
      true, // Restrict AppInvoke
    ).then((value) {
      print(value); // Handle the transaction result here
    }).catchError((error) {
      print(error); // Handle errors here
    });
  }
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Implement the UI and initiate the transaction

In your main UI file, create a button to initiate the Paytm transaction.

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Paytm Integration',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  final PaytmService paytmService = PaytmService();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Paytm Integration'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            // Replace these values with your actual order details
            String orderId = 'ORDER_ID';
            String custId = 'CUSTOMER_ID';
            String amount = '1.00';

            paytmService.startTransaction(context, orderId, custId, amount);
          },
          child: Text('Pay with Paytm'),
        ),
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Step 6: Backend for generating checksum with Laravel

Create a Laravel project if you don't already have one.

composer create-project --prefer-dist laravel/laravel paytm_backend
cd paytm_backend
Enter fullscreen mode Exit fullscreen mode

Install Paytm checksum package

Install the Paytm checksum package via Composer.

composer require paytm/pg
Enter fullscreen mode Exit fullscreen mode

Create an API route

Add a new route in routes/api.php to handle the checksum generation.

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PaytmController;

Route::post('/generate-checksum', [PaytmController::class, 'generateChecksum']);
Enter fullscreen mode Exit fullscreen mode

Create the PaytmController
Create a new controller using Artisan.

php artisan make:controller PaytmController
Enter fullscreen mode Exit fullscreen mode

Implement the checksum generation logic in PaytmController
Add the following code to app/Http/Controllers/PaytmController.php.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use PaytmChecksum;

class PaytmController extends Controller
{
    public function generateChecksum(Request $request)
    {
        $paytmParams = $request->all();
        $merchantKey = 'YOUR_MERCHANT_KEY'; // Replace with your Paytm Merchant Key

        $checksum = PaytmChecksum::generateSignature($paytmParams, $merchantKey);

        return response()->json(['CHECKSUMHASH' => $checksum]);
    }
}
Enter fullscreen mode Exit fullscreen mode

Using Paytm Package

here is a step-by-step guide to integrate Paytm in a Flutter app using paytm: ^3.0.1 with a Laravel backend and using flutteronesdkdependencies without using WebView.

Step 1: Set Up Laravel Backend

  1. Install Paytm All-in-One SDK First, install the Paytm All-in-One SDK package for Laravel via Composer:
composer require paytm/paytm-sdk
Enter fullscreen mode Exit fullscreen mode
  1. Create Paytm Controller Create a new controller to handle Paytm transactions:
php artisan make:controller PaytmController
Enter fullscreen mode Exit fullscreen mode
  1. Configure Paytm Credentials In your .env file, add your Paytm credentials:
PAYTM_MERCHANT_ID=your_merchant_id
PAYTM_MERCHANT_KEY=your_merchant_key
PAYTM_WEBSITE=WEBSTAGING
PAYTM_CHANNEL=WEB
PAYTM_INDUSTRY_TYPE_ID=Retail
PAYTM_CALLBACK_URL=https://yourdomain.com/paytm/callback
Enter fullscreen mode Exit fullscreen mode
  1. Add Routes In your routes/web.php file, add routes for initiating the payment and handling the callback:
Route::post('paytm/payment', [PaytmController::class, 'initiatePayment']);
Route::post('paytm/callback', [PaytmController::class, 'handleCallback']);
Enter fullscreen mode Exit fullscreen mode
  1. Implement Paytm Controller Methods In PaytmController.php, implement the methods for initiating the payment and handling the callback:
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use PaytmWallet;

class PaytmController extends Controller
{
    public function initiatePayment(Request $request)
    {
        $payment = PaytmWallet::with('receive');
        $payment->prepare([
            'order' => $request->order_id,
            'user' => $request->user_id,
            'mobile_number' => $request->mobile_number,
            'email' => $request->email,
            'amount' => $request->amount,
            'callback_url' => env('PAYTM_CALLBACK_URL')
        ]);
        return $payment->receive();
    }

    public function handleCallback(Request $request)
    {
        $transaction = PaytmWallet::with('receive');
        $response = $transaction->response();

        if ($transaction->isSuccessful()) {
            // Payment successful
            return response()->json(['status' => 'success', 'data' => $response]);
        } else if ($transaction->isFailed()) {
            // Payment failed
            return response()->json(['status' => 'failed', 'data' => $response]);
        } else if ($transaction->isOpen()) {
            // Payment open/pending
            return response()->json(['status' => 'pending', 'data' => $response]);
        }
        // Payment response
        return response()->json(['status' => 'error', 'data' => $response]);
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 2: Set Up Flutter Frontend

  1. Add Dependencies In your pubspec.yaml file, add the required dependencies:
dependencies:
  flutter:
    sdk: flutter
  paytm: ^3.0.1
Enter fullscreen mode Exit fullscreen mode
  1. Create Payment Service Create a new service to handle the payment request in Flutter:
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:paytm/paytm.dart';

class PaymentService {
  Future<void> initiatePayment({
    required String orderId,
    required String userId,
    required String mobileNumber,
    required String email,
    required double amount,
  }) async {
    final url = Uri.parse('https://yourdomain.com/paytm/payment');
    final response = await http.post(url, body: {
      'order_id': orderId,
      'user_id': userId,
      'mobile_number': mobileNumber,
      'email': email,
      'amount': amount.toString(),
    });

    if (response.statusCode == 200) {
      final paymentData = json.decode(response.body);

      if (paymentData['status'] == 'success') {
        final txnToken = paymentData['txnToken'];
        final mid = 'your_merchant_id';
        final orderId = paymentData['orderId'];
        final amount = paymentData['amount'].toString();

        final paytmResponse = await Paytm.payWithPaytm(
          mId: mid,
          orderId: orderId,
          txnToken: txnToken,
          txnAmount: amount,
          callBackUrl: 'https://securegw-stage.paytm.in/theia/paytmCallback?ORDER_ID=$orderId',
          staging: true,
          appInvokeEnabled: true,
        );

        if (paytmResponse['error']) {
          print('Payment failed: ${paytmResponse['errorMessage']}');
        } else {
          print('Payment successful: ${paytmResponse['response']}');
        }
      } else {
        print('Payment initiation failed: ${paymentData['data']}');
      }
    } else {
      print('Server error: ${response.body}');
    }
  }
}
Enter fullscreen mode Exit fullscreen mode
  1. Implement Payment Button In your Flutter app, create a button to initiate the payment:
import 'package:flutter/material.dart';
import 'payment_service.dart';

class PaymentPage extends StatelessWidget {
  final PaymentService paymentService = PaymentService();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Paytm Payment'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            paymentService.initiatePayment(
              orderId: 'ORDER12345',
              userId: 'USER123',
              mobileNumber: '9999999999',
              email: 'user@example.com',
              amount: 100.0,
            );
          },
          child: Text('Pay with Paytm'),
        ),
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Reference
Reference2

Top comments (0)