pay<T> method

  1. @override
Future<void> pay<T>({
  1. required T setupPayment,
})
override

Initiates a PayPal payment checkout flow.

This method expects a generic parameter T, but will only accept an instance of SetupPaypalPayment. If the wrong type is passed, it throws an ArgumentError.

The method pushes a new screen with the PayPal checkout interface. It handles user actions through the provided callbacks:

  • onSuccess β€” triggered on successful payment with a map of PayPal response parameters.
  • onError β€” triggered if the payment fails due to any error.
  • onCancled β€” triggered if the user cancels the payment.

Default fallback snackbars will be shown if the callbacks are not provided.

Example:

PaypalService().pay(
  setupPayment: SetupPaypalPayment(
    context: context,
    clientId: 'xxx',
    secretKey: 'yyy',
    transactions: [...],
    onSuccess: (result) => print("Success!"),
    onError: () => print("Something went wrong."),
    onCancled: () => print("User canceled."),
  ),
);

πŸ’‘ This method should be called inside a widget with a valid BuildContext.

Implementation

@override
Future<void> pay<T>({required T setupPayment}) async {
  try {
    if (setupPayment is! SetupePaypalPayment) {
      throw ArgumentError("setupPayment must be of type SetupPaypalPayment'");
    }
    Navigator.of(setupPayment.context).push(
      MaterialPageRoute(
        builder: (BuildContext context) => PaypalCheckoutView(
          sandboxMode: setupPayment.sandboxMode,
          clientId: setupPayment.clientId,
          secretKey: setupPayment.secretKey,
          transactions: setupPayment.transactions.map(
            (e) {
              return e.toJson();
            },
          ).toList(),
          note: "Contact us for any questions on your order.",
          onSuccess: (Map params) async {
            if (setupPayment.onSuccess == null) {
              Navigator.pop(context);
              _showMessage(
                context,
                Icons.check_circle,
                Colors.greenAccent,
                "Payment completed successfully! πŸŽ‰",
              );
            } else {
              setupPayment.onSuccess!(params);
            }
          },
          onError: (error) {
            if (setupPayment.onError == null) {
              debugPrint(error.toString());
              Navigator.pop(context);
              _showMessage(
                  context, Icons.error_outline, Colors.red, error.toString());
            } else {
              setupPayment.onError!();
            }
          },
          onCancel: () {
            if (setupPayment.onCancled != null) {
              setupPayment.onCancled!();
            } else {
              print("The process was cancled");
            }
          },
        ),
      ),
    );
  } catch (e) {
    debugPrint(e.toString());
  }
}