flutter_hyperswitch 1.1.0 copy "flutter_hyperswitch: ^1.1.0" to clipboard
flutter_hyperswitch: ^1.1.0 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:io';
import 'package:flutter/material.dart';
import 'package:flutter_hyperswitch/flutter_hyperswitch.dart' hide Card;
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();

  Session? _sessionId;
  SavedSession? _savedSessionId;

  String _statusText = '';
  String _defaultPMText = '';
  String _confirmStatusText = '';

  bool _isInitialized = false;
  bool _showChangeButton = false;

  int _confirmState = 0;

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

  Future<void> _initPlatformState() async {
    try {
      final response =
          await http.get(Uri.parse("$_endpoint/create-payment-intent"));
      if (response.statusCode == 200) {
        final responseBody = jsonDecode(response.body) as Map<String, dynamic>;
        _hyper
            .init(HyperConfig(publishableKey: responseBody['publishableKey']));
        _sessionId = await _hyper.initPaymentSession(PaymentMethodParams(
            clientSecret: responseBody['clientSecret'],
            configuration: Configuration(
                appearance: Appearance(
                    shapes: Shapes(
                        shadow: Shadow(color: "#00000050", intensity: 5)),
                    primaryButton: PrimaryButton(
                        shapes: Shapes(
                            shadow:
                                Shadow(color: "#000000", intensity: 2)))))));
        setState(() {
          _isInitialized = _sessionId != null;
          _statusText =
              _isInitialized ? _statusText : "initPaymentSession failed";
        });
      } else {
        setState(() {
          _statusText = "API Call Failed";
        });
      }
    } catch (error) {
      setState(() {
        _statusText = error.toString();
      });
    }
  }

  Future<void> _initializeHeadless() async {
    try {
      if (_sessionId != null) {
        _savedSessionId =
            await _hyper.getCustomerSavedPaymentMethods(_sessionId!);
        if (_savedSessionId != null) {
          final obj = await _hyper
              .getCustomerDefaultSavedPaymentMethodData(_savedSessionId!);
          if (obj != null) {
            final paymentMethod = obj.left;
            if (paymentMethod != null) {
              final card = paymentMethod.left;
              if (card != null) {
                setState(() {
                  _defaultPMText =
                      "${card.nickName}  ${card.cardNumber}  ${card.expiryDate}";
                  _confirmState = 2;
                  _showChangeButton = true;
                });
              } else {
                final wallet = paymentMethod.right;
                if (wallet != null) {
                  setState(() {
                    _defaultPMText = wallet.walletType;
                  });
                } else {
                  setState(() {
                    _defaultPMText = "No Default Payment Method present";
                  });
                }
              }
            } else {
              final err = obj.right;
              setState(() {
                _defaultPMText =
                    err?.message ?? "No Default Payment Method present";
              });
            }
          } else {
            setState(() {
              _defaultPMText =
                  "getCustomerDefaultSavedPaymentMethodData failed";
            });
          }
        } else {
          setState(() {
            _defaultPMText = "SavedSession is empty";
          });
        }
      } else {
        setState(() {
          _defaultPMText = "SessionId is empty";
        });
      }
    } catch (error) {
      setState(() {
        _defaultPMText = error.toString();
      });
    }
  }

  Future<void> _confirmPayment() async {
    setState(() {
      _confirmState = 1;
    });
    try {
      if (_savedSessionId != null) {
        final confirmWithCustomerDefaultPaymentMethodResponse = await _hyper
            .confirmWithCustomerDefaultPaymentMethod(_savedSessionId!);
        if (confirmWithCustomerDefaultPaymentMethodResponse != null) {
          final message =
              confirmWithCustomerDefaultPaymentMethodResponse.message;
          if (message.isLeft) {
            _confirmStatusText =
                "${confirmWithCustomerDefaultPaymentMethodResponse.status.name}\n${message.left!.name}";
          } else {
            _confirmStatusText =
                "${confirmWithCustomerDefaultPaymentMethodResponse.status.name}\n${message.right}";
          }
        } else {
          setState(() {
            _confirmStatusText =
                "confirmWithCustomerDefaultPaymentMethod failed";
          });
        }
      } else {
        setState(() {
          _confirmStatusText = "SavedSession is empty";
        });
      }
    } catch (error) {
      setState(() {
        _confirmStatusText = error.toString();
      });
    } finally {
      setState(() {
        _confirmState = 2;
      });
    }
  }

  Future<void> _presentPaymentSheet() async {
    try {
      if (_sessionId != null) {
        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}";
            }
          });
          if (presentPaymentSheetResponse.status != Status.cancelled) {
            _initPlatformState();
          }
        }
      } else {
        setState(() {
          _statusText = "presentPaymentSheet failed";
        });
      }
    } catch (error) {
      setState(() {
        _statusText = error.toString();
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Column(
          children: [
            _buildHeadlessSdkExample(),
            _buildPaymentSheetExample(),
          ],
        ),
      ),
    );
  }

  Widget _buildHeadlessSdkExample() {
    return Expanded(
        child: 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:
                                  _isInitialized ? _initializeHeadless : null,
                              child: Text(_isInitialized
                                  ? "Initialize Headless"
                                  : "Loading ..."))),
                      Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Flexible(child: Text(_defaultPMText)),
                            if (_showChangeButton)
                              TextButton(
                                  onPressed: _presentPaymentSheet,
                                  child: const Text("Change"))
                          ]),
                      if (_confirmState > 0)
                        Center(
                            child: ElevatedButton(
                                onPressed:
                                    _confirmState == 2 ? _confirmPayment : null,
                                child: Text(_confirmState == 1
                                    ? "Processing ..."
                                    : "Confirm Payment"))),
                      if (_confirmStatusText.isNotEmpty)
                        Center(child: Text(_confirmStatusText))
                    ]))));
  }

  Widget _buildPaymentSheetExample() {
    return Expanded(
        child: 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:
                                  _isInitialized ? _presentPaymentSheet : null,
                              child: Text(_isInitialized
                                  ? "Open Payment Sheet"
                                  : "Loading ..."))),
                      Center(child: Text(_statusText))
                    ]))));
  }
}
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