Flutter with Node Backend

Integrate hyper SDK to your Flutter App using hyperswitch-node

Use this guide to integrate hyper SDK to your Flutter app.

Before following these steps, please configure your payment methods here.

Requirements

1. Setup the server

1.1 Install the hyperswitch-node library

Install the package and import it in your code

$ npm install @juspay-tech/hyperswitch-node

1.2 Create a payment

Before creating a payment, import the hyper dependencies and initialize it with your API key. Get your API key from Hyperswitch dashboard.

const hyper = require("@juspay-tech/hyperswitch-node")(β€˜YOUR_API_KEY’);

Add an endpoint on your server that creates a Payment. Creating a Payment helps to establish the intent of the customer to start a payment. It also helps to track the customer’s payment lifecycle, keeping track of failed payment attempts and ensuring the customer is only charged once. Return the client_secret obtained in the response to securely complete the payment on the client.

// Create a Payment with the order amount and currency
app.post("/create-payment", async (req, res) => {
  try {
    const paymentIntent = await hyper.paymentIntents.create({
      currency: "USD",
      amount: 100,
    });
    // Send publishable key and PaymentIntent details to client
    res.send({
      clientSecret: paymentIntent.client_secret,
    });
  } catch (err) {
    return res.status(400).send({
      error: {
        message: err.message,
      },
    });
  }
});

2. Build checkout page on the client

2.1 Install the flutter_hyperswitch library

Add flutter_hyperswitch to your pubspec.yaml file

dependencies:
  flutter_hyperswitch: ^version_number

Run the following command to fetch and install the dependencies.

flutter pub get

3. Complete the checkout on the client

3.1 Initialise the Hyperswitch SDK

Initialise Hyper onto your app with your publishable key with the Hyper constructor. To get a PublishableKey please find it here.

import 'package:flutter_hyperswitch/flutter_hyperswitch.dart';
final _hyper = FlutterHyperswitch();
_hyper.init(HyperConfig(publishableKey: 'YOUR_PUBLISHABLE_KEY', customBackendUrl: 'YOUR_CUSTOM_BACKEND_URL'));

When utilising a custom backend or logging system, you can add the customBackendUrl to HyperConfig

3.2 Create a Payment Intent

Make a network request to the backend endpoint you created in the previous step. The clientSecret returned by your endpoint is used to complete the payment.

Future<String> fetchPaymentParams() async {
    try {
      var response = await http.get(Uri.parse("$API_URL/create-payment"),
      return jsonDecode(response.body)["clientSecret"];
    } catch (error) {
      throw Exception("Create Payment API call failed");
    }
  }

3.3 Initialize your Payment Session

Initialize a Payment Session by passing the clientSecret to the initPaymentSession

final params = PaymentMethodParams(clientSecret: 'YOUR_PAYMENT_INTENT_CLIENT_SECRET');
Session? _sessionId = await _hyper.initPaymentSession(params);

3.4 Present payment sheet and handle response

To display the Payment Sheet, integrate a "Pay Now" button within the checkout page, which, when clicked, invokes the presentPaymentSheet()method and handles the payment response.

Consider the below function, it invokes presentPaymentSheet and handles payment results.

Future<void> _presentPaymentSheet() async {
  final presentPaymentSheetResponse = await _hyper.presentPaymentSheet(_sessionId!);
  if (presentPaymentSheetResponse != null) {
    final message = presentPaymentSheetResponse.message;
    setState(() {
      if (message.isLeft) {
        _statusText =
            "${presentPaymentSheetResponse.status.name}\n${message.left!.name}";
      } else {
        _statusText =
            "${presentPaymentSheetResponse.status.name}\n${message.right}";
      }
    });
  }
}

Congratulations! Now that you have integrated the Flutter SDK, you can customize the payment sheet to blend with the rest of your app.

Next step:

πŸ’³pagePayment methods setup

Last updated