-
Notifications
You must be signed in to change notification settings - Fork 629
/
PaymentFlowResultProcessor.kt
355 lines (329 loc) · 12.6 KB
/
PaymentFlowResultProcessor.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
package com.stripe.android.payments
import android.content.Context
import com.stripe.android.PaymentController
import com.stripe.android.PaymentIntentResult
import com.stripe.android.SetupIntentResult
import com.stripe.android.StripeIntentResult
import com.stripe.android.StripeIntentResult.Outcome.Companion.CANCELED
import com.stripe.android.StripeIntentResult.Outcome.Companion.SUCCEEDED
import com.stripe.android.core.Logger
import com.stripe.android.core.exception.InvalidRequestException
import com.stripe.android.core.exception.MaxRetryReachedException
import com.stripe.android.core.injection.IOContext
import com.stripe.android.core.injection.PUBLISHABLE_KEY
import com.stripe.android.core.networking.ApiRequest
import com.stripe.android.core.networking.RetryDelaySupplier
import com.stripe.android.model.PaymentIntent
import com.stripe.android.model.PaymentMethod
import com.stripe.android.model.SetupIntent
import com.stripe.android.model.StripeIntent
import com.stripe.android.model.shouldRefresh
import com.stripe.android.networking.StripeRepository
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject
import javax.inject.Named
import javax.inject.Provider
import javax.inject.Singleton
import kotlin.coroutines.CoroutineContext
/**
* Class responsible for processing the result of a [PaymentController] confirm operation.
*/
internal sealed class PaymentFlowResultProcessor<T : StripeIntent, out S : StripeIntentResult<T>>(
context: Context,
private val publishableKeyProvider: Provider<String>,
protected val stripeRepository: StripeRepository,
private val logger: Logger,
private val workContext: CoroutineContext,
private val retryDelaySupplier: RetryDelaySupplier = RetryDelaySupplier()
) {
private val failureMessageFactory = PaymentFlowFailureMessageFactory(context)
suspend fun processResult(
unvalidatedResult: PaymentFlowResult.Unvalidated
): S = withContext(workContext) {
val result = unvalidatedResult.validate()
val requestOptions = ApiRequest.Options(
apiKey = publishableKeyProvider.get(),
stripeAccount = result.stripeAccountId
)
requireNotNull(
retrieveStripeIntent(
result.clientSecret,
requestOptions,
expandFields = EXPAND_PAYMENT_METHOD
)
).let { stripeIntent ->
when {
stripeIntent.status == StripeIntent.Status.Succeeded -> {
createStripeIntentResult(
stripeIntent,
SUCCEEDED,
failureMessageFactory.create(stripeIntent, result.flowOutcome)
)
}
shouldRefreshIntent(stripeIntent, result.flowOutcome) -> {
val intent = refreshStripeIntentUntilTerminalState(
result.clientSecret,
requestOptions
)
val flowOutcome = if (intent.status == StripeIntent.Status.Succeeded) {
SUCCEEDED
} else {
result.flowOutcome
}
createStripeIntentResult(
intent,
flowOutcome,
failureMessageFactory.create(intent, result.flowOutcome)
)
}
shouldCancelIntentSource(stripeIntent, result.canCancelSource) -> {
val sourceId = result.sourceId.orEmpty()
logger.debug(
"Canceling source '$sourceId' for '${stripeIntent.javaClass.simpleName}'"
)
val intent = requireNotNull(
cancelStripeIntentSource(
stripeIntent,
requestOptions,
sourceId,
)
)
createStripeIntentResult(
intent,
result.flowOutcome,
failureMessageFactory.create(intent, result.flowOutcome)
)
}
else -> {
createStripeIntentResult(
stripeIntent,
result.flowOutcome,
failureMessageFactory.create(stripeIntent, result.flowOutcome)
)
}
}
}
}
private fun shouldCancelIntentSource(
stripeIntent: StripeIntent,
shouldCancelSource: Boolean
): Boolean {
// It is very important to check `requiresAction()` because we can't always tell what
// action the customer took during payment authentication (e.g. when using Custom Tabs).
// We don't want to cancel if required actions have been resolved and the payment is ready
// for capture.
return shouldCancelSource && stripeIntent.requiresAction()
}
private fun shouldRefreshIntent(
stripeIntent: StripeIntent,
@StripeIntentResult.Outcome flowOutcome: Int
): Boolean {
// For some payment methods, after user confirmation(resulting in flowOutCome == SUCCEEDED),
// there is a delay when Stripe backend transfers its state out of "requires_action".
// For a PaymentIntent with such payment method, we will need to poll the refresh endpoint
// until the PaymentIntent reaches a deterministic state.
val succeededMaybeRefresh = flowOutcome == SUCCEEDED && stripeIntent.shouldRefresh()
// For 3DS flow, if the transaction is still unexpectedly processing, refresh the
// PaymentIntent. This could happen if, for example, a payment is approved in a WebView,
// user closes the sheet, and the approval races with this fetch
val cancelledMaybeRefresh = flowOutcome == CANCELED &&
stripeIntent.status == StripeIntent.Status.Processing &&
stripeIntent.paymentMethod?.type == PaymentMethod.Type.Card
return succeededMaybeRefresh || cancelledMaybeRefresh
}
protected abstract suspend fun retrieveStripeIntent(
clientSecret: String,
requestOptions: ApiRequest.Options,
expandFields: List<String>
): T?
protected abstract suspend fun refreshStripeIntent(
clientSecret: String,
requestOptions: ApiRequest.Options,
expandFields: List<String>
): T?
/**
* Keeps polling refresh endpoint for this [StripeIntent] until its status is no longer
* "requires_action".
*
* @param clientSecret for the intent
* @param requestOptions options for [ApiRequest]
*
* @return a [StripeIntent] object with a deterministic state.
*
* @throws MaxRetryReachedException when max retry is reached and the status is still
* "requires_action".
*/
@Throws(
MaxRetryReachedException::class,
InvalidRequestException::class
)
private suspend fun refreshStripeIntentUntilTerminalState(
clientSecret: String,
requestOptions: ApiRequest.Options,
): T {
var remainingRetries = MAX_RETRIES
var stripeIntent = requireNotNull(
refreshStripeIntent(
clientSecret = clientSecret,
requestOptions = requestOptions,
expandFields = listOf()
)
)
while (shouldRetry(stripeIntent) && remainingRetries > 1) {
val delayMs = retryDelaySupplier.getDelayMillis(
MAX_RETRIES,
remainingRetries
)
CoroutineScope(workContext).launch {
delay(delayMs)
}
stripeIntent = requireNotNull(
refreshStripeIntent(
clientSecret = clientSecret,
requestOptions = requestOptions,
expandFields = listOf()
)
)
remainingRetries--
}
if (shouldRetry(stripeIntent)) {
throw MaxRetryReachedException()
} else {
return stripeIntent
}
}
/**
* Cancels the source of this intent so that the payment method attached to it is cleared,
* transferring the intent's status from requires_action to requires_payment_method.
*/
protected abstract suspend fun cancelStripeIntentSource(
stripeIntent: T,
requestOptions: ApiRequest.Options,
sourceId: String
): T?
protected abstract fun createStripeIntentResult(
stripeIntent: T,
@StripeIntentResult.Outcome outcomeFromFlow: Int,
failureMessage: String?
): S
private fun shouldRetry(stripeIntent: StripeIntent): Boolean {
val requiresAction = stripeIntent.requiresAction()
val isCardPaymentProcessing = stripeIntent.status == StripeIntent.Status.Processing &&
stripeIntent.paymentMethod?.type == PaymentMethod.Type.Card
return requiresAction || isCardPaymentProcessing
}
internal companion object {
val EXPAND_PAYMENT_METHOD = listOf("payment_method")
const val MAX_RETRIES = 3
}
}
/**
* Processes the result of a [PaymentIntent] confirmation.
*/
@Singleton
internal class PaymentIntentFlowResultProcessor @Inject constructor(
context: Context,
@Named(PUBLISHABLE_KEY) publishableKeyProvider: () -> String,
stripeRepository: StripeRepository,
logger: Logger,
@IOContext workContext: CoroutineContext
) : PaymentFlowResultProcessor<PaymentIntent, PaymentIntentResult>(
context, publishableKeyProvider, stripeRepository, logger, workContext
) {
override suspend fun retrieveStripeIntent(
clientSecret: String,
requestOptions: ApiRequest.Options,
expandFields: List<String>
): PaymentIntent? =
stripeRepository.retrievePaymentIntent(
clientSecret,
requestOptions,
expandFields
)
override suspend fun refreshStripeIntent(
clientSecret: String,
requestOptions: ApiRequest.Options,
expandFields: List<String>
): PaymentIntent? =
stripeRepository.refreshPaymentIntent(
clientSecret,
requestOptions
)
override suspend fun cancelStripeIntentSource(
stripeIntent: PaymentIntent,
requestOptions: ApiRequest.Options,
sourceId: String
): PaymentIntent? =
stripeRepository.cancelPaymentIntentSource(
stripeIntent.id.orEmpty(),
sourceId,
requestOptions,
)
override fun createStripeIntentResult(
stripeIntent: PaymentIntent,
outcomeFromFlow: Int,
failureMessage: String?
): PaymentIntentResult =
PaymentIntentResult(
stripeIntent,
outcomeFromFlow,
failureMessage
)
}
/**
* Processes the result of a [SetupIntent] confirmation.
*/
@Singleton
internal class SetupIntentFlowResultProcessor @Inject constructor(
context: Context,
@Named(PUBLISHABLE_KEY) publishableKeyProvider: () -> String,
stripeRepository: StripeRepository,
logger: Logger,
@IOContext workContext: CoroutineContext
) : PaymentFlowResultProcessor<SetupIntent, SetupIntentResult>(
context, publishableKeyProvider, stripeRepository, logger, workContext
) {
override suspend fun retrieveStripeIntent(
clientSecret: String,
requestOptions: ApiRequest.Options,
expandFields: List<String>
): SetupIntent? =
stripeRepository.retrieveSetupIntent(
clientSecret,
requestOptions,
expandFields
)
override suspend fun refreshStripeIntent(
clientSecret: String,
requestOptions: ApiRequest.Options,
expandFields: List<String>
): SetupIntent? =
stripeRepository.retrieveSetupIntent(
clientSecret,
requestOptions,
expandFields
)
override suspend fun cancelStripeIntentSource(
stripeIntent: SetupIntent,
requestOptions: ApiRequest.Options,
sourceId: String
): SetupIntent? =
stripeRepository.cancelSetupIntentSource(
stripeIntent.id.orEmpty(),
sourceId,
requestOptions,
)
override fun createStripeIntentResult(
stripeIntent: SetupIntent,
outcomeFromFlow: Int,
failureMessage: String?
): SetupIntentResult =
SetupIntentResult(
stripeIntent,
outcomeFromFlow,
failureMessage
)
}