olo_pay_sdk 1.1.0-Dev copy "olo_pay_sdk: ^1.1.0-Dev" to clipboard
olo_pay_sdk: ^1.1.0-Dev copied to clipboard

retracted

Olo Pay Flutter SDK: Add simple PCI-compliant payments to your apps

example/lib/main.dart

// Copyright © 2022 Olo Inc. All rights reserved.
// This software is made available under the Olo Pay SDK License (See LICENSE.md file)
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:olo_pay_sdk/olo_pay_sdk.dart';
import 'package:pay/pay.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Olo Pay SDK Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: const Color.fromRGBO(1, 160, 219, 1)),
        useMaterial3: true,
      ),
      darkTheme: ThemeData.dark(),
      themeMode: ThemeMode.system,
      home: const MyHomePage(),
    );
  }
}

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

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  // Step 1: Create the plugin instance
  final _oloPaySdkPlugin = OloPaySdk();
  CardDetailsSingleLineTextFieldController? _cardInputController;

  String _error = '';
  String _status = '';
  bool _sdkInitialized = false;
  bool _digitalWalletsReady = false;
  bool _enabled = true;
  bool _showAll = false;

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

  void onSingleLineControllerCreated(CardDetailsSingleLineTextFieldController controller) {
    _cardInputController = controller;
  }

  void updateError(String error) {
    setState(() {
      _error = error;
    });
  }

  void updatePaymentMethod(PaymentMethod paymentMethod) {
    updateStatus("Payment Method\n${paymentMethod.toString()}");
  }

  void updateStatus(String status) {
    setState(() {
      _status = status;
    });
  }

  void onInputChanged(bool isValid, Map<CardField, CardFieldState> fieldStates) {
    // Add code here to handle/test this callback
    // log('onInputChanged: $isValid');
  }

  void onValidStateChanged(bool isValid, Map<CardField, CardFieldState> fieldStates) {
    // Add code here to handle/test this callback
    // log('onValidStateChanged: $isValid');
  }

  void onFocusChanged(CardField? focusedField, bool isValid, Map<CardField, CardFieldState> fieldStates) {
    // Add code here to handle/test this callback
    // log('onFocusChanged: $focusedField');
  }

  void onDigitalWalletReady(bool isReady) {
    setState(() {
      _digitalWalletsReady = isReady;
    });
  }

  Future<void> initPlatformState() async {
    var sdkInitialized = false;
    try {
      // Step 2: Add a digital wallet listener
      _oloPaySdkPlugin.onDigitalWalletReady = onDigitalWalletReady;

      const OloPaySetupParameters sdkParams = OloPaySetupParameters(
        productionEnvironment: false,
      );

      const GooglePaySetupParameters googlePayParams = GooglePaySetupParameters(
        countryCode: "US",
        merchantName: "Foosburgers",
        productionEnvironment: false,
      );

      const ApplePaySetupParameters applePayParams = ApplePaySetupParameters(
        merchantId: "merchant.com.olopaysdktestharness",
        companyLabel: "SDK Test",
      );

      // Step 3: Initialize the Olo Pay SDK
      await _oloPaySdkPlugin.initializeOloPay(
        oloPayParams: sdkParams,
        googlePayParams: googlePayParams,
        applePayParams: applePayParams,
      );

      // If initializeOloPay() succeeds there is no need for this method call in a production app... just directly set state to true
      //We do this just to test that the isOloPayInitialized() method is working properly.
      sdkInitialized = await _oloPaySdkPlugin.isOloPayInitialized();
    } on PlatformException catch (e) {
      updateStatus(e.message!);
    }

    setState(() {
      _sdkInitialized = sdkInitialized;
    });
  }

  Future<void> createPaymentMethod() async {
    try {
      var paymentMethod = await _cardInputController?.createPaymentMethod();
      if (paymentMethod != null) {
        updatePaymentMethod(paymentMethod);
      }
    } on PlatformException {
      // No need to update error here if you are using onErrorMessageChanged callback
      // updateError(e.message!);
    }
  }

  Future<void> createDigitalWalletPaymentMethod() async {
    const DigitalWalletPaymentParameters paymentParams = DigitalWalletPaymentParameters(
      amount: 1.21,
    );

    try {
      PaymentMethod? paymentMethod = await _oloPaySdkPlugin.createDigitalWalletPaymentMethod(paymentParams);

      if (paymentMethod == null) {
        // User canceled digital wallet flow
        updateStatus("User Canceled");
      } else {
        updatePaymentMethod(paymentMethod);
      }
    } on PlatformException catch (e) {
      updateStatus(e.message!);
    }
  }

  Future<void> getState() async {
    try {
      var state = await _cardInputController?.getState();
      if (state != null) {
        var status = state.entries
            .map<String>((e) => "${e.key}\n${e.value.toString()}\n")
            .reduce((value, element) => value + element);
        updateStatus(status);
      }
    } on PlatformException catch (e) {
      updateStatus(e.message!);
    }
  }

  Future<void> isValid() async {
    try {
      var valid = await _cardInputController?.isValid();
      if (valid != null) {
        updateStatus("Is Valid: $valid");
      }
    } on PlatformException catch (e) {
      updateStatus(e.message!);
    }
  }

  Future<void> getCardType() async {
    try {
      var cardType = await _cardInputController?.getCardType();
      if (cardType != null) {
        updateStatus("Card Type: ${cardType.stringValue}");
      }
    } on PlatformException catch (e) {
      updateStatus(e.message!);
    }
  }

  Future<void> isEnabled() async {
    if (_cardInputController == null) {
      return;
    }

    var isEnabled = await _cardInputController!.isEnabled();
    updateStatus("Enabled: $isEnabled");
  }

  Future<void> toggleEnabled() async {
    if (_cardInputController == null) {
      return;
    }

    try {
      await _cardInputController!.setEnabled(!_enabled);
      setState(() {
        _enabled = !_enabled;
        updateStatus("Enabled: $_enabled");
      });
    } on PlatformException catch (e) {
      updateStatus(e.message!);
    }
  }

  Future<void> clear() async {
    try {
      await _cardInputController?.clearFields();
      updateStatus("");
    } on PlatformException catch (e) {
      updateStatus(e.message!);
    }
  }

  Future<void> hasErrorMessage() async {
    if (_cardInputController == null) {
      return;
    }

    try {
      var editedFieldsError = await _cardInputController?.hasErrorMessage();
      var uneditedFieldsError = await _cardInputController?.hasErrorMessage(ignoreUneditedFields: false);

      updateStatus("Has Error Message:\nEdited Fields Only: $editedFieldsError\nAll Fields: $uneditedFieldsError");
    } on PlatformException catch (e) {
      updateStatus(e.message!);
    }
  }

  Future<void> getErrorMessage() async {
    if (_cardInputController == null) {
      return;
    }

    try {
      var editedFieldsError = await _cardInputController?.getErrorMessage();
      var uneditedFieldsError = await _cardInputController?.getErrorMessage(ignoreUneditedFields: false);

      updateStatus("Error Message:\n\nEdited Fields Only:\n$editedFieldsError\nAll Fields:\n$uneditedFieldsError");
    } on PlatformException catch (e) {
      updateStatus(e.message!);
    }
  }

  Future<void> requestFocus() async {
    if (_cardInputController == null) {
      return;
    }

    try {
      await _cardInputController?.requestFocus();
    } on PlatformException catch (e) {
      updateStatus(e.message!);
    }
  }

  Future<void> clearFocus() async {
    if (_cardInputController == null) {
      return;
    }

    try {
      await _cardInputController?.clearFocus();
    } on PlatformException catch (e) {
      updateStatus(e.message!);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: const Text("Olo Pay SDK Demo"),
      ),
      body: SingleChildScrollView(
        child: Center(
          child: Padding(
            padding: const EdgeInsets.all(10.0),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Row(
                  children: [
                    const Text(
                      "SDK Initialized:   ",
                      style: TextStyle(fontWeight: FontWeight.bold),
                    ),
                    Text(_sdkInitialized.toString())
                  ],
                ),
                Row(
                  children: [
                    const Text(
                      "Digital Wallets Ready:   ",
                      style: TextStyle(fontWeight: FontWeight.bold),
                    ),
                    Text(_digitalWalletsReady.toString())
                  ],
                ),
                const SizedBox(height: 20.0),
                Row(
                  children: [
                    if (defaultTargetPlatform == TargetPlatform.android && _digitalWalletsReady)
                      Expanded(
                        child: RawGooglePayButton(
                          type: GooglePayButtonType.buy,
                          onPressed: createDigitalWalletPaymentMethod,
                        ),
                      ),
                    if (defaultTargetPlatform == TargetPlatform.iOS && _digitalWalletsReady)
                      Expanded(
                        child: RawApplePayButton(
                          type: ApplePayButtonType.buy,
                          onPressed: createDigitalWalletPaymentMethod,
                        ),
                      ),
                  ],
                ),
                const SizedBox(height: 15.0),
                if (_sdkInitialized) //The SDK must be initialized prior to displaying the text field
                  CardDetailsSingleLineTextField(
                    // Step 5: Provide a callback to get a controller instance
                    onControllerCreated: onSingleLineControllerCreated,
                    onErrorMessageChanged: updateError,
                    onInputChanged: onInputChanged,
                    onValidStateChanged: onValidStateChanged,
                    onFocusChanged: onFocusChanged,
                  ),
                const SizedBox(height: 16.0),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    ElevatedButton(
                      // Step 6: Create the payment method with a card input widget
                      onPressed: createPaymentMethod,
                      child: const Text("Submit"),
                    ),
                    ElevatedButton(
                      onPressed: clear,
                      child: const Text("Clear"),
                    ),
                    TextButton.icon(
                      icon: Text(_showAll ? "Show Less" : "Show More"),
                      label: Icon(
                        _showAll ? Icons.keyboard_arrow_up : Icons.keyboard_arrow_down,
                        size: 24.0,
                      ),
                      onPressed: () {
                        setState(() {
                          _showAll = !_showAll;
                        });
                      },
                    ),
                  ],
                ),
                const SizedBox(height: 8.0),
                if (_showAll)
                  GridView.count(
                    crossAxisCount: 3,
                    crossAxisSpacing: 8.0,
                    mainAxisSpacing: 8.0,
                    childAspectRatio: 3,
                    shrinkWrap: true,
                    padding: const EdgeInsets.all(8.0),
                    children: [
                      ElevatedButton(
                        onPressed: getState,
                        child: const Text("State"),
                      ),
                      ElevatedButton(
                        onPressed: isValid,
                        child: const Text("Is Valid?"),
                      ),
                      ElevatedButton(
                        onPressed: getCardType,
                        child: const Text("Card Type"),
                      ),
                      ElevatedButton(
                        onPressed: isEnabled,
                        child: const Text("Enabled?"),
                      ),
                      ElevatedButton(
                        onPressed: hasErrorMessage,
                        child: const Text("Has Error?"),
                      ),
                      ElevatedButton(
                        onPressed: getErrorMessage,
                        child: const Text("Errors"),
                      ),
                      ElevatedButton(
                        onPressed: requestFocus,
                        child: const Text("Focus"),
                      ),
                      ElevatedButton(
                        onPressed: clearFocus,
                        child: const Text("Clear Focus"),
                      ),
                      TextButton.icon(
                        icon: const Text("Enable"),
                        label: Icon(
                          _enabled ? Icons.check_box : Icons.check_box_outline_blank,
                          size: 24.0,
                        ),
                        onPressed: toggleEnabled,
                      ),
                    ],
                  ),
                const SizedBox(height: 8.0),
                Text(
                  _status,
                  textAlign: TextAlign.center,
                  style: const TextStyle(
                    color: Colors.blue,
                    fontSize: 18.0,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}