-
Notifications
You must be signed in to change notification settings - Fork 629
/
Stripe.java
927 lines (864 loc) · 38.4 KB
/
Stripe.java
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
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
package com.stripe.android;
import android.content.Context;
import android.os.AsyncTask;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.Size;
import androidx.annotation.VisibleForTesting;
import com.stripe.android.exception.APIConnectionException;
import com.stripe.android.exception.APIException;
import com.stripe.android.exception.AuthenticationException;
import com.stripe.android.exception.CardException;
import com.stripe.android.exception.InvalidRequestException;
import com.stripe.android.exception.StripeException;
import com.stripe.android.model.AccountParams;
import com.stripe.android.model.BankAccount;
import com.stripe.android.model.Card;
import com.stripe.android.model.PaymentIntent;
import com.stripe.android.model.PaymentIntentParams;
import com.stripe.android.model.Source;
import com.stripe.android.model.SourceParams;
import com.stripe.android.model.StripePaymentSource;
import com.stripe.android.model.Token;
import java.lang.ref.WeakReference;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import static com.stripe.android.StripeNetworkUtils.hashMapFromBankAccount;
import static com.stripe.android.StripeNetworkUtils.hashMapFromCard;
import static com.stripe.android.StripeNetworkUtils.hashMapFromPersonalId;
/**
* Class that handles {@link Token} creation from charges, {@link Card}, and accounts.
*/
public class Stripe {
private final SourceCreator mSourceCreator = new SourceCreator() {
@Override
public void create(
@NonNull final SourceParams sourceParams,
@NonNull final String publishableKey,
@Nullable final String stripeAccount,
@Nullable Executor executor,
@NonNull final SourceCallback sourceCallback) {
executeTask(executor, new CreateSourceTask(mContext, sourceParams, publishableKey,
stripeAccount, sourceCallback));
}
};
@VisibleForTesting
TokenCreator mTokenCreator = new TokenCreator() {
@Override
public void create(
@NonNull final Map<String, Object> tokenParams,
@NonNull final String publishableKey,
@Nullable final String stripeAccount,
@NonNull @Token.TokenType final String tokenType,
@Nullable final Executor executor,
@NonNull final TokenCallback callback) {
executeTask(executor, new CreateTokenTask(mContext, tokenParams, publishableKey,
stripeAccount, tokenType, callback, mLoggingResponseListener));
}
};
@NonNull private final Context mContext;
@Nullable private StripeApiHandler.LoggingResponseListener mLoggingResponseListener;
private String mDefaultPublishableKey;
private String mStripeAccount;
/**
* A constructor with only context, to set the key later.
*
* @param context {@link Context} for resolving resources
*/
public Stripe(@NonNull Context context) {
mContext = context.getApplicationContext();
}
/**
* Constructor with publishable key.
*
* @param context {@link Context} for resolving resources
* @param publishableKey the client's publishable key
*/
public Stripe(@NonNull Context context, String publishableKey) {
mContext = context.getApplicationContext();
setDefaultPublishableKey(publishableKey);
}
/**
* The simplest way to create a {@link BankAccount} token. This runs on the default
* {@link Executor} and with the currently set {@link #mDefaultPublishableKey}.
*
* @param bankAccount the {@link BankAccount} used to create this token
* @param callback a {@link TokenCallback} to receive either the token or an error
*/
public void createBankAccountToken(
@NonNull final BankAccount bankAccount,
@NonNull final TokenCallback callback) {
createBankAccountToken(bankAccount, mDefaultPublishableKey, null, callback);
}
/**
* Call to create a {@link Token} for a {@link BankAccount} with the publishable key and
* {@link Executor} specified.
*
* @param bankAccount the {@link BankAccount} for which to create a {@link Token}
* @param publishableKey the publishable key to use
* @param executor an {@link Executor} to run this operation on. If null, this is run on a
* default non-ui executor
* @param callback a {@link TokenCallback} to receive the result or error message
*/
public void createBankAccountToken(
@NonNull final BankAccount bankAccount,
@NonNull @Size(min = 1) final String publishableKey,
@Nullable final Executor executor,
@NonNull final TokenCallback callback) {
if (bankAccount == null) {
throw new RuntimeException(
"Required parameter: 'bankAccount' is requred to create a token");
}
createTokenFromParams(
hashMapFromBankAccount(mContext, bankAccount),
publishableKey,
Token.TYPE_BANK_ACCOUNT,
executor,
callback);
}
/**
* The simplest way to create a PII token. This runs on the default
* {@link Executor} and with the currently set {@link #mDefaultPublishableKey}.
*
* @param personalId the personal id used to create this token
* @param callback a {@link TokenCallback} to receive either the token or an error
*/
public void createPiiToken(
@NonNull final String personalId,
@NonNull final TokenCallback callback) {
createPiiToken(personalId, mDefaultPublishableKey, null, callback);
}
/**
* Call to create a {@link Token} for PII with the publishable key and
* {@link Executor} specified.
*
* @param personalId the personal id used to create this token
* @param publishableKey the publishable key to use
* @param executor an {@link Executor} to run this operation on. If null, this is run on a
* default non-ui executor
* @param callback a {@link TokenCallback} to receive the result or error message
*/
public void createPiiToken(
@NonNull final String personalId,
@NonNull @Size(min = 1) final String publishableKey,
@Nullable final Executor executor,
@NonNull final TokenCallback callback) {
createTokenFromParams(
hashMapFromPersonalId(personalId),
publishableKey,
Token.TYPE_PII,
executor,
callback);
}
/**
* Blocking method to create a {@link Token} for a {@link BankAccount}. Do not call this on
* the UI thread or your app will crash.
*
* This method uses the default publishable key for this {@link Stripe} instance.
*
* @param bankAccount the {@link Card} to use for this token
* @return a {@link Token} that can be used for this {@link BankAccount}
*
* @throws AuthenticationException failure to properly authenticate yourself (check your key)
* @throws InvalidRequestException your request has invalid parameters
* @throws APIConnectionException failure to connect to Stripe's API
* @throws CardException should not be thrown with this type of token, but is theoretically
* possible given the underlying methods called
* @throws APIException any other type of problem (for instance, a temporary issue with
* Stripe's servers
*/
public Token createBankAccountTokenSynchronous(final BankAccount bankAccount)
throws AuthenticationException,
InvalidRequestException,
APIConnectionException,
CardException,
APIException {
return createBankAccountTokenSynchronous(bankAccount, mDefaultPublishableKey);
}
/**
* Blocking method to create a {@link Token} using a {@link BankAccount}. Do not call this on
* the UI thread or your app will crash.
*
* @param bankAccount the {@link BankAccount} to use for this token
* @param publishableKey the publishable key to use with this request
* @return a {@link Token} that can be used for this {@link BankAccount}
*
* @throws AuthenticationException failure to properly authenticate yourself (check your key)
* @throws InvalidRequestException your request has invalid parameters
* @throws APIConnectionException failure to connect to Stripe's API
* @throws CardException should not be thrown with this type of token, but is theoretically
* possible given the underlying methods called
* @throws APIException any other type of problem
*/
public Token createBankAccountTokenSynchronous(
final BankAccount bankAccount,
String publishableKey)
throws AuthenticationException,
InvalidRequestException,
APIConnectionException,
CardException,
APIException {
validateKey(publishableKey);
RequestOptions requestOptions = RequestOptions.builder(
publishableKey,
mStripeAccount,
RequestOptions.TYPE_QUERY).build();
return StripeApiHandler.createToken(
mContext,
hashMapFromBankAccount(mContext, bankAccount),
requestOptions,
Token.TYPE_BANK_ACCOUNT,
mLoggingResponseListener);
}
/**
* Create a {@link Source} using an {@link AsyncTask} on the default {@link Executor} with a
* publishable api key that has already been set on this {@link Stripe} instance.
*
* @param sourceParams the {@link SourceParams} to be used
* @param callback a {@link SourceCallback} to receive a result or an error message
*/
public void createSource(@NonNull SourceParams sourceParams, @NonNull SourceCallback callback) {
createSource(sourceParams, callback, null, null);
}
/**
* Create a {@link Source} using an {@link AsyncTask}.
*
* @param sourceParams the {@link SourceParams} to be used
* @param callback a {@link SourceCallback} to receive a result or an error message
* @param publishableKey the publishable api key to be used
* @param executor an {@link Executor} on which to execute the task, or {@link null} for default
*/
public void createSource(
@NonNull SourceParams sourceParams,
@NonNull SourceCallback callback,
@Nullable String publishableKey,
@Nullable Executor executor) {
String apiKey = publishableKey == null ? mDefaultPublishableKey : publishableKey;
if (apiKey == null) {
return;
}
mSourceCreator.create(sourceParams, apiKey, mStripeAccount, executor, callback);
}
/**
* The simplest way to create a token, using a {@link Card} and {@link TokenCallback}. This
* runs on the default {@link Executor} and with the
* currently set {@link #mDefaultPublishableKey}.
*
* @param card the {@link Card} used to create this payment token
* @param callback a {@link TokenCallback} to receive either the token or an error
*/
public void createToken(@NonNull final Card card, @NonNull final TokenCallback callback) {
createToken(card, mDefaultPublishableKey, callback);
}
/**
* Call to create a {@link Token} with a specific public key.
*
* @param card the {@link Card} used for this transaction
* @param publishableKey the public key used for this transaction
* @param callback a {@link TokenCallback} to receive the result of this operation
*/
public void createToken(
@NonNull final Card card,
@NonNull final String publishableKey,
@NonNull final TokenCallback callback) {
createToken(card, publishableKey, null, callback);
}
/**
* Call to create a {@link Token} on a specific {@link Executor}.
* @param card the {@link Card} to use for this token creation
* @param executor An {@link Executor} on which to run this operation. If you don't wish to
* specify an executor, use one of the other createTokenFromParams methods.
* @param callback a {@link TokenCallback} to receive the result of this operation
*/
public void createToken(
@NonNull final Card card,
@NonNull final Executor executor,
@NonNull final TokenCallback callback) {
createToken(card, mDefaultPublishableKey, executor, callback);
}
/**
* Call to create a {@link Token} with the publishable key and {@link Executor} specified.
*
* @param card the {@link Card} used for this token
* @param publishableKey the publishable key to use
* @param executor an {@link Executor} to run this operation on. If null, this is run on a
* default non-ui executor
* @param callback a {@link TokenCallback} to receive the result or error message
*/
public void createToken(
@NonNull final Card card,
@NonNull @Size(min = 1) final String publishableKey,
@Nullable final Executor executor,
@NonNull final TokenCallback callback) {
if (card == null) {
throw new RuntimeException(
"Required Parameter: 'card' is required to create a token");
}
createTokenFromParams(
hashMapFromCard(mContext, card),
publishableKey,
Token.TYPE_CARD,
executor,
callback);
}
/**
* Blocking method to create a {@link Source} object using this object's
* {@link Stripe#mDefaultPublishableKey key}.
*
* Do not call this on the UI thread or your app will crash.
*
* @param params a set of {@link SourceParams} with which to create the source
* @return a {@link Source}, or {@code null} if a problem occurred
*
* @throws AuthenticationException failure to properly authenticate yourself (check your key)
* @throws InvalidRequestException your request has invalid parameters
* @throws APIConnectionException failure to connect to Stripe's API
* @throws APIException any other type of problem (for instance, a temporary issue with
* Stripe's servers
*/
@Nullable
public Source createSourceSynchronous(@NonNull SourceParams params)
throws AuthenticationException,
InvalidRequestException,
APIConnectionException,
APIException {
return createSourceSynchronous(params, null);
}
/**
* Blocking method to create a {@link Source} object.
* Do not call this on the UI thread or your app will crash.
*
* @param params a set of {@link SourceParams} with which to create the source
* @param publishableKey a publishable API key to use
* @return a {@link Source}, or {@code null} if a problem occurred
* @throws AuthenticationException failure to properly authenticate yourself (check your key)
* @throws InvalidRequestException your request has invalid parameters
* @throws APIConnectionException failure to connect to Stripe's API
* @throws APIException any other type of problem (for instance, a temporary issue with
* Stripe's servers
*/
public Source createSourceSynchronous(
@NonNull SourceParams params,
@Nullable String publishableKey)
throws AuthenticationException,
InvalidRequestException,
APIConnectionException,
APIException {
String apiKey = publishableKey == null ? mDefaultPublishableKey : publishableKey;
if (apiKey == null) {
return null;
}
return StripeApiHandler.createSource(
null, mContext, params, apiKey, mStripeAccount, mLoggingResponseListener);
}
/**
* Blocking method to retrieve a {@link PaymentIntent} object.
* Do not call this on the UI thread or your app will crash.
*
* @param paymentIntentParams a set of params with which to retrieve the Payment Intent
* @param publishableKey a publishable API key to use
* @return a {@link PaymentIntent} or {@code null} if a problem occurred
*
* @throws AuthenticationException
* @throws InvalidRequestException
* @throws APIConnectionException
* @throws APIException
*/
public PaymentIntent retrievePaymentIntentSynchronous(
@NonNull PaymentIntentParams paymentIntentParams,
@NonNull String publishableKey) throws AuthenticationException,
InvalidRequestException,
APIConnectionException,
APIException {
return StripeApiHandler.retrievePaymentIntent(
mContext,
paymentIntentParams,
publishableKey,
mStripeAccount,
mLoggingResponseListener);
}
/**
* Blocking method to confirm a {@link PaymentIntent} object.
* Do not call this on the UI thread or your app will crash.
*
* @param paymentIntentParams a set of params with which to confirm the Payment Intent
* @param publishableKey a publishable API key to use
* @return a {@link PaymentIntent} or {@code null} if a problem occurred
*
* @throws AuthenticationException
* @throws InvalidRequestException
* @throws APIConnectionException
* @throws APIException
*/
public PaymentIntent confirmPaymentIntentSynchronous(
@NonNull PaymentIntentParams paymentIntentParams,
@NonNull String publishableKey) throws AuthenticationException,
InvalidRequestException,
APIConnectionException,
APIException {
return StripeApiHandler.confirmPaymentIntent(
null,
mContext,
paymentIntentParams,
publishableKey,
mStripeAccount,
mLoggingResponseListener);
}
/**
* Blocking method to create a {@link Token}. Do not call this on the UI thread or your app
* will crash. This method uses the default publishable key for this {@link Stripe} instance.
*
* @param card the {@link Card} to use for this token
* @return a {@link Token} that can be used for this card
*
* @throws AuthenticationException failure to properly authenticate yourself (check your key)
* @throws InvalidRequestException your request has invalid parameters
* @throws APIConnectionException failure to connect to Stripe's API
* @throws CardException the card cannot be charged for some reason
* @throws APIException any other type of problem (for instance, a temporary issue with
* Stripe's servers
*/
public Token createTokenSynchronous(final Card card)
throws AuthenticationException,
InvalidRequestException,
APIConnectionException,
CardException,
APIException {
return createTokenSynchronous(card, mDefaultPublishableKey);
}
/**
* Blocking method to create a {@link Token}. Do not call this on the UI thread or your app
* will crash.
*
* @param card the {@link Card} to use for this token
* @param publishableKey the publishable key to use with this request
* @return a {@link Token} that can be used for this card
*
* @throws AuthenticationException failure to properly authenticate yourself (check your key)
* @throws InvalidRequestException your request has invalid parameters
* @throws APIConnectionException failure to connect to Stripe's API
* @throws APIException any other type of problem (for instance, a temporary issue with
* Stripe's servers)
*/
public Token createTokenSynchronous(final Card card, String publishableKey)
throws AuthenticationException,
InvalidRequestException,
APIConnectionException,
CardException,
APIException {
validateKey(publishableKey);
RequestOptions requestOptions = RequestOptions.builder(
publishableKey,
mStripeAccount,
RequestOptions.TYPE_QUERY).build();
return StripeApiHandler.createToken(
mContext,
hashMapFromCard(mContext, card),
requestOptions,
Token.TYPE_CARD,
mLoggingResponseListener);
}
/**
* Blocking method to create a {@link Token} for PII. Do not call this on the UI thread
* or your app will crash. The method uses the currently set {@link #mDefaultPublishableKey}.
*
* @param personalId the personal ID to use for this token
* @return a {@link Token} that can be used for this card
*
* @throws AuthenticationException failure to properly authenticate yourself (check your key)
* @throws InvalidRequestException your request has invalid parameters
* @throws APIConnectionException failure to connect to Stripe's API
* @throws APIException any other type of problem (for instance, a temporary issue with
* Stripe's servers)
*/
public Token createPiiTokenSynchronous(@NonNull String personalId)
throws AuthenticationException,
InvalidRequestException,
APIConnectionException,
CardException,
APIException {
return createPiiTokenSynchronous(personalId, mDefaultPublishableKey);
}
/**
* Blocking method to create a {@link Token} for PII. Do not call this on the UI thread
* or your app will crash.
*
* @param personalId the personal ID to use for this token
* @param publishableKey the publishable key to use with this request
* @return a {@link Token} that can be used for this card
*
* @throws AuthenticationException failure to properly authenticate yourself (check your key)
* @throws InvalidRequestException your request has invalid parameters
* @throws APIConnectionException failure to connect to Stripe's API
* @throws APIException any other type of problem (for instance, a temporary issue with
* Stripe's servers)
*/
public Token createPiiTokenSynchronous(@NonNull String personalId, String publishableKey)
throws AuthenticationException,
InvalidRequestException,
APIConnectionException,
CardException,
APIException {
validateKey(publishableKey);
RequestOptions requestOptions = RequestOptions.builder(
publishableKey,
mStripeAccount,
RequestOptions.TYPE_QUERY).build();
return StripeApiHandler.createToken(
mContext,
hashMapFromPersonalId(personalId),
requestOptions,
Token.TYPE_PII,
mLoggingResponseListener);
}
/**
* Blocking method to create a {@link Token} for a Connect Account. Do not call this on the UI
* thread or your app will crash. The method uses the currently set
* {@link #mDefaultPublishableKey}.
*
* @param accountParams params to use for this token.
* @return a {@link Token} that can be used for this account.
*
* @throws AuthenticationException failure to properly authenticate yourself (check your key)
* @throws InvalidRequestException your request has invalid parameters
* @throws APIConnectionException failure to connect to Stripe's API
* @throws APIException any other type of problem (for instance, a temporary issue with
* Stripe's servers)
*/
public Token createAccountTokenSynchronous(@NonNull final AccountParams accountParams)
throws AuthenticationException,
InvalidRequestException,
APIConnectionException,
APIException {
return createAccountTokenSynchronous(accountParams, mDefaultPublishableKey);
}
/**
* Blocking method to create a {@link Token} for a Connect Account. Do not call this on the UI
* thread.
*
* @param accountParams params to use for this token.
* @param publishableKey the publishable key to use with this request. If null is passed in as
* the publishable key, we will use the default publishable key.
* @return a {@link Token} that can be used for this account.
*
* @throws AuthenticationException failure to properly authenticate yourself (check your key)
* @throws InvalidRequestException your request has invalid parameters
* @throws APIConnectionException failure to connect to Stripe's API
* @throws APIException any other type of problem (for instance, a temporary issue with
* Stripe's servers)
*/
public Token createAccountTokenSynchronous(
@NonNull final AccountParams accountParams,
@Nullable String publishableKey)
throws AuthenticationException,
InvalidRequestException,
APIConnectionException,
APIException {
String apiKey = publishableKey == null ? mDefaultPublishableKey : publishableKey;
if (apiKey == null) {
return null;
}
validateKey(publishableKey);
RequestOptions requestOptions = RequestOptions.builder(
publishableKey,
mStripeAccount,
RequestOptions.TYPE_QUERY).build();
try {
return StripeApiHandler.createToken(
mContext,
accountParams.toParamMap(),
requestOptions,
Token.TYPE_ACCOUNT,
mLoggingResponseListener);
} catch (CardException exception) {
// Should never occur. CardException is only for card related requests.
}
return null;
}
public void logEventSynchronous(
@NonNull List<String> productUsageTokens,
@NonNull StripePaymentSource paymentSource) {
RequestOptions.RequestOptionsBuilder builder =
RequestOptions.builder(mDefaultPublishableKey);
if (mStripeAccount != null) {
builder.setStripeAccount(mStripeAccount);
}
RequestOptions options = builder.build();
final Map<String, Object> loggingMap;
if (paymentSource instanceof Token) {
Token token = (Token) paymentSource;
loggingMap = LoggingUtils.getTokenCreationParams(
mContext,
productUsageTokens,
mDefaultPublishableKey,
token.getType());
} else {
Source source = (Source) paymentSource;
loggingMap = LoggingUtils.getSourceCreationParams(
mContext,
productUsageTokens,
mDefaultPublishableKey,
source.getType());
}
StripeApiHandler.logApiCall(loggingMap, options, mLoggingResponseListener);
}
/**
* Retrieve an existing {@link Source} from the Stripe API. Note that this is a
* synchronous method, and cannot be called on the main thread. Doing so will cause your app
* to crash. This method uses the default publishable key for this {@link Stripe} instance.
*
* @param sourceId the {@link Source#mId} field of the desired Source object
* @param clientSecret the {@link Source#mClientSecret} field of the desired Source object
* @return a {@link Source} if one could be found based on the input params, or {@code null} if
* no such Source could be found.
*
* @throws AuthenticationException failure to properly authenticate yourself (check your key)
* @throws InvalidRequestException your request has invalid parameters
* @throws APIConnectionException failure to connect to Stripe's API
* @throws APIException any other type of problem (for instance, a temporary issue with
* Stripe's servers)
*/
public Source retrieveSourceSynchronous(
@NonNull @Size(min = 1) String sourceId,
@NonNull @Size(min = 1) String clientSecret)
throws AuthenticationException,
InvalidRequestException,
APIConnectionException,
APIException {
return retrieveSourceSynchronous(sourceId, clientSecret, null);
}
/**
* Retrieve an existing {@link Source} from the Stripe API. Note that this is a
* synchronous method, and cannot be called on the main thread. Doing so will cause your app
* to crash.
*
* @param sourceId the {@link Source#mId} field of the desired Source object
* @param clientSecret the {@link Source#mClientSecret} field of the desired Source object
* @param publishableKey a publishable API key to use
* @return a {@link Source} if one could be found based on the input params, or {@code null} if
* no such Source could be found.
*
* @throws AuthenticationException failure to properly authenticate yourself (check your key)
* @throws InvalidRequestException your request has invalid parameters
* @throws APIConnectionException failure to connect to Stripe's API
* @throws APIException any other type of problem (for instance, a temporary issue with
* Stripe's servers)
*/
public Source retrieveSourceSynchronous(
@NonNull @Size(min = 1) String sourceId,
@NonNull @Size(min = 1) String clientSecret,
@Nullable String publishableKey)
throws AuthenticationException,
InvalidRequestException,
APIConnectionException,
APIException {
String apiKey = publishableKey == null ? mDefaultPublishableKey : publishableKey;
if (apiKey == null) {
return null;
}
return StripeApiHandler.retrieveSource(sourceId, clientSecret, apiKey, mStripeAccount);
}
/**
* Set the default publishable key to use with this {@link Stripe} instance.
*
* @param publishableKey the key to be set
*/
public void setDefaultPublishableKey(@NonNull @Size(min = 1) String publishableKey) {
validateKey(publishableKey);
mDefaultPublishableKey = publishableKey;
}
/**
* Set the Stripe Connect account to use with this Stripe instance.
*
* @see <a href=https://stripe.com/docs/connect/authentication#authentication-via-the-stripe-account-header>
* Authentication via the stripe account header</a>
* @param stripeAccount the account ID to be set
*/
public void setStripeAccount(@NonNull @Size(min = 1) String stripeAccount) {
mStripeAccount = stripeAccount;
}
@VisibleForTesting
void setLoggingResponseListener(StripeApiHandler.LoggingResponseListener listener) {
mLoggingResponseListener = listener;
}
private void createTokenFromParams(
@NonNull final Map<String, Object> tokenParams,
@NonNull @Size(min = 1) final String publishableKey,
@NonNull @Token.TokenType final String tokenType,
@Nullable final Executor executor,
@NonNull final TokenCallback callback) {
if (callback == null) {
throw new RuntimeException(
"Required Parameter: 'callback' is required to use the created " +
"token and handle errors");
}
validateKey(publishableKey);
mTokenCreator.create(
tokenParams,
publishableKey,
mStripeAccount,
tokenType,
executor,
callback);
}
private void validateKey(@NonNull @Size(min = 1) String publishableKey) {
if (publishableKey == null || publishableKey.length() == 0) {
throw new IllegalArgumentException("Invalid Publishable Key: " +
"You must use a valid publishable key to create a token. " +
"For more info, see https://stripe.com/docs/stripe.js.");
}
if (publishableKey.startsWith("sk_")) {
throw new IllegalArgumentException("Invalid Publishable Key: " +
"You are using a secret key to create a token, " +
"instead of the publishable one. For more info, " +
"see https://stripe.com/docs/stripe.js");
}
}
private void executeTask(@Nullable Executor executor,
@NonNull AsyncTask<Void, Void, ResponseWrapper> task) {
if (executor != null) {
task.executeOnExecutor(executor);
} else {
task.execute();
}
}
private static class ResponseWrapper {
@Nullable final Source source;
@Nullable final Token token;
@Nullable final Exception error;
private ResponseWrapper(@Nullable Token token) {
this.token = token;
this.source = null;
this.error = null;
}
private ResponseWrapper(@Nullable Source source) {
this.source = source;
this.error = null;
this.token = null;
}
private ResponseWrapper(@NonNull Exception error) {
this.error = error;
this.source = null;
this.token = null;
}
}
interface SourceCreator {
void create(
@NonNull SourceParams params,
@NonNull String publishableKey,
@Nullable String stripeAccount,
@Nullable Executor executor,
@NonNull SourceCallback sourceCallback);
}
@VisibleForTesting
interface TokenCreator {
void create(Map<String, Object> params,
String publishableKey,
String stripeAccount,
@NonNull @Token.TokenType String tokenType,
Executor executor,
TokenCallback callback);
}
private static class CreateSourceTask extends AsyncTask<Void, Void, ResponseWrapper> {
@NonNull private final WeakReference<Context> mContextRef;
@NonNull private final SourceParams mSourceParams;
@NonNull private final String mPublishableKey;
@Nullable private final String mStripeAccount;
@NonNull private final WeakReference<SourceCallback> mSourceCallbackRef;
CreateSourceTask(@NonNull Context context,
@NonNull SourceParams sourceParams,
@NonNull String publishableKey,
@Nullable String stripeAccount,
@NonNull SourceCallback sourceCallback) {
mContextRef = new WeakReference<>(context);
mSourceParams = sourceParams;
mPublishableKey = publishableKey;
mStripeAccount = stripeAccount;
mSourceCallbackRef = new WeakReference<>(sourceCallback);
}
@Override
protected ResponseWrapper doInBackground(Void... params) {
try {
final Source source = StripeApiHandler.createSource(
null,
mContextRef.get(),
mSourceParams,
mPublishableKey,
mStripeAccount,
null);
return new ResponseWrapper(source);
} catch (StripeException stripeException) {
return new ResponseWrapper(stripeException);
}
}
@Override
protected void onPostExecute(@NonNull ResponseWrapper responseWrapper) {
final SourceCallback sourceCallback = mSourceCallbackRef.get();
if (sourceCallback != null) {
if (responseWrapper.source != null) {
sourceCallback.onSuccess(responseWrapper.source);
} else if (responseWrapper.error != null) {
sourceCallback.onError(responseWrapper.error);
}
}
}
}
private static class CreateTokenTask extends AsyncTask<Void, Void, ResponseWrapper> {
@NonNull private final WeakReference<Context> mContextRef;
@NonNull private final Map<String, Object> mTokenParams;
@NonNull private final String mPublishableKey;
@Nullable private final String mStripeAccount;
@NonNull @Token.TokenType private final String mTokenType;
@NonNull private final WeakReference<TokenCallback> mCallbackRef;
@Nullable private final StripeApiHandler.LoggingResponseListener mLoggingResponseListener;
CreateTokenTask(@NonNull Context context,
@NonNull final Map<String, Object> tokenParams,
@NonNull final String publishableKey,
@Nullable final String stripeAccount,
@NonNull @Token.TokenType final String tokenType,
@Nullable final TokenCallback callback,
@Nullable final StripeApiHandler.LoggingResponseListener loggingResponseListener) {
mContextRef = new WeakReference<>(context);
mTokenParams = tokenParams;
mPublishableKey = publishableKey;
mStripeAccount = stripeAccount;
mTokenType = tokenType;
mLoggingResponseListener = loggingResponseListener;
mCallbackRef = new WeakReference<>(callback);
}
@Override
protected ResponseWrapper doInBackground(Void... params) {
try {
final RequestOptions requestOptions = RequestOptions.builder(mPublishableKey,
mStripeAccount, RequestOptions.TYPE_QUERY).build();
final Token token = StripeApiHandler.createToken(
mContextRef.get(),
mTokenParams,
requestOptions,
mTokenType,
mLoggingResponseListener);
return new ResponseWrapper(token);
} catch (StripeException e) {
return new ResponseWrapper(e);
}
}
@Override
protected void onPostExecute(@NonNull ResponseWrapper result) {
tokenTaskPostExecution(result);
}
private void tokenTaskPostExecution(@NonNull ResponseWrapper result) {
final TokenCallback callback = mCallbackRef.get();
if (callback != null) {
if (result.token != null) {
callback.onSuccess(result.token);
} else if (result.error != null) {
callback.onError(result.error);
} else {
callback.onError(new RuntimeException("Somehow got neither a token response or"
+ " an error response"));
}
}
}
}
}