-
-
Notifications
You must be signed in to change notification settings - Fork 538
/
stripe.dart
705 lines (627 loc) · 23.4 KB
/
stripe.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:meta/meta.dart';
import 'package:stripe_platform_interface/stripe_platform_interface.dart';
/// [Stripe] is the facade of the library and exposes the operations that can be
/// executed on the Stripe platform.
///
class Stripe {
// Disables the platform override in order to use a manually registered
// ignore: comment_references
// [SharePlatform] for testing purposes.
// See https://github.com/flutter/flutter/issues/52267 for more details.
//
Stripe._();
/// Sets the publishable key that is used to identify the account on the
/// Stripe platform.
static set publishableKey(String value) {
if (value == instance._publishableKey) {
return;
}
instance._publishableKey = value;
instance.markNeedsSettings();
}
/// Retrieves the publishable API key.
static String get publishableKey {
if (instance._publishableKey == null) {
throw const StripeConfigException('Publishable key is not set');
}
return instance._publishableKey!;
}
/// Whether or not to set the return url for Androdi as well
static set setReturnUrlSchemeOnAndroid(bool? value) {
if (value == instance._setReturnUrlSchemeOnAndroid) {
return;
}
instance._setReturnUrlSchemeOnAndroid = value;
instance.markNeedsSettings();
}
/// Retrieves the id associate with the Stripe account.
static String? get stripeAccountId => instance._stripeAccountId;
/// Sets the account id that is generated when creating a Stripe account.
static set stripeAccountId(String? value) {
if (value == instance._stripeAccountId) {
return;
}
instance._stripeAccountId = value;
instance.markNeedsSettings();
}
/// Retrieves the configuration parameters for 3D secure.
static ThreeDSecureConfigurationParams? get threeDSecureParams =>
instance._threeDSecureParams;
/// Sets the configuration parameters for 3D secure.
static set threeDSecureParams(ThreeDSecureConfigurationParams? value) {
if (value == instance._threeDSecureParams) {
return;
}
instance._threeDSecureParams = value;
instance.markNeedsSettings();
}
/// Sets the custom url scheme
static set urlScheme(String? value) {
if (value == instance._urlScheme) {
return;
}
instance._urlScheme = value;
instance.markNeedsSettings();
}
/// Retrieves the custom url scheme
static String? get urlScheme {
return instance._urlScheme;
}
/// Retrieves the setReturnUrlSchemeOnAndroid parameter
static bool? get setReturnUrlSchemeOnAndroid {
return instance._setReturnUrlSchemeOnAndroid;
}
/// Retrieves the merchant identifier.
static String? get merchantIdentifier => instance._merchantIdentifier;
/// Sets the merchant identifier.
static set merchantIdentifier(String? value) {
if (value == instance._merchantIdentifier) {
return;
}
instance._merchantIdentifier = value;
instance.markNeedsSettings();
}
/// Reconfigures the Stripe platform by applying the current values for
/// [publishableKey], [merchantIdentifier], [stripeAccountId],
/// [threeDSecureParams], [urlScheme]
Future<void> applySettings() => _initialise(
publishableKey: publishableKey,
merchantIdentifier: merchantIdentifier,
stripeAccountId: stripeAccountId,
threeDSecureParams: threeDSecureParams,
urlScheme: urlScheme,
setReturnUrlSchemeOnAndroid: setReturnUrlSchemeOnAndroid,
);
/// Exposes a [ValueListenable] whether or not GooglePay (on Android) or Apple Pay (on iOS)
/// is supported for this device.
ValueListenable<bool> get isPlatformPaySupportedListenable {
if (_isPlatformPaySupported == null) {
_isPlatformPaySupported = ValueNotifier(false);
isPlatformPaySupported();
}
return _isPlatformPaySupported!;
}
/// Check if the relevant native wallet (Apple Pay on iOS and Google Pay on Android)
/// is supported.
///
/// The [googlePay] param can be provided to check if platform pay is supported on
/// Google Pay test env or if a payment method is required.
Future<bool> isPlatformPaySupported({
IsGooglePaySupportedParams? googlePay,
}) async {
await _awaitForSettings();
final isSupported =
await _platform.isPlatformPaySupported(params: googlePay);
_isPlatformPaySupported ??= ValueNotifier(false);
_isPlatformPaySupported?.value = isSupported;
return isSupported;
}
/// Laucnhes the relevant native wallsheet (Apple Pay on iOS and Google Pay on Android)
/// in order to create a payment intent
///
/// Argument [params] is describing the the Apple Pay or Google pay configuration.
/// Creating payment method does not return a token by default. Use `usesDeprecatedTokenFlow` instead.
///
/// throws [StripeError] in case creating payment method is failing.
Future<PaymentMethod> createPlatformPayPaymentMethod({
required PlatformPayPaymentMethodParams params,
bool usesDeprecatedTokenFlow = false,
}) async {
try {
await _awaitForSettings();
return await _platform.platformPayCreatePaymentMethod(
params: params,
usesDeprecatedTokenFlow: usesDeprecatedTokenFlow,
);
} on StripeError {
rethrow;
}
}
/// Launches the relevant native wallet sheet (Apple Pay on iOS and Google Pay on Android)
/// in order to confirm a Stripe setup intent.
///
/// The [clientSecret] is the secret of the SetupIntent. [ConfirmParams] are
/// parameters describing the GooglePay and Apple Pay configuration.
///
/// Throws an [StripeError] in case confirmPlatformPaySetupIntent fails.
Future<SetupIntent> confirmPlatformPaySetupIntent({
required String clientSecret,
required PlatformPayConfirmParams confirmParams,
}) async {
try {
await _awaitForSettings();
return _platform.platformPayConfirmSetupIntent(
clientSecret: clientSecret,
params: confirmParams,
);
} on StripeError {
rethrow;
}
}
/// Launches the relevant native wallet sheet (Apple Pay on iOS an Google Pay on Android)
/// in order to confirm a Stripe payment intent.
///
/// The [clientSecret] is the secret of the PaymentIntent. [ConfirmParams] are
/// parameters describing the GooglePay and Apple Pay configuration.
///
/// Throws an [StripeError] in case confirmPlatformPaySetupIntent fails.
Future<PaymentIntent> confirmPlatformPayPaymentIntent({
required String clientSecret,
required PlatformPayConfirmParams confirmParams,
}) async {
try {
await _awaitForSettings();
return _platform.platformPayConfirmPaymentIntent(
clientSecret: clientSecret,
params: confirmParams,
);
} on StripeError {
rethrow;
}
}
@internal
bool debugUpdatePlatformSheetCalled = false;
/// Updates the native payment sheet with new data **iOS-only.
///
/// For example this method is required to call when the user updates shippingmethod, shippingAddress and couponcode.
Future<void> updatePlatformSheet({
required PlatformPaySheetUpdateParams params,
}) async {
await _awaitForSettings();
assert(() {
debugUpdatePlatformSheetCalled = true;
return true;
}());
debugUpdatePlatformSheetCalled = true;
return _platform.updatePlatformSheet(params: params);
}
@internal
bool debugConfigurePlatformOrderTrackingCalled = false;
/// Updates the native payment sheet with new order tracking information
/// **iOS-only.
///
/// This method is required to call when the onOrderTracking is
/// called
Future<void> configurePlatformOrderTracking({
required PlatformPayOrderDetails orderDetails,
}) async {
await _awaitForSettings();
assert(() {
debugConfigurePlatformOrderTrackingCalled = true;
return true;
}());
return _platform.configurePlatformOrderTracking(orderDetails: orderDetails);
}
/// Creates a single-use token that represents an Apple Pay credit card’s details.
///
/// The [payment] param should be the data response from the `pay` plugin. It can
/// be used both with the callback `onPaymentResult` from `pay.ApplePayButton` or
/// directly with `Pay.showPaymentSelector`
///
/// Throws an [StripeError] in case createApplePayToken fails.
Future<TokenData> createApplePayToken(Map<String, dynamic> payment) async {
await _awaitForSettings();
try {
final tokenData = await _platform.createApplePayToken(payment);
return tokenData;
} on StripeError catch (error) {
throw StripeError(message: error.message, code: error.message);
}
}
///Converts payment information defined in [params] into a [PaymentMethod]
///object that can be passed to your server.
///
/// [params] specificies the parameters associated with the specific
/// paymentmethod. See [PaymentMethodParams] for more details.
///
/// Throws an [StripeException] in case creating the payment method fails.
Future<PaymentMethod> createPaymentMethod({
required PaymentMethodParams params,
PaymentMethodOptions? options,
}) async {
await _awaitForSettings();
try {
final paymentMethod =
await _platform.createPaymentMethod(params, options);
return paymentMethod;
} on StripeError catch (error) {
throw StripeError(message: error.message, code: error.message);
}
}
/// Creates a single-use token that represents a credit card’s details.
///
/// Tokens are considered legacy, use [PaymentMethod] and [PaymentIntent]
/// instead.
/// Throws an [StripeError] in case createToken fails.
Future<TokenData> createToken(CreateTokenParams params) async {
await _awaitForSettings();
try {
final tokenData = await _platform.createToken(params);
return tokenData;
} on StripeError catch (error) {
throw StripeError(message: error.message, code: error.message);
}
}
/// Retrieves a [PaymentIntent] using the provided [clientSecret].
///
/// Throws a [StripeException] in case retrieving the intent fails.
Future<PaymentIntent> retrievePaymentIntent(String clientSecret) async {
await _awaitForSettings();
try {
final paymentMethod = await _platform.retrievePaymentIntent(clientSecret);
return paymentMethod;
} on StripeError catch (error) {
throw StripeError(message: error.message, code: error.message);
}
}
/// Retrieves a [SetupIntent] using the provided [clientSecret].
///
/// Throws a [StripeException] in case retrieving the intent fails.
Future<SetupIntent> retrieveSetupIntent(String clientSecret) async {
await _awaitForSettings();
try {
final setupIntent = await _platform.retrieveSetupIntent(clientSecret);
return setupIntent;
} on StripeError catch (error) {
throw StripeError(message: error.message, code: error.message);
}
}
/// Opens the UI to set up credit cards for Apple Pay.
Future<void> openApplePaySetup() async {
await _platform.openApplePaySetup();
}
/// Handle URL callback from iDeal payment returnUrl to close iOS in-app webview
Future<bool> handleURLCallback(String url) async {
try {
return await _platform.handleURLCallback(url);
} catch (e) {
rethrow;
}
}
/// Confirms a payment method, using the provided [paymentIntentClientSecret]
/// and [data].
///
/// See [PaymentMethodParams] for more details. The method returns a
/// [PaymentIntent]. Throws a [StripeException] when confirming the
/// paymentmethod fails.
Future<PaymentIntent> confirmPayment({
required String paymentIntentClientSecret,
PaymentMethodParams? data,
PaymentMethodOptions? options,
}) async {
await _awaitForSettings();
try {
final paymentMethod = await _platform.confirmPayment(
paymentIntentClientSecret,
data,
options,
);
return paymentMethod;
} on StripeError {
rethrow;
}
}
/// Use this method in case the [PaymentIntent] status is
/// [PaymentIntentsStatus.RequiresAction]. Executing this action can take
/// several seconds and it is important to not resubmit the form.
///
/// Throws a [StripeException] when confirming the handle card action fails.
Future<PaymentIntent> handleNextAction(String paymentIntentClientSecret,
{String? returnURL}) async {
await _awaitForSettings();
try {
final paymentIntent = await _platform
.handleNextAction(paymentIntentClientSecret, returnURL: returnURL);
return paymentIntent;
} on StripeError {
//throw StripeError<CardActionError>(error.code, error.message);
rethrow;
}
}
/// Use this method in case the [SetupIntent] status is
/// [PaymentIntentsStatus.RequiresAction]. Executing this action can take
/// several seconds and it is important to not resubmit the form.
///
/// Throws a [StripeException] when confirming the handle card action fails.
Future<SetupIntent> handleNextActionForSetupIntent(
String setupIntentClientSecret,
{String? returnURL}) async {
await _awaitForSettings();
try {
final paymentIntent = await _platform.handleNextActionForSetupIntent(
setupIntentClientSecret,
returnURL: returnURL);
return paymentIntent;
} on StripeError {
rethrow;
}
}
/// Confirm the [SetupIntent] using the [paymentIntentClientSecret]
/// and [params].
///
/// Use this method when the customer submits the form for SetupIntent.
///
/// Throws a [StripeException] when confirming the setupintent fails.
Future<SetupIntent> confirmSetupIntent({
required String paymentIntentClientSecret,
required PaymentMethodParams params,
PaymentMethodOptions? options,
}) async {
await _awaitForSettings();
try {
final setupIntent = await _platform.confirmSetupIntent(
paymentIntentClientSecret, params, options);
return setupIntent;
} on StripeException {
rethrow;
}
}
/// Creates a token that represents an updated CVC.
///
/// Returns a single-use token.
///
/// Throws [StripeError] in case creating the token fails.
Future<String?> createTokenForCVCUpdate(
String cvc,
) async {
await _awaitForSettings();
try {
final tokenId = await _platform.createTokenForCVCUpdate(
cvc,
);
return tokenId;
} on StripeError {
//throw StripeError<CardActionError>(error.code, error.message);
rethrow;
}
}
/// Initializes the payment by providing a configuration
///
/// See [SetupPaymentSheetParameters] for more info. In order to show the
/// payment sheet it is required to call [presentPaymentSheet].
Future<PaymentSheetPaymentOption?> initPaymentSheet({
required SetupPaymentSheetParameters paymentSheetParameters,
}) async {
assert(
!(paymentSheetParameters.applePay != null &&
instance._merchantIdentifier == null),
'merchantIdentifier must be specified if you are using Apple Pay. Please refer to this article to get a merchant identifier: https://support.stripe.com/questions/enable-apple-pay-on-your-stripe-account');
await _awaitForSettings();
return _platform.initPaymentSheet(paymentSheetParameters);
}
/// Displays the paymentsheet
///
/// See [PresentPaymentSheetPameters] for more details
///
/// throws [StripeException] in case of a failure
Future<PaymentSheetPaymentOption?> presentPaymentSheet({
PaymentSheetPresentOptions? options,
}) async {
await _awaitForSettings();
return await _platform.presentPaymentSheet(options: options);
}
/// Method used to confirm to the user that the intent is created successfull
/// or not successfull when using a defferred payment method.
Future<void> intentCreationCallback(
IntentCreationCallbackParams params) async {
await _awaitForSettings();
return await _platform.intentCreationCallback(params);
}
/// Call this method when the user logs out from your app.
///
/// This will ensure that any persisted authentication state in the
/// paymentsheet, such as authentication cookies are cleared during logout.
Future<void> resetPaymentSheetCustomer() async {
await _awaitForSettings();
return await _platform.resetPaymentSheetCustomer();
}
/// Confirms the paymentsheet payment
///
/// throws [StripeException] in case of a failure
Future<void> confirmPaymentSheetPayment() async {
return await _platform.confirmPaymentSheetPayment();
}
/// Updates the internal card details. This method will not validate the card
/// information so you should validate the information yourself.
/// WARNING!!! Only do this if you're certain that you fulfill the necessary
/// PCI compliance requirements. Make sure that you're not mistakenly logging
/// or storing full card details! See the docs for
/// details: https://stripe.com/docs/security/guide#validating-pci-compliance
Future<void> dangerouslyUpdateCardDetails(CardDetails card) async {
return await _platform.dangerouslyUpdateCardDetails(card);
}
/// Inititialise google pay
@Deprecated(
'Use [confirmPlatformPaySetupIntent] or [confirmPlatformPayPaymentIntent] or [createPlatformPayPaymentMethod] instead.')
Future<void> initGooglePay(GooglePayInitParams params) async {
return await _platform.initGooglePay(params);
}
/// Setup google pay.
///
/// Throws a [StripeException] in case it is failing
@Deprecated(
'Use [confirmPlatformPaySetupIntent] or [confirmPlatformPayPaymentIntent].')
Future<void> presentGooglePay(PresentGooglePayParams params) async {
return await _platform.presentGooglePay(params);
}
/// Create a payment method for google pay.
///
/// Throws a [StripeException] in case it is failing
@Deprecated('Use [createPlatformPayPaymentMethod instead.')
Future<PaymentMethod> createGooglePayPaymentMethod(
CreateGooglePayPaymentParams params) async {
return await _platform.createGooglePayPaymentMethod(params);
}
/// Determines if Google Pay is supported on the device
///
/// On iOS this defaults to false
///
@Deprecated('Use [isPlatformPaySupported] instead')
Future<bool> isGooglePaySupported(IsGooglePaySupportedParams params) async {
return await _platform.googlePayIsSupported(params);
}
/// Collect the bankaccount details for the payment intent.
///
/// Only US bank accounts are supported. This method is only implemented for
/// iOS at the moment.
Future<PaymentIntent> collectBankAccount({
/// Whether the clientsecret is associated with setup or paymentintent
required bool isPaymentIntent,
/// The clientSecret of the payment and setup intent
required String clientSecret,
/// Parameters associated with the account holder.
///
/// The name and email is required.
required CollectBankAccountParams params,
}) async {
return await _platform.collectBankAccount(
isPaymentIntent: isPaymentIntent,
clientSecret: clientSecret,
params: params,
);
}
/// Verify the bank account with microtransactions
///
/// Only US bank accounts are supported.This method is only implemented for
/// iOS at the moment.
Future<PaymentIntent> verifyPaymentIntentWithMicrodeposits({
/// Whether the clientsecret is associated with setup or paymentintent
required bool isPaymentIntent,
/// The clientSecret of the payment and setup intent
required String clientSecret,
/// Parameters to verify the microdeposits.
required VerifyMicroDepositsParams params,
}) async {
return await _platform.verifyPaymentIntentWithMicrodeposits(
isPaymentIntent: isPaymentIntent,
clientSecret: clientSecret,
params: params,
);
}
/// check if a particular card can be provisioned with the current app
/// on this particular device.
Future<AddToWalletResult> canAddToWallet(String last4) async {
return await _platform.canAddToWallet(last4);
}
/// Call the financial connections authentication flow in order to collect a US bank account to enhance payouts.
///
/// Needs `clientSecret` of the stripe financial connections sessions.
/// For more info see [Add a Financial Connections Account to a US Custom Connect](https://stripe.com/docs/financial-connections/connect-payouts).
///
/// Throws [StripeError] in case creating the token fails.
Future<FinancialConnectionTokenResult> collectBankAccountToken(
{required String clientSecret}) async {
try {
return _platform.collectBankAccountToken(clientSecret: clientSecret);
} on StripeError {
rethrow;
}
}
/// Call the financial connections authentication flow in order to collect the user account data.
///
/// Needs `clientSecret` of the stripe financial connections sessions.
/// For more info see: [Collect an account to build data-powered products](https://stripe.com/docs/financial-connections/other-data-powered-products)
///
/// Throws [StripeError] in case creating the token fails.
Future<FinancialConnectionSessionResult> collectFinancialConnectionsAccounts(
{required String clientSecret}) async {
try {
return _platform.collectFinancialConnectionsAccounts(
clientSecret: clientSecret);
} on StripeError {
rethrow;
}
}
/// Initializes the customer sheet with the provided [parameters].
Future<CustomerSheetResult?> initCustomerSheet(
{required CustomerSheetInitParams customerSheetInitParams}) async {
await _awaitForSettings();
return _platform.initCustomerSheet(customerSheetInitParams);
}
/// Display the customersheet sheet. With the provided [options].
Future<CustomerSheetResult?> presentCustomerSheet({
CustomerSheetPresentParams? options,
}) async {
await _awaitForSettings();
return _platform.presentCustomerSheet(options: options);
}
/// Retrieve the customer sheet payment option selection.
Future<CustomerSheetResult?>
retrieveCustomerSheetPaymentOptionSelection() async {
await _awaitForSettings();
return _platform.retrieveCustomerSheetPaymentOptionSelection();
}
FutureOr<void> _awaitForSettings() {
if (_needsSettings) {
_settingsFuture = applySettings();
}
if (_settingsFuture != null) {
return _settingsFuture;
}
return null;
}
Future<void>? _settingsFuture;
static final Stripe instance = Stripe._();
String? _publishableKey;
String? _stripeAccountId;
ThreeDSecureConfigurationParams? _threeDSecureParams;
String? _merchantIdentifier;
String? _urlScheme;
bool? _setReturnUrlSchemeOnAndroid;
static StripePlatform? __platform;
// This is to manually endorse the Linux plugin until automatic registration
// of dart plugins is implemented.
// See https://github.com/flutter/flutter/issues/52267 for more details.
static StripePlatform get _platform {
__platform ??= StripePlatform.instance;
return __platform!;
}
bool _needsSettings = true;
void markNeedsSettings() {
_needsSettings = true;
if (!_platform.updateSettingsLazily) {
_awaitForSettings();
}
}
Future<void> _initialise(
{required String publishableKey,
String? stripeAccountId,
ThreeDSecureConfigurationParams? threeDSecureParams,
String? merchantIdentifier,
String? urlScheme,
bool? setReturnUrlSchemeOnAndroid}) async {
_needsSettings = false;
await _platform.initialise(
publishableKey: publishableKey,
stripeAccountId: stripeAccountId,
threeDSecureParams: threeDSecureParams,
merchantIdentifier: merchantIdentifier,
urlScheme: urlScheme,
);
}
ValueNotifier<bool>? _isPlatformPaySupported;
// Internal use only
static final buildWebCard = _platform.buildCard;
}