-
Notifications
You must be signed in to change notification settings - Fork 66
/
DropInActivity.kt
745 lines (648 loc) · 29.7 KB
/
DropInActivity.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
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
/*
* Copyright (c) 2019 Adyen N.V.
*
* This file is open source and available under the MIT license. See the LICENSE file for more info.
*
* Created by caiof on 9/4/2019.
*/
package com.adyen.checkout.dropin.ui
import android.app.Activity
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import androidx.activity.viewModels
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.adyen.checkout.bacs.BacsDirectDebitComponent
import com.adyen.checkout.card.CardComponent
import com.adyen.checkout.components.ActionComponentData
import com.adyen.checkout.components.PaymentComponentState
import com.adyen.checkout.components.analytics.AnalyticEvent
import com.adyen.checkout.components.analytics.AnalyticsDispatcher
import com.adyen.checkout.components.extensions.createLocalizedContext
import com.adyen.checkout.components.model.PaymentMethodsApiResponse
import com.adyen.checkout.components.model.paymentmethods.PaymentMethod
import com.adyen.checkout.components.model.paymentmethods.StoredPaymentMethod
import com.adyen.checkout.components.model.payments.request.OrderRequest
import com.adyen.checkout.components.model.payments.response.Action
import com.adyen.checkout.components.model.payments.response.BalanceResult
import com.adyen.checkout.components.model.payments.response.OrderResponse
import com.adyen.checkout.core.log.LogUtil
import com.adyen.checkout.core.log.Logger
import com.adyen.checkout.dropin.ActionHandler
import com.adyen.checkout.dropin.DropIn
import com.adyen.checkout.dropin.DropInConfiguration
import com.adyen.checkout.dropin.DropInPrefs
import com.adyen.checkout.dropin.R
import com.adyen.checkout.dropin.service.BalanceDropInServiceResult
import com.adyen.checkout.dropin.service.BaseDropInServiceResult
import com.adyen.checkout.dropin.service.DropInService
import com.adyen.checkout.dropin.service.DropInServiceInterface
import com.adyen.checkout.dropin.service.DropInServiceResult
import com.adyen.checkout.dropin.service.DropInServiceResultError
import com.adyen.checkout.dropin.service.OrderDropInServiceResult
import com.adyen.checkout.dropin.service.RecurringDropInServiceResult
import com.adyen.checkout.dropin.service.SessionDropInServiceInterface
import com.adyen.checkout.dropin.service.SessionDropInServiceResult
import com.adyen.checkout.dropin.ui.action.ActionComponentDialogFragment
import com.adyen.checkout.dropin.ui.base.DropInBottomSheetDialogFragment
import com.adyen.checkout.dropin.ui.component.BacsDirectDebitDialogFragment
import com.adyen.checkout.dropin.ui.component.CardComponentDialogFragment
import com.adyen.checkout.dropin.ui.component.GenericComponentDialogFragment
import com.adyen.checkout.dropin.ui.component.GiftCardComponentDialogFragment
import com.adyen.checkout.dropin.ui.component.GooglePayComponentDialogFragment
import com.adyen.checkout.dropin.ui.giftcard.GiftCardBalanceResult
import com.adyen.checkout.dropin.ui.giftcard.GiftCardPaymentConfirmationData
import com.adyen.checkout.dropin.ui.giftcard.GiftCardPaymentConfirmationDialogFragment
import com.adyen.checkout.dropin.ui.paymentmethods.PaymentMethodListDialogFragment
import com.adyen.checkout.dropin.ui.stored.PreselectedStoredPaymentMethodFragment
import com.adyen.checkout.dropin.ui.viewmodel.DropInActivityEvent
import com.adyen.checkout.dropin.ui.viewmodel.DropInDestination
import com.adyen.checkout.dropin.ui.viewmodel.DropInViewModel
import com.adyen.checkout.dropin.ui.viewmodel.DropInViewModelFactory
import com.adyen.checkout.giftcard.GiftCardComponent
import com.adyen.checkout.giftcard.GiftCardComponentState
import com.adyen.checkout.googlepay.GooglePayComponent
import com.adyen.checkout.redirect.RedirectUtil
import com.adyen.checkout.sessions.model.Session
import com.adyen.checkout.wechatpay.WeChatPayUtils
import kotlinx.coroutines.launch
private val TAG = LogUtil.getTag()
private const val PRESELECTED_PAYMENT_METHOD_FRAGMENT_TAG = "PRESELECTED_PAYMENT_METHOD_FRAGMENT"
private const val PAYMENT_METHODS_LIST_FRAGMENT_TAG = "PAYMENT_METHODS_LIST_FRAGMENT"
private const val COMPONENT_FRAGMENT_TAG = "COMPONENT_DIALOG_FRAGMENT"
private const val ACTION_FRAGMENT_TAG = "ACTION_DIALOG_FRAGMENT"
private const val LOADING_FRAGMENT_TAG = "LOADING_DIALOG_FRAGMENT"
private const val GIFT_CARD_PAYMENT_CONFIRMATION_FRAGMENT_TAG = "GIFT_CARD_PAYMENT_CONFIRMATION_FRAGMENT"
internal const val GOOGLE_PAY_REQUEST_CODE = 1
/**
* Activity that presents the available PaymentMethods to the Shopper.
*/
@Suppress("TooManyFunctions")
class DropInActivity :
AppCompatActivity(),
DropInBottomSheetDialogFragment.Protocol,
ActionHandler.ActionHandlingInterface {
private val dropInViewModel: DropInViewModel by viewModels { DropInViewModelFactory(this) }
private lateinit var actionHandler: ActionHandler
private val loadingDialog = LoadingDialogFragment.newInstance()
private var dropInService: DropInServiceInterface? = null
private var serviceBound: Boolean = false
// these queues exist for when a call is requested before the service is bound
private var paymentDataQueue: PaymentComponentState<*>? = null
private var actionDataQueue: ActionComponentData? = null
private var balanceDataQueue: GiftCardComponentState? = null
private var orderDataQueue: Unit? = null
private var orderCancellationQueue: OrderRequest? = null
private val serviceConnection = object : ServiceConnection {
override fun onServiceConnected(className: ComponentName, binder: IBinder) {
Logger.d(TAG, "onServiceConnected")
val dropInBinder = binder as? DropInService.DropInBinder ?: return
dropInService = dropInBinder.getService()
dropInViewModel.onDropInServiceConnected()
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
dropInService?.observeResult {
handleDropInServiceResult(it)
}
}
}
paymentDataQueue?.let {
Logger.d(TAG, "Sending queued payment request")
requestPaymentsCall(it)
paymentDataQueue = null
}
actionDataQueue?.let {
Logger.d(TAG, "Sending queued action request")
requestDetailsCall(it)
actionDataQueue = null
}
balanceDataQueue?.let {
Logger.d(TAG, "Sending queued action request")
requestBalanceCall(it)
balanceDataQueue = null
}
orderDataQueue?.let {
Logger.d(TAG, "Sending queued order request")
requestOrdersCall()
orderDataQueue = null
}
orderCancellationQueue?.let {
Logger.d(TAG, "Sending queued cancel order request")
requestCancelOrderCall(it, true)
orderCancellationQueue = null
}
}
override fun onServiceDisconnected(className: ComponentName) {
Logger.d(TAG, "onServiceDisconnected")
dropInService = null
}
}
override fun attachBaseContext(newBase: Context?) {
Logger.d(TAG, "attachBaseContext")
super.attachBaseContext(createLocalizedContext(newBase))
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Logger.d(TAG, "onCreate - $savedInstanceState")
setContentView(R.layout.activity_drop_in)
overridePendingTransition(0, 0)
val bundle = savedInstanceState ?: intent.extras
val initializationSuccessful = assertBundleExists(bundle)
if (!initializationSuccessful) {
terminateWithError("Initialization failed")
return
}
if (noDialogPresent()) {
dropInViewModel.onCreated()
}
actionHandler = ActionHandler(this, dropInViewModel.dropInConfiguration)
actionHandler.restoreState(this, savedInstanceState)
handleIntent(intent)
sendAnalyticsEvent()
initObservers()
startDropInService()
}
private fun noDialogPresent(): Boolean {
return getFragmentByTag(PRESELECTED_PAYMENT_METHOD_FRAGMENT_TAG) == null &&
getFragmentByTag(PAYMENT_METHODS_LIST_FRAGMENT_TAG) == null &&
getFragmentByTag(COMPONENT_FRAGMENT_TAG) == null &&
getFragmentByTag(ACTION_FRAGMENT_TAG) == null &&
getFragmentByTag(GIFT_CARD_PAYMENT_CONFIRMATION_FRAGMENT_TAG) == null
}
private fun createLocalizedContext(baseContext: Context?): Context? {
if (baseContext == null) return baseContext
// We need to get the Locale from sharedPrefs because attachBaseContext is called before onCreate, so we don't have the Config object yet.
val locale = DropInPrefs.getShopperLocale(baseContext)
return baseContext.createLocalizedContext(locale)
}
private fun assertBundleExists(bundle: Bundle?): Boolean {
if (bundle == null) {
Logger.e(TAG, "Failed to initialize - bundle is null")
return false
}
return true
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
checkGooglePayActivityResult(requestCode, resultCode, data)
}
private fun checkGooglePayActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode != GOOGLE_PAY_REQUEST_CODE) return
val fragment = getFragmentByTag(COMPONENT_FRAGMENT_TAG) as? GooglePayComponentDialogFragment
if (fragment == null) {
Logger.e(TAG, "GooglePayComponentDialogFragment is not loaded")
return
}
fragment.handleActivityResult(resultCode, data)
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
Logger.d(TAG, "onNewIntent")
if (intent != null) {
handleIntent(intent)
} else {
Logger.e(TAG, "Null intent")
}
}
override fun onStart() {
Logger.v(TAG, "onStart")
super.onStart()
}
private fun startDropInService() {
val bound = DropInService.startService(
context = this,
connection = serviceConnection,
merchantService = dropInViewModel.serviceComponentName,
additionalData = dropInViewModel.dropInConfiguration.additionalDataForDropInService,
)
if (bound) {
serviceBound = true
} else {
Logger.e(
TAG,
"Error binding to ${dropInViewModel.serviceComponentName.className}. " +
"The system couldn't find the service or your client doesn't have permission to bind to it"
)
}
}
override fun onStop() {
Logger.v(TAG, "onStop")
super.onStop()
}
private fun stopDropInService() {
if (serviceBound) {
DropInService.stopService(
context = this,
merchantService = dropInViewModel.serviceComponentName,
connection = serviceConnection,
)
serviceBound = false
}
}
override fun requestPaymentsCall(paymentComponentState: PaymentComponentState<*>) {
Logger.d(TAG, "requestPaymentsCall")
if (dropInService == null) {
Logger.e(TAG, "service is disconnected, adding to queue")
paymentDataQueue = paymentComponentState
return
}
dropInViewModel.isWaitingResult = true
setLoading(true)
dropInViewModel.updatePaymentComponentStateForPaymentsCall(paymentComponentState)
dropInService?.requestPaymentsCall(paymentComponentState)
}
override fun requestDetailsCall(actionComponentData: ActionComponentData) {
Logger.d(TAG, "requestDetailsCall")
if (dropInService == null) {
Logger.e(TAG, "service is disconnected, adding to queue")
actionDataQueue = actionComponentData
return
}
dropInViewModel.isWaitingResult = true
setLoading(true)
dropInService?.requestDetailsCall(actionComponentData)
}
override fun showError(errorMessage: String, reason: String, terminate: Boolean) {
Logger.d(TAG, "showError - message: $errorMessage")
AlertDialog.Builder(this)
.setTitle(R.string.error_dialog_title)
.setMessage(errorMessage)
.setOnDismissListener { this@DropInActivity.errorDialogDismissed(reason, terminate) }
.setPositiveButton(R.string.error_dialog_button) { dialog, _ -> dialog.dismiss() }
.show()
}
private fun errorDialogDismissed(reason: String, terminateDropIn: Boolean) {
if (terminateDropIn) {
terminateWithError(reason)
} else {
setLoading(false)
}
}
override fun displayAction(action: Action) {
Logger.d(TAG, "showActionDialog")
setLoading(false)
hideAllScreens()
val actionFragment = ActionComponentDialogFragment.newInstance(action)
actionFragment.show(supportFragmentManager, ACTION_FRAGMENT_TAG)
actionFragment.setToHandleWhenStarting()
}
override fun onActionError(errorMessage: String) {
showError(getString(R.string.action_failed), errorMessage, true)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
Logger.d(TAG, "onSaveInstanceState")
actionHandler.saveState(outState)
}
override fun onResume() {
Logger.v(TAG, "onResume")
super.onResume()
setLoading(dropInViewModel.isWaitingResult)
}
override fun onDestroy() {
Logger.v(TAG, "onDestroy")
super.onDestroy()
}
override fun showPreselectedDialog() {
Logger.d(TAG, "showPreselectedDialog")
hideAllScreens()
PreselectedStoredPaymentMethodFragment.newInstance(dropInViewModel.getPreselectedStoredPaymentMethod())
.show(supportFragmentManager, PRESELECTED_PAYMENT_METHOD_FRAGMENT_TAG)
}
override fun showPaymentMethodsDialog() {
Logger.d(TAG, "showPaymentMethodsDialog")
hideAllScreens()
PaymentMethodListDialogFragment().show(supportFragmentManager, PAYMENT_METHODS_LIST_FRAGMENT_TAG)
}
override fun showStoredComponentDialog(storedPaymentMethod: StoredPaymentMethod, fromPreselected: Boolean) {
Logger.d(TAG, "showStoredComponentDialog")
hideAllScreens()
val dialogFragment = when {
CardComponent.PAYMENT_METHOD_TYPES.contains(storedPaymentMethod.type) -> CardComponentDialogFragment
else -> GenericComponentDialogFragment
}.newInstance(storedPaymentMethod, fromPreselected)
dialogFragment.show(supportFragmentManager, COMPONENT_FRAGMENT_TAG)
}
override fun showComponentDialog(paymentMethod: PaymentMethod) {
Logger.d(TAG, "showComponentDialog")
hideAllScreens()
val dialogFragment = when {
CardComponent.PAYMENT_METHOD_TYPES.contains(paymentMethod.type) ->
CardComponentDialogFragment.newInstance(paymentMethod)
BacsDirectDebitComponent.PAYMENT_METHOD_TYPES.contains(paymentMethod.type) ->
BacsDirectDebitDialogFragment.newInstance(paymentMethod)
GiftCardComponent.PAYMENT_METHOD_TYPES.contains(paymentMethod.type) ->
GiftCardComponentDialogFragment.newInstance(paymentMethod)
GooglePayComponent.PAYMENT_METHOD_TYPES.contains(paymentMethod.type) ->
GooglePayComponentDialogFragment.newInstance(paymentMethod)
else -> GenericComponentDialogFragment.newInstance(paymentMethod)
}
dialogFragment.show(supportFragmentManager, COMPONENT_FRAGMENT_TAG)
}
private fun hideAllScreens() {
hideFragmentDialog(PRESELECTED_PAYMENT_METHOD_FRAGMENT_TAG)
hideFragmentDialog(PAYMENT_METHODS_LIST_FRAGMENT_TAG)
hideFragmentDialog(COMPONENT_FRAGMENT_TAG)
hideFragmentDialog(ACTION_FRAGMENT_TAG)
hideFragmentDialog(GIFT_CARD_PAYMENT_CONFIRMATION_FRAGMENT_TAG)
}
override fun terminateDropIn() {
Logger.d(TAG, "terminateDropIn")
dropInViewModel.cancelDropIn()
}
override fun requestBalanceCall(giftCardComponentState: GiftCardComponentState) {
Logger.d(TAG, "requestCheckBalanceCall")
val paymentMethod = dropInViewModel.onBalanceCallRequested(giftCardComponentState) ?: return
if (dropInService == null) {
Logger.e(TAG, "requestBalanceCall - service is disconnected")
balanceDataQueue = giftCardComponentState
return
}
dropInViewModel.isWaitingResult = true
setLoading(true)
dropInService?.requestBalanceCall(paymentMethod)
}
private fun requestOrdersCall() {
Logger.d(TAG, "requestOrdersCall")
if (dropInService == null) {
Logger.e(TAG, "requestOrdersCall - service is disconnected")
orderDataQueue = Unit
return
}
dropInViewModel.isWaitingResult = true
setLoading(true)
dropInService?.requestOrdersCall()
}
private fun requestCancelOrderCall(order: OrderRequest, isDropInCancelledByUser: Boolean) {
Logger.d(TAG, "requestCancelOrderCall")
if (dropInService == null) {
Logger.e(TAG, "requestOrdersCall - service is disconnected")
orderCancellationQueue = order
return
}
dropInViewModel.isWaitingResult = true
setLoading(true)
dropInService?.requestCancelOrder(order, isDropInCancelledByUser)
}
override fun finishWithAction() {
Logger.d(TAG, "finishWithActionCall")
sendResult(DropIn.FINISHED_WITH_ACTION)
}
override fun removeStoredPaymentMethod(storedPaymentMethod: StoredPaymentMethod) {
dropInService?.requestRemoveStoredPaymentMethod(storedPaymentMethod)
setLoading(true)
}
private fun handleDropInServiceResult(dropInServiceResult: BaseDropInServiceResult) {
Logger.d(TAG, "handleDropInServiceResult - ${dropInServiceResult::class.simpleName}")
dropInViewModel.isWaitingResult = false
when (dropInServiceResult) {
is DropInServiceResult -> handleDropInServiceResult(dropInServiceResult)
is BalanceDropInServiceResult -> handleDropInServiceResult(dropInServiceResult)
is OrderDropInServiceResult -> handleDropInServiceResult(dropInServiceResult)
is RecurringDropInServiceResult -> handleDropInServiceResult(dropInServiceResult)
is SessionDropInServiceResult -> handleDropInServiceResult(dropInServiceResult)
}
}
private fun handleDropInServiceResult(dropInServiceResult: DropInServiceResult) {
when (dropInServiceResult) {
is DropInServiceResult.Finished -> sendResult(dropInServiceResult.result)
is DropInServiceResult.Action -> handleAction(dropInServiceResult.action)
is DropInServiceResult.Update -> handlePaymentMethodsUpdate(dropInServiceResult)
is DropInServiceResult.Error -> handleErrorDropInServiceResult(dropInServiceResult)
}
}
private fun handleDropInServiceResult(dropInServiceResult: BalanceDropInServiceResult) {
when (dropInServiceResult) {
is BalanceDropInServiceResult.Balance -> handleBalanceResult(dropInServiceResult.balance)
is BalanceDropInServiceResult.Error -> handleErrorDropInServiceResult(dropInServiceResult)
}
}
private fun handleDropInServiceResult(dropInServiceResult: OrderDropInServiceResult) {
when (dropInServiceResult) {
is OrderDropInServiceResult.OrderCreated -> handleOrderResult(dropInServiceResult.order)
is OrderDropInServiceResult.Error -> handleErrorDropInServiceResult(dropInServiceResult)
}
}
private fun handleDropInServiceResult(dropInServiceResult: RecurringDropInServiceResult) {
when (dropInServiceResult) {
is RecurringDropInServiceResult.PaymentMethodRemoved ->
handleRemovePaymentMethodResult(dropInServiceResult.id)
is RecurringDropInServiceResult.Error -> handleErrorDropInServiceResult(dropInServiceResult)
}
}
private fun handleDropInServiceResult(dropInServiceResult: SessionDropInServiceResult) {
when (dropInServiceResult) {
is SessionDropInServiceResult.SetupDone ->
dropInViewModel.onSessionSetupSuccessful(dropInServiceResult.paymentMethods)
is SessionDropInServiceResult.SessionDataChanged ->
dropInViewModel.onSessionDataChanged(dropInServiceResult.sessionData)
is SessionDropInServiceResult.SessionTakenOverUpdated ->
dropInViewModel.onSessionTakenOverUpdated(dropInServiceResult.isFlowTakenOver)
is SessionDropInServiceResult.Error -> handleErrorDropInServiceResult(dropInServiceResult)
}
}
private fun handleErrorDropInServiceResult(dropInServiceResult: DropInServiceResultError) {
Logger.d(TAG, "handleDropInServiceResult ERROR - reason: ${dropInServiceResult.reason}")
val reason = dropInServiceResult.reason ?: "Unspecified reason"
val errorMessage = dropInServiceResult.errorMessage ?: getString(R.string.payment_failed)
showError(errorMessage, reason, dropInServiceResult.dismissDropIn)
}
private fun handleAction(action: Action) {
actionHandler.handleAction(this, action, ::sendResult)
}
private fun handlePaymentMethodsUpdate(dropInServiceResult: DropInServiceResult.Update) {
dropInViewModel.handlePaymentMethodsUpdate(
dropInServiceResult.paymentMethodsApiResponse,
dropInServiceResult.order
)
}
private fun sendResult(content: String) {
val resultIntent = Intent().putExtra(DropIn.RESULT_KEY, content)
setResult(Activity.RESULT_OK, resultIntent)
terminateSuccessfully()
}
private fun terminateSuccessfully() {
Logger.d(TAG, "terminateSuccessfully")
terminate()
}
private fun terminateWithError(reason: String) {
Logger.d(TAG, "terminateWithError")
val resultIntent = Intent().putExtra(DropIn.ERROR_REASON_KEY, reason)
setResult(Activity.RESULT_CANCELED, resultIntent)
terminate()
}
private fun terminate() {
Logger.d(TAG, "terminate")
stopDropInService()
finish()
overridePendingTransition(0, R.anim.fade_out)
}
private fun handleIntent(intent: Intent) {
Logger.d(TAG, "handleIntent: action - ${intent.action}")
dropInViewModel.isWaitingResult = false
if (WeChatPayUtils.isResultIntent(intent)) {
Logger.d(TAG, "isResultIntent")
actionHandler.handleWeChatPayResponse(intent)
}
when (intent.action) {
// Redirect response
Intent.ACTION_VIEW -> {
val data = intent.data
if (data != null && data.toString().startsWith(RedirectUtil.REDIRECT_RESULT_SCHEME)) {
actionHandler.handleRedirectResponse(intent)
} else {
Logger.e(TAG, "Unexpected response from ACTION_VIEW - ${intent.data}")
}
}
else -> {
Logger.e(TAG, "Unable to find action")
}
}
}
private fun sendAnalyticsEvent() {
Logger.d(TAG, "sendAnalyticsEvent")
val analyticEvent = AnalyticEvent.create(
this,
AnalyticEvent.Flavor.DROPIN,
"dropin",
dropInViewModel.dropInConfiguration.shopperLocale
)
AnalyticsDispatcher.dispatchEvent(this, dropInViewModel.dropInConfiguration.environment, analyticEvent)
}
private fun initObservers() {
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
dropInViewModel.eventsFlow.collect { handleEvent(it) }
}
}
}
private fun handleEvent(event: DropInActivityEvent) {
when (event) {
is DropInActivityEvent.MakePartialPayment -> requestPaymentsCall(event.paymentComponentState)
is DropInActivityEvent.ShowPaymentMethods -> {
setLoading(false)
showPaymentMethodsDialog()
}
is DropInActivityEvent.CancelOrder -> requestCancelOrderCall(event.order, event.isDropInCancelledByUser)
is DropInActivityEvent.CancelDropIn -> terminateWithError(DropIn.ERROR_REASON_USER_CANCELED)
is DropInActivityEvent.NavigateTo -> loadFragment(event.destination)
is DropInActivityEvent.SessionServiceConnected -> onSessionServiceConnected(event)
}
}
private fun onSessionServiceConnected(event: DropInActivityEvent.SessionServiceConnected) {
(dropInService as? SessionDropInServiceInterface)?.initialize(
session = event.session,
clientKey = event.clientKey,
baseUrl = event.baseUrl,
shouldFetchPaymentMethods = event.shouldFetchPaymentMethods,
isFlowTakenOver = event.isFlowTakenOver,
)
}
private fun loadFragment(destination: DropInDestination) {
when (destination) {
is DropInDestination.ActionComponent -> displayAction(destination.action)
is DropInDestination.GiftCardPaymentConfirmation -> showGiftCardPaymentConfirmationDialog(destination.data)
is DropInDestination.PaymentComponent -> showComponentDialog(destination.paymentMethod)
is DropInDestination.PaymentMethods -> showPaymentMethodsDialog()
is DropInDestination.PreselectedStored -> showPreselectedDialog()
}
}
private fun hideFragmentDialog(tag: String) {
getFragmentByTag(tag)?.dismiss()
}
private fun getFragmentByTag(tag: String): DialogFragment? {
val fragment = supportFragmentManager.findFragmentByTag(tag)
return fragment as DialogFragment?
}
private fun setLoading(showLoading: Boolean) {
if (showLoading) {
if (!loadingDialog.isAdded) {
loadingDialog.show(supportFragmentManager, LOADING_FRAGMENT_TAG)
}
} else {
getFragmentByTag(LOADING_FRAGMENT_TAG)?.dismiss()
}
}
private fun handleBalanceResult(balanceResult: BalanceResult) {
Logger.v(TAG, "handleBalanceResult")
val result = dropInViewModel.handleBalanceResult(balanceResult)
Logger.d(TAG, "handleBalanceResult: ${result::class.java.simpleName}")
when (result) {
is GiftCardBalanceResult.Error -> showError(
getString(result.errorMessage),
result.reason,
result.terminateDropIn
)
is GiftCardBalanceResult.FullPayment -> handleGiftCardFullPayment(result)
is GiftCardBalanceResult.RequestOrderCreation -> requestOrdersCall()
is GiftCardBalanceResult.RequestPartialPayment -> requestPartialPayment()
}
}
private fun handleGiftCardFullPayment(fullPayment: GiftCardBalanceResult.FullPayment) {
Logger.d(TAG, "handleGiftCardFullPayment")
setLoading(false)
showGiftCardPaymentConfirmationDialog(fullPayment.data)
}
private fun showGiftCardPaymentConfirmationDialog(data: GiftCardPaymentConfirmationData) {
Logger.d(TAG, "showGiftCardPaymentConfirmationDialog")
hideAllScreens()
GiftCardPaymentConfirmationDialogFragment.newInstance(data)
.show(supportFragmentManager, GIFT_CARD_PAYMENT_CONFIRMATION_FRAGMENT_TAG)
}
private fun handleOrderResult(order: OrderResponse) {
Logger.v(TAG, "handleOrderResult")
dropInViewModel.handleOrderCreated(order)
}
override fun requestPartialPayment() {
dropInViewModel.partialPaymentRequested()
}
override fun requestOrderCancellation() {
dropInViewModel.orderCancellationRequested()
}
private fun handleRemovePaymentMethodResult(id: String) {
setLoading(false)
dropInViewModel.removeStoredPaymentMethodWithId(id)
val preselectedStoredPaymentMethodFragment =
getFragmentByTag(PRESELECTED_PAYMENT_METHOD_FRAGMENT_TAG) as? PreselectedStoredPaymentMethodFragment
if (preselectedStoredPaymentMethodFragment != null) {
showPaymentMethodsDialog()
return
}
val paymentMethodListDialogFragment =
getFragmentByTag(PAYMENT_METHODS_LIST_FRAGMENT_TAG) as? PaymentMethodListDialogFragment
if (paymentMethodListDialogFragment != null) {
paymentMethodListDialogFragment.removeStoredPaymentMethod(id)
return
}
}
companion object {
fun createIntent(
context: Context,
dropInConfiguration: DropInConfiguration,
paymentMethodsApiResponse: PaymentMethodsApiResponse,
service: ComponentName,
): Intent {
val intent = Intent(context, DropInActivity::class.java)
DropInViewModel.putIntentExtras(intent, dropInConfiguration, paymentMethodsApiResponse, service)
return intent
}
fun createIntent(
context: Context,
dropInConfiguration: DropInConfiguration,
session: Session,
service: ComponentName,
): Intent {
val intent = Intent(context, DropInActivity::class.java)
DropInViewModel.putIntentExtras(intent, dropInConfiguration, session, service)
return intent
}
}
}