Movatterモバイル変換


[0]ホーム

URL:


pay 3.3.0copy "pay: ^3.3.0" to clipboard
pay: ^3.3.0 copied to clipboard

1.0k

Metadata

A plug-in to add support for payments on Flutter applications.

More...

pub package

A plugin to add payments to your Flutter application.

Platform Support#

AndroidiOS
Google PayApple Pay

Getting started#

Before you start, create an account with the payment providers you are planning to support and follow the setup instructions:

Apple Pay:

  1. Take a look at theintegration requirements.
  2. Create amerchant identifier for your business.
  3. Create apayment processing certificate to encrypt payment information.

Google Pay:

  1. Take a look at theintegration requirements.
  2. Sign up to thebusiness console and create an account.

Usage#

To start using this plugin, addpay as adependency in your pubspec.yaml file with the following command:

flutter pub add pay

Define the configuration for your payment provider(s). Take a look at the parameters available in the documentation forApple Pay andGoogle Pay, and explore thesample configurations in this package.

Example#

This snippet assumes the existence of a payment configuration for Apple Pay (defaultApplePayConfigString) and another one for Google Pay (defaultGooglePayConfigString):

import 'package:pay/pay.dart';const _paymentItems = [  PaymentItem(    label: 'Total',    amount: '99.99',    status: PaymentItemStatus.final_price,  )];ApplePayButton(  paymentConfiguration: PaymentConfiguration.fromJsonString(      defaultApplePayConfigString),  paymentItems: _paymentItems,  style: ApplePayButtonStyle.black,  type: ApplePayButtonType.buy,  margin: const EdgeInsets.only(top: 15.0),  onPaymentResult: onApplePayResult,  loadingIndicator: const Center(    child: CircularProgressIndicator(),  ),),GooglePayButton(  paymentConfiguration: PaymentConfiguration.fromJsonString(      defaultGooglePayConfigString),  paymentItems: _paymentItems,  type: GooglePayButtonType.buy,  margin: const EdgeInsets.only(top: 15.0),  onPaymentResult: onGooglePayResult,  loadingIndicator: const Center(    child: CircularProgressIndicator(),  ),),void onApplePayResult(paymentResult) {  // Send the resulting Apple Pay token to your server / PSP}void onGooglePayResult(paymentResult) {  // Send the resulting Google Pay token to your server / PSP}

Alternative methods to load your payment configurations#

JSON strings

The example above uses thePaymentConfiguration.fromJsonString method to load your payment configuration from a string in JSON format (example). This configuration can be retrieved from a remote location at runtime (recommended) or provided at build time.

Asset files

You can also place payment configurations under yourassets folder and load them at runtime. Suppose that you add a JSON file with the namegoogle_pay_config.json to yourassets folder to configure your Google Pay integration. You can load it and use it to create aPaymentConfiguration object for the button (e.g.: using aFutureBuilder):

final Future<PaymentConfiguration> _googlePayConfigFuture =     PaymentConfiguration.fromAsset('google_pay_config.json');FutureBuilder<PaymentConfiguration>(    future: _googlePayConfigFuture,    builder: (context, snapshot) => snapshot.hasData        ? GooglePayButton(          paymentConfiguration: snapshot.data!,          paymentItems: _paymentItems,          type: GooglePayButtonType.buy,          margin: const EdgeInsets.only(top: 15.0),          onPaymentResult: onGooglePayResult,          loadingIndicator: const Center(            child: CircularProgressIndicator(),          ),        )        : const SizedBox.shrink()),

Advanced usage#

If you prefer to have more control over each individual request and the button separately, you can instantiate a payment client and add the buttons to your layout independently:

import 'package:pay/pay.dart';const _paymentItems = [  PaymentItem(    label: 'Total',    amount: '99.99',    status: PaymentItemStatus.final_price,  )];final Pay _payClient = Pay({  PayProvider.google_pay: payment_configurations.defaultGooglePayConfig,  PayProvider.apple_pay: payment_configurations.defaultApplePayConfig,});

As you can see, you can add multiple configurations to your payment client, one for each payment provider supported.

Now, you can use theuserCanPay method to determine whether the user can start a payment process with a given provider. This call returns aFuture<bool> result that you can use to decide what to do next. For example, you can feed theFuture to aFutureBuilder that shows a different UI based on the result of the call:

@overrideWidget build(BuildContext context) {  return FutureBuilder<bool>(    future: _payClient.userCanPay(PayProvider.apple_pay),    builder: (context, snapshot) {      if (snapshot.connectionState == ConnectionState.done) {        if (snapshot.data == true) {          return RawApplePayButton(              type: ApplePayButtonType.buy,              onPressed: _onApplePayPressed);        } else {          // userCanPay returned false          // Consider showing an alternative payment method        }      } else {        // The operation hasn't finished loading        // Consider showing a loading indicator       }    },  );}

Finally, handle theonPressed event and trigger the payment selector as follows:

void _onApplePayPressed() async {  final result = await _payClient.showPaymentSelector(    PayProvider.apple_pay,    _paymentItems,  );  // Send the resulting Google Pay token to your server / PSP}

Handling a payment result response (Android only)#

On Android, payment results are received using an event channel, in order to eliminate the effect of lost references during activity recreation events. Because of that, calls toPay.showPaymentSelector only initiate the payment process and don't return any result.

To subscribe to the result stream, create anEventChannel using the payment results channel name (plugins.flutter.io/pay/payment_result) and start listening to events:

static const eventChannel =    EventChannel('plugins.flutter.io/pay/payment_result');final _paymentResultSubscription = eventChannel    .receiveBroadcastStream()    .map((result) => jsonDecode(result as String) as Map<String, dynamic>)    .listen((result) {      // TODO: Send the resulting Google Pay token to your server / PSP    }, onError: (error) {      // TODO: Handle errors    });

Make sure to cancel the subscription and clear the reference when it is not needed anymore:

_paymentResultSubscription.cancel();_paymentResultSubscription = null;

See theadvanced example to see a working integration.

Additional resources#

Take a look at the following resources to manage your payment accounts and learn more about the APIs for the supported providers:

Google PayApple Pay
Platforms Android iOS
 Documentation OverviewOverview
 Console Google Pay Business ConsoleDeveloper portal
ReferenceAPI reference Apple Pay API
Style guidelines Brand guidelinesButtons and Marks

Note: This is not an officially supported Google product.
1.09k
likes
140
points
77.1k
downloads

Publisher

verified publishergoogle.dev

Weekly Downloads

Metadata

A plug-in to add support for payments on Flutter applications.

Repository (GitHub)
View/report issues
Contributing

Documentation

API reference

License

Apache-2.0 (license)

Dependencies

flutter,flutter_localizations,meta,pay_android,pay_ios,pay_platform_interface

More

Packages that depend on pay

Packages that implement pay

Metadata

1.09k
likes
140
points
77.1k
downloads

Publisher

verified publishergoogle.dev

Weekly Downloads

Metadata

A plug-in to add support for payments on Flutter applications.

Repository (GitHub)
View/report issues
Contributing

Documentation

API reference

License

Apache-2.0 (license)

Dependencies

flutter,flutter_localizations,meta,pay_android,pay_ios,pay_platform_interface

More

Packages that depend on pay

Packages that implement pay

Back


[8]ページ先頭

©2009-2026 Movatter.jp