flutter_hyperswitch 1.0.6 copy "flutter_hyperswitch: ^1.0.6" to clipboard
flutter_hyperswitch: ^1.0.6 copied to clipboard

Flutter Hyperswitch: Simplifying payment integration for Flutter apps with seamless API interactions and customizable UI.

example/lib/main.dart

import 'dart:convert';
import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/material.dart' as material;
import 'package:flutter_hyperswitch/flutter_hyperswitch.dart';
import 'package:flutter_hyperswitch/flutter_hyperswitch.dart' as hyper;
import 'package:http/http.dart' as http;

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

class MyApp extends StatefulWidget {
  const MyApp({super.key});

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

class _MyAppState extends State<MyApp> {
  final String _endpoint =
      Platform.isAndroid ? "http://10.0.2.2:5252" : "http://localhost:5252";
  final _hyper = FlutterHyperswitch();
  bool isButtonEnabled = false;
  int isButtonEnabled2 = 0;
  String _response = '';
  String _defaultPM = '';
  String _status = '';
  bool _showChange = false;
  PaymentMethodSession? paymentMethodSession;
  Session? sessionObject;

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

  Future<void> initPlatformState() async {
    try {
      var response =
          await http.get(Uri.parse("$_endpoint/create-payment-intent"));

      if (response.statusCode == 200) {
        Map<String, dynamic> responseBody = jsonDecode(response.body);
        _hyper
            .init(HyperConfig(publishableKey: responseBody['publishableKey']));
        sessionObject = await _hyper.initPaymentSession(
            PaymentMethodParams(clientSecret: responseBody['clientSecret']));
        setState(() {
          isButtonEnabled = true;
        });
      } else {
        _response = "API Call Failed";
      }
    } catch (error) {
      _response = "API Call Failed";
    }
  }

  Future<void> onPress1() async {
    PaymentResult presentPaymentSheetResponse =
        await sessionObject?.presentPaymentSheet();

    if (!mounted) return;

    setState(() {
      _response = presentPaymentSheetResponse.message;
      if (presentPaymentSheetResponse.status != "cancelled") {
        isButtonEnabled = false;
        initPlatformState();
      }
    });
  }

  Future<void> onPress2() async {
    paymentMethodSession =
        await sessionObject?.getCustomerSavedPaymentMethods();
    Object obj =
        paymentMethodSession?.getCustomerDefaultSavedPaymentMethodData();

    setState(() {
      if (obj is hyper.Card) {
        _defaultPM = "${obj.nickName}  ${obj.cardNumber}  ${obj.expiryDate}";
        isButtonEnabled2 = 2;
        _showChange = true;
      } else if (obj is Wallet) {
        _defaultPM = obj.walletType;
        isButtonEnabled2 = 2;
        _showChange = true;
      } else if (obj is Error) {
        _defaultPM = obj.message;
        _showChange = false;
      }
    });
  }

  Future<void> onPress3() async {
    setState(() {
      isButtonEnabled2 = 1;
    });
    PaymentResult confirmWithCustomerDefaultPaymentMethodResponse =
        await paymentMethodSession?.confirmWithCustomerDefaultPaymentMethod();
    setState(() {
      isButtonEnabled2 = 2;
      _status = confirmWithCustomerDefaultPaymentMethodResponse.message;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            appBar: AppBar(
              title: const Text('Plugin example app'),
            ),
            body: Column(children: [
              Expanded(
                  child: material.Card(
                      elevation: 4,
                      margin: const EdgeInsets.all(18),
                      child: Padding(
                          padding: const EdgeInsets.all(36),
                          child: Column(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                const Center(
                                    child: Text("Headless SDK Example",
                                        style: TextStyle(
                                            fontSize: 16,
                                            fontWeight: FontWeight.w500))),
                                Center(
                                    child: ElevatedButton(
                                        onPressed:
                                            isButtonEnabled ? onPress2 : null,
                                        child: Text(isButtonEnabled
                                            ? "Initialise Headless"
                                            : "Loading ..."))),
                                Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Flexible(child: Text(_defaultPM)),
                                      if (_showChange)
                                        TextButton(
                                            onPressed: onPress1,
                                            child: const Text("Change"))
                                    ]),
                                if (isButtonEnabled2 > 0)
                                  Center(
                                    child: ElevatedButton(
                                        onPressed: isButtonEnabled2 == 2
                                            ? onPress3
                                            : null,
                                        child: Text(isButtonEnabled2 == 1
                                            ? "Processing ..."
                                            : "Confirm Payment")),
                                  ),
                                if (_status != '')
                                  Center(child: Flexible(child: Text(_status)))
                              ])))),
              Expanded(
                  child: material.Card(
                      elevation: 4,
                      margin: const EdgeInsets.only(
                          left: 18, right: 18, bottom: 18),
                      child: Padding(
                          padding: const EdgeInsets.all(36),
                          child: Column(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                const Center(
                                    child: Text("Payment Sheet Example",
                                        style: TextStyle(
                                            fontSize: 16,
                                            fontWeight: FontWeight.w500))),
                                Center(
                                  child: ElevatedButton(
                                      onPressed:
                                          isButtonEnabled ? onPress1 : null,
                                      child: Text(isButtonEnabled
                                          ? "Open Payment Sheet"
                                          : "Loading ...")),
                                ),
                                Center(child: Flexible(child: Text(_response)))
                              ]))))
            ])));
  }
}
1
likes
0
points
1.28k
downloads

Publisher

verified publisherhyperswitch.io

Weekly Downloads

Flutter Hyperswitch: Simplifying payment integration for Flutter apps with seamless API interactions and customizable UI.

Homepage

License

unknown (license)

Dependencies

flutter, http, plugin_platform_interface

More

Packages that depend on flutter_hyperswitch