-
Notifications
You must be signed in to change notification settings - Fork 629
/
StripePaymentController.kt
592 lines (552 loc) · 21.2 KB
/
StripePaymentController.kt
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
package com.stripe.android
import android.content.Context
import android.content.Intent
import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.ActivityResultCaller
import androidx.activity.result.ActivityResultLauncher
import androidx.annotation.VisibleForTesting
import com.google.android.instantapps.InstantApps
import com.stripe.android.core.Logger
import com.stripe.android.core.exception.APIConnectionException
import com.stripe.android.core.exception.APIException
import com.stripe.android.core.exception.AuthenticationException
import com.stripe.android.core.exception.InvalidRequestException
import com.stripe.android.core.exception.StripeException
import com.stripe.android.core.networking.AnalyticsRequestExecutor
import com.stripe.android.core.networking.ApiRequest
import com.stripe.android.core.networking.DefaultAnalyticsRequestExecutor
import com.stripe.android.model.ConfirmPaymentIntentParams
import com.stripe.android.model.ConfirmSetupIntentParams
import com.stripe.android.model.ConfirmStripeIntentParams
import com.stripe.android.model.PaymentIntent
import com.stripe.android.model.SetupIntent
import com.stripe.android.model.Source
import com.stripe.android.model.StripeIntent
import com.stripe.android.model.WeChatPayNextAction
import com.stripe.android.networking.AlipayRepository
import com.stripe.android.networking.DefaultAlipayRepository
import com.stripe.android.networking.PaymentAnalyticsEvent
import com.stripe.android.networking.PaymentAnalyticsRequestFactory
import com.stripe.android.networking.StripeRepository
import com.stripe.android.payments.DefaultReturnUrl
import com.stripe.android.payments.PaymentFlowFailureMessageFactory
import com.stripe.android.payments.PaymentFlowResult
import com.stripe.android.payments.PaymentIntentFlowResultProcessor
import com.stripe.android.payments.SetupIntentFlowResultProcessor
import com.stripe.android.payments.core.authentication.DefaultPaymentAuthenticatorRegistry
import com.stripe.android.payments.core.authentication.PaymentAuthenticatorRegistry
import com.stripe.android.view.AuthActivityStarterHost
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.util.concurrent.TimeUnit
import kotlin.coroutines.CoroutineContext
/**
* A controller responsible for confirming and authenticating payment (typically through resolving
* any required customer action). The payment authentication mechanism (e.g. 3DS) will be determined
* by the [PaymentIntent] or [SetupIntent] object.
*/
internal class StripePaymentController
constructor(
context: Context,
private val publishableKeyProvider: () -> String,
private val stripeRepository: StripeRepository,
private val enableLogging: Boolean = false,
workContext: CoroutineContext = Dispatchers.IO,
private val analyticsRequestExecutor: AnalyticsRequestExecutor =
DefaultAnalyticsRequestExecutor(Logger.getInstance(enableLogging), workContext),
private val paymentAnalyticsRequestFactory: PaymentAnalyticsRequestFactory =
PaymentAnalyticsRequestFactory(context.applicationContext, publishableKeyProvider),
private val alipayRepository: AlipayRepository = DefaultAlipayRepository(stripeRepository),
private val uiContext: CoroutineContext = Dispatchers.Main
) : PaymentController {
private val failureMessageFactory = PaymentFlowFailureMessageFactory(context)
private val paymentIntentFlowResultProcessor = PaymentIntentFlowResultProcessor(
context,
publishableKeyProvider,
stripeRepository,
Logger.getInstance(enableLogging),
workContext
)
private val setupIntentFlowResultProcessor = SetupIntentFlowResultProcessor(
context,
publishableKeyProvider,
stripeRepository,
Logger.getInstance(enableLogging),
workContext
)
private val defaultReturnUrl = DefaultReturnUrl.create(context)
private val isInstantApp = InstantApps.isInstantApp(context)
/**
* [paymentRelayLauncher] is mutable and might be updated during
* through [registerLaunchersWithActivityResultCaller]
*/
private var paymentRelayLauncher: ActivityResultLauncher<PaymentRelayStarter.Args>? = null
private val paymentRelayStarterFactory = { host: AuthActivityStarterHost ->
paymentRelayLauncher?.let {
PaymentRelayStarter.Modern(it)
} ?: PaymentRelayStarter.Legacy(host)
}
/**
* A map between 3ds1 [StripeIntent] ids to its corresponding returnUrl.
* An entry will be removed once the [StripeIntent] is confirmed.
*/
private val threeDs1IntentReturnUrlMap = mutableMapOf<String, String>()
private val authenticatorRegistry: PaymentAuthenticatorRegistry =
DefaultPaymentAuthenticatorRegistry.createInstance(
context,
stripeRepository,
analyticsRequestExecutor,
paymentAnalyticsRequestFactory,
enableLogging,
workContext,
uiContext,
threeDs1IntentReturnUrlMap,
publishableKeyProvider,
paymentAnalyticsRequestFactory.defaultProductUsageTokens,
isInstantApp
)
override fun registerLaunchersWithActivityResultCaller(
activityResultCaller: ActivityResultCaller,
activityResultCallback: ActivityResultCallback<PaymentFlowResult.Unvalidated>
) {
paymentRelayLauncher = activityResultCaller.registerForActivityResult(
PaymentRelayContract(),
activityResultCallback
)
authenticatorRegistry.onNewActivityResultCaller(
activityResultCaller,
activityResultCallback
)
}
override fun unregisterLaunchers() {
paymentRelayLauncher?.unregister()
paymentRelayLauncher = null
authenticatorRegistry.onLauncherInvalidated()
}
/**
* Confirm the Stripe Intent and resolve any next actions
*/
override suspend fun startConfirmAndAuth(
host: AuthActivityStarterHost,
confirmStripeIntentParams: ConfirmStripeIntentParams,
requestOptions: ApiRequest.Options
) {
logReturnUrl(confirmStripeIntentParams.returnUrl)
val returnUrl =
if (isInstantApp) {
confirmStripeIntentParams.returnUrl
} else {
confirmStripeIntentParams.returnUrl.takeUnless { it.isNullOrBlank() }
?: defaultReturnUrl.value
}
runCatching {
when (confirmStripeIntentParams) {
is ConfirmPaymentIntentParams -> {
confirmPaymentIntent(
confirmStripeIntentParams.also {
it.returnUrl = returnUrl
},
requestOptions
)
}
is ConfirmSetupIntentParams -> {
confirmSetupIntent(
confirmStripeIntentParams.also {
it.returnUrl = returnUrl
},
requestOptions
)
}
}
}.fold(
onSuccess = { intent ->
intent.nextActionData?.let {
if (it is StripeIntent.NextActionData.SdkData.Use3DS1) {
intent.id?.let { intentId ->
threeDs1IntentReturnUrlMap[intentId] = returnUrl.orEmpty()
}
}
}
handleNextAction(
host,
intent,
requestOptions
)
},
onFailure = {
handleError(
host,
getRequestCode(confirmStripeIntentParams),
it
)
}
)
}
override suspend fun confirmAndAuthenticateAlipay(
confirmPaymentIntentParams: ConfirmPaymentIntentParams,
authenticator: AlipayAuthenticator,
requestOptions: ApiRequest.Options
): PaymentIntentResult {
return authenticateAlipay(
confirmPaymentIntent(
confirmPaymentIntentParams,
requestOptions
),
authenticator,
requestOptions
)
}
override suspend fun confirmWeChatPay(
confirmPaymentIntentParams: ConfirmPaymentIntentParams,
requestOptions: ApiRequest.Options
): WeChatPayNextAction {
confirmPaymentIntent(
confirmPaymentIntentParams,
requestOptions
).let { paymentIntent ->
require(paymentIntent.nextActionData is StripeIntent.NextActionData.WeChatPayRedirect) {
"Unable to confirm Payment Intent with WeChatPay SDK"
}
return WeChatPayNextAction(
paymentIntent,
paymentIntent.nextActionData.weChat
)
}
}
private suspend fun confirmPaymentIntent(
confirmStripeIntentParams: ConfirmPaymentIntentParams,
requestOptions: ApiRequest.Options
): PaymentIntent {
return requireNotNull(
stripeRepository.confirmPaymentIntent(
// mark this request as `use_stripe_sdk=true`
confirmStripeIntentParams
.withShouldUseStripeSdk(shouldUseStripeSdk = true),
requestOptions,
expandFields = EXPAND_PAYMENT_METHOD
)
) {
REQUIRED_ERROR
}
}
private suspend fun confirmSetupIntent(
confirmStripeIntentParams: ConfirmSetupIntentParams,
requestOptions: ApiRequest.Options
): SetupIntent {
return requireNotNull(
stripeRepository.confirmSetupIntent(
// mark this request as `use_stripe_sdk=true`
confirmStripeIntentParams
.withShouldUseStripeSdk(shouldUseStripeSdk = true),
requestOptions,
expandFields = EXPAND_PAYMENT_METHOD
)
) {
REQUIRED_ERROR
}
}
override suspend fun startAuth(
host: AuthActivityStarterHost,
clientSecret: String,
requestOptions: ApiRequest.Options,
type: PaymentController.StripeIntentType
) {
runCatching {
val stripeIntent = when (type) {
PaymentController.StripeIntentType.PaymentIntent -> {
stripeRepository.retrievePaymentIntent(
clientSecret,
requestOptions
)
}
PaymentController.StripeIntentType.SetupIntent -> {
stripeRepository.retrieveSetupIntent(
clientSecret,
requestOptions
)
}
}
requireNotNull(stripeIntent)
}.fold(
onSuccess = { stripeIntent ->
handleNextAction(
host = host,
stripeIntent = stripeIntent,
requestOptions = requestOptions
)
},
onFailure = {
handleError(
host,
when (type) {
PaymentController.StripeIntentType.PaymentIntent -> {
PAYMENT_REQUEST_CODE
}
PaymentController.StripeIntentType.SetupIntent -> {
SETUP_REQUEST_CODE
}
},
it
)
}
)
}
override suspend fun startAuthenticateSource(
host: AuthActivityStarterHost,
source: Source,
requestOptions: ApiRequest.Options
) {
analyticsRequestExecutor.executeAsync(
paymentAnalyticsRequestFactory.createRequest(PaymentAnalyticsEvent.AuthSourceStart)
)
runCatching {
requireNotNull(
stripeRepository.retrieveSource(
sourceId = source.id.orEmpty(),
clientSecret = source.clientSecret.orEmpty(),
options = requestOptions
)
)
}.fold(
onSuccess = { retrievedSourced ->
onSourceRetrieved(host, retrievedSourced, requestOptions)
},
onFailure = {
handleError(
host,
SOURCE_REQUEST_CODE,
it
)
}
)
}
private suspend fun onSourceRetrieved(
host: AuthActivityStarterHost,
source: Source,
requestOptions: ApiRequest.Options
) {
authenticatorRegistry.getAuthenticator(source).authenticate(
host,
source,
requestOptions
)
}
/**
* Decide whether [getPaymentIntentResult] should be called.
*/
override fun shouldHandlePaymentResult(requestCode: Int, data: Intent?): Boolean {
return requestCode == PAYMENT_REQUEST_CODE && data != null
}
/**
* Decide whether [getSetupIntentResult] should be called.
*/
override fun shouldHandleSetupResult(requestCode: Int, data: Intent?): Boolean {
return requestCode == SETUP_REQUEST_CODE && data != null
}
override fun shouldHandleSourceResult(requestCode: Int, data: Intent?): Boolean {
return requestCode == SOURCE_REQUEST_CODE && data != null
}
/**
* Get the PaymentIntent's client_secret from {@param data} and use to retrieve
* the PaymentIntent object with updated status.
*
* @param data the result Intent
* @return the [PaymentIntentResult] object
*
* @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)
* @throws IllegalArgumentException if the response's JsonParser returns null
*/
@Throws(
AuthenticationException::class,
InvalidRequestException::class,
APIConnectionException::class,
APIException::class,
IllegalArgumentException::class
)
override suspend fun getPaymentIntentResult(data: Intent) =
paymentIntentFlowResultProcessor.processResult(
PaymentFlowResult.Unvalidated.fromIntent(data)
)
/**
* Get the SetupIntent's client_secret from {@param data} and use to retrieve
* the PaymentIntent object with updated status.
*
* @param data the result Intent
* @return the [SetupIntentResult] object
*
* @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)
* @throws IllegalArgumentException if the response's JsonParser returns null
*/
@Throws(
AuthenticationException::class,
InvalidRequestException::class,
APIConnectionException::class,
APIException::class,
IllegalArgumentException::class
)
override suspend fun getSetupIntentResult(data: Intent) =
setupIntentFlowResultProcessor.processResult(
PaymentFlowResult.Unvalidated.fromIntent(data)
)
/**
* Get the Source's client_secret from {@param data} and use to retrieve
* the Source object with updated status.
*
* @param data the result Intent
* @return the [Source] object
*
* @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)
* @throws IllegalArgumentException if the Source response's JsonParser returns null
*/
@Throws(
AuthenticationException::class,
InvalidRequestException::class,
APIConnectionException::class,
APIException::class,
IllegalArgumentException::class
)
override suspend fun getAuthenticateSourceResult(data: Intent): Source {
val result = PaymentFlowResult.Unvalidated.fromIntent(data)
val sourceId = result.sourceId.orEmpty()
val clientSecret = result.clientSecret.orEmpty()
val requestOptions = ApiRequest.Options(
apiKey = publishableKeyProvider(),
stripeAccount = result.stripeAccountId
)
analyticsRequestExecutor.executeAsync(
paymentAnalyticsRequestFactory.createRequest(PaymentAnalyticsEvent.AuthSourceResult)
)
return requireNotNull(
stripeRepository.retrieveSource(
sourceId,
clientSecret,
requestOptions
)
)
}
private suspend fun authenticateAlipay(
paymentIntent: PaymentIntent,
authenticator: AlipayAuthenticator,
requestOptions: ApiRequest.Options
): PaymentIntentResult {
val outcome =
alipayRepository.authenticate(paymentIntent, authenticator, requestOptions).outcome
val refreshedPaymentIntent = requireNotNull(
stripeRepository.retrievePaymentIntent(
paymentIntent.clientSecret.orEmpty(),
requestOptions,
expandFields = EXPAND_PAYMENT_METHOD
)
)
return PaymentIntentResult(
refreshedPaymentIntent,
outcome,
failureMessageFactory.create(refreshedPaymentIntent, outcome)
)
}
private suspend fun handleError(
host: AuthActivityStarterHost,
requestCode: Int,
throwable: Throwable
) = withContext(uiContext) {
paymentRelayStarterFactory(host)
.start(
PaymentRelayStarter.Args.ErrorArgs(
StripeException.create(throwable),
requestCode
)
)
}
/**
* Determine which authentication mechanism should be used, or bypass authentication
* if it is not needed.
*/
@VisibleForTesting
override suspend fun handleNextAction(
host: AuthActivityStarterHost,
stripeIntent: StripeIntent,
requestOptions: ApiRequest.Options
) {
authenticatorRegistry.getAuthenticator(stripeIntent).authenticate(
host,
stripeIntent,
requestOptions
)
}
private fun logReturnUrl(returnUrl: String?) {
when (returnUrl) {
defaultReturnUrl.value -> {
PaymentAnalyticsEvent.ConfirmReturnUrlDefault
}
null -> {
PaymentAnalyticsEvent.ConfirmReturnUrlNull
}
else -> {
PaymentAnalyticsEvent.ConfirmReturnUrlCustom
}
}.let { event ->
analyticsRequestExecutor.executeAsync(
paymentAnalyticsRequestFactory.createRequest(event)
)
}
}
internal companion object {
internal const val PAYMENT_REQUEST_CODE = 50000
internal const val SETUP_REQUEST_CODE = 50001
internal const val SOURCE_REQUEST_CODE = 50002
/**
* Get the appropriate request code for the given stripe intent type
*
* @param intent the [StripeIntent] to get the request code for
* @return PAYMENT_REQUEST_CODE or SETUP_REQUEST_CODE
*/
@JvmSynthetic
internal fun getRequestCode(intent: StripeIntent): Int {
return if (intent is PaymentIntent) {
PAYMENT_REQUEST_CODE
} else {
SETUP_REQUEST_CODE
}
}
/**
* Get the appropriate request code for the given stripe intent params type
*
* @param params the [ConfirmStripeIntentParams] to get the request code for
* @return PAYMENT_REQUEST_CODE or SETUP_REQUEST_CODE
*/
@JvmSynthetic
internal fun getRequestCode(params: ConfirmStripeIntentParams): Int {
return when (params) {
is ConfirmPaymentIntentParams -> PAYMENT_REQUEST_CODE
is ConfirmSetupIntentParams -> SETUP_REQUEST_CODE
}
}
@JvmStatic
@JvmOverloads
fun create(
context: Context,
publishableKey: String,
stripeRepository: StripeRepository,
enableLogging: Boolean = false
): PaymentController {
return StripePaymentController(
context.applicationContext,
{ publishableKey },
stripeRepository,
enableLogging
)
}
internal val EXPAND_PAYMENT_METHOD = listOf("payment_method")
internal val CHALLENGE_DELAY = TimeUnit.SECONDS.toMillis(2L)
private const val REQUIRED_ERROR = "API request returned an invalid response."
}
}