forked from stripe/stripe-react-native
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCardFieldView.kt
More file actions
531 lines (477 loc) · 16 KB
/
CardFieldView.kt
File metadata and controls
531 lines (477 loc) · 16 KB
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
package com.reactnativestripesdk
import android.annotation.SuppressLint
import android.content.res.ColorStateList
import android.graphics.Color
import android.os.Build
import android.text.Editable
import android.text.InputFilter
import android.text.TextWatcher
import android.util.Log
import android.widget.FrameLayout
import androidx.core.os.LocaleListCompat
import com.facebook.react.bridge.ReadableMap
import com.facebook.react.uimanager.PixelUtil
import com.facebook.react.uimanager.ThemedReactContext
import com.facebook.react.uimanager.UIManagerHelper
import com.facebook.react.views.text.ReactTypefaceUtils
import com.google.android.material.shape.CornerFamily
import com.google.android.material.shape.MaterialShapeDrawable
import com.google.android.material.shape.ShapeAppearanceModel
import com.reactnativestripesdk.utils.PostalCodeUtilities
import com.reactnativestripesdk.utils.getIntOr
import com.reactnativestripesdk.utils.getIntOrNull
import com.reactnativestripesdk.utils.getValOr
import com.reactnativestripesdk.utils.hideSoftKeyboard
import com.reactnativestripesdk.utils.mapCardBrand
import com.reactnativestripesdk.utils.mapToPreferredNetworks
import com.reactnativestripesdk.utils.showSoftKeyboard
import com.stripe.android.core.model.CountryCode
import com.stripe.android.core.model.CountryUtils
import com.stripe.android.databinding.StripeCardInputWidgetBinding
import com.stripe.android.model.Address
import com.stripe.android.model.PaymentMethodCreateParams
import com.stripe.android.view.CardInputListener
import com.stripe.android.view.CardInputWidget
import com.stripe.android.view.CardValidCallback
import com.stripe.android.view.StripeEditText
@SuppressLint("ViewConstructor")
class CardFieldView(
private val context: ThemedReactContext,
) : FrameLayout(context) {
private var mCardWidget: CardInputWidget = CardInputWidget(context)
private val cardInputWidgetBinding = StripeCardInputWidgetBinding.bind(mCardWidget)
val cardDetails: MutableMap<String, Any?> =
mutableMapOf(
"brand" to "",
"last4" to "",
"expiryMonth" to null,
"expiryYear" to null,
"postalCode" to "",
"validNumber" to "Unknown",
"validCVC" to "Unknown",
"validExpiryDate" to "Unknown",
)
var cardParams: PaymentMethodCreateParams.Card? = null
var cardAddress: Address? = null
private var dangerouslyGetFullCardDetails: Boolean = false
private var currentFocusedField: String? = null
private var isCardValid = false
init {
cardInputWidgetBinding.container.isFocusable = true
cardInputWidgetBinding.container.isFocusableInTouchMode = true
cardInputWidgetBinding.container.requestFocus()
addView(mCardWidget)
setListeners()
viewTreeObserver.addOnGlobalLayoutListener { requestLayout() }
}
fun setAutofocus(value: Boolean) {
if (value) {
cardInputWidgetBinding.cardNumberEditText.requestFocus()
cardInputWidgetBinding.cardNumberEditText.showSoftKeyboard()
}
}
fun requestFocusFromJS() {
cardInputWidgetBinding.cardNumberEditText.requestFocus()
cardInputWidgetBinding.cardNumberEditText.showSoftKeyboard()
}
fun requestBlurFromJS() {
cardInputWidgetBinding.cardNumberEditText.hideSoftKeyboard()
cardInputWidgetBinding.cardNumberEditText.clearFocus()
cardInputWidgetBinding.container.requestFocus()
}
fun requestClearFromJS() {
cardInputWidgetBinding.cardNumberEditText.setText("")
cardInputWidgetBinding.cvcEditText.setText("")
cardInputWidgetBinding.expiryDateEditText.setText("")
if (mCardWidget.postalCodeEnabled) {
cardInputWidgetBinding.postalCodeEditText.setText("")
}
}
private fun onChangeFocus() {
UIManagerHelper
.getEventDispatcherForReactTag(context, id)
?.dispatchEvent(CardFocusChangeEvent(context.surfaceId, id, currentFocusedField))
}
fun setCardStyle(value: ReadableMap?) {
val borderWidth = value.getIntOrNull("borderWidth")
val backgroundColor = getValOr(value, "backgroundColor", null)
val borderColor = getValOr(value, "borderColor", null)
val borderRadius = value.getIntOr("borderRadius", 0)
val textColor = getValOr(value, "textColor", null)
val fontSize = value.getIntOrNull("fontSize")
val fontFamily = getValOr(value, "fontFamily")
val placeholderColor = getValOr(value, "placeholderColor", null)
val textErrorColor = getValOr(value, "textErrorColor", null)
val cursorColor = getValOr(value, "cursorColor", null)
val bindings =
setOf(
cardInputWidgetBinding.cardNumberEditText,
cardInputWidgetBinding.cvcEditText,
cardInputWidgetBinding.expiryDateEditText,
cardInputWidgetBinding.postalCodeEditText,
)
textColor?.let {
for (editTextBinding in bindings) {
editTextBinding.setTextColor(Color.parseColor(it))
}
}
textErrorColor?.let {
for (editTextBinding in bindings) {
editTextBinding.setErrorColor(Color.parseColor(it))
}
}
placeholderColor?.let {
for (editTextBinding in bindings) {
editTextBinding.setHintTextColor(Color.parseColor(it))
}
setCardBrandTint(Color.parseColor(it))
}
fontSize?.let {
for (editTextBinding in bindings) {
editTextBinding.textSize = it.toFloat()
}
}
fontFamily?.let {
for (editTextBinding in bindings) {
// Load custom font from assets, and fallback to default system font
editTextBinding.typeface =
ReactTypefaceUtils.applyStyles(
null,
-1,
-1,
it.takeIf { it.isNotEmpty() },
context.assets,
)
}
}
cursorColor?.let {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val color = Color.parseColor(it)
for (editTextBinding in bindings) {
editTextBinding.textCursorDrawable?.setTint(color)
editTextBinding.textSelectHandle?.setTint(color)
editTextBinding.textSelectHandleLeft?.setTint(color)
editTextBinding.textSelectHandleRight?.setTint(color)
editTextBinding.highlightColor = color
}
}
}
mCardWidget.setPadding(20, 0, 20, 0)
mCardWidget.background =
MaterialShapeDrawable(
ShapeAppearanceModel()
.toBuilder()
.setAllCorners(CornerFamily.ROUNDED, PixelUtil.toPixelFromDIP(borderRadius.toDouble()))
.build(),
).also { shape ->
shape.strokeWidth = 0.0f
shape.strokeColor = ColorStateList.valueOf(Color.parseColor("#000000"))
shape.fillColor = ColorStateList.valueOf(Color.parseColor("#FFFFFF"))
borderWidth?.let {
shape.strokeWidth = PixelUtil.toPixelFromDIP(it.toDouble())
}
borderColor?.let {
shape.strokeColor = ColorStateList.valueOf(Color.parseColor(it))
}
backgroundColor?.let {
shape.fillColor = ColorStateList.valueOf(Color.parseColor(it))
}
}
}
private fun setCardBrandTint(color: Int) {
try {
cardInputWidgetBinding.cardBrandView::class.java
.getDeclaredMethod("setTintColorInt\$payments_core_release", Int::class.java)
.let {
it(cardInputWidgetBinding.cardBrandView, color)
}
} catch (e: Exception) {
Log.e(
"StripeReactNative",
"Unable to set card brand tint color: " + e.message,
)
}
}
fun setPlaceHolders(value: ReadableMap?) {
val numberPlaceholder = getValOr(value, "number", null)
val expirationPlaceholder = getValOr(value, "expiration", null)
val cvcPlaceholder = getValOr(value, "cvc", null)
val postalCodePlaceholder = getValOr(value, "postalCode", null)
numberPlaceholder?.let {
cardInputWidgetBinding.cardNumberEditText.hint = it
}
expirationPlaceholder?.let {
cardInputWidgetBinding.expiryDateEditText.hint = it
}
cvcPlaceholder?.let {
mCardWidget.setCvcLabel(it)
}
postalCodePlaceholder?.let {
cardInputWidgetBinding.postalCodeEditText.hint = it
}
}
fun setDangerouslyGetFullCardDetails(isEnabled: Boolean) {
dangerouslyGetFullCardDetails = isEnabled
}
fun setPostalCodeEnabled(isEnabled: Boolean) {
mCardWidget.postalCodeEnabled = isEnabled
if (isEnabled == false) {
mCardWidget.postalCodeRequired = false
}
}
fun setDisabled(isDisabled: Boolean) {
mCardWidget.isEnabled = !isDisabled
}
fun setPreferredNetworks(preferredNetworks: ArrayList<Int>?) {
mCardWidget.setPreferredNetworks(mapToPreferredNetworks(preferredNetworks))
}
fun setOnBehalfOf(onBehalfOf: String?) {
mCardWidget.onBehalfOf = onBehalfOf
}
/**
* We can reliable assume that setPostalCodeEnabled is called before
* setCountryCode because of the order of the props in CardField.tsx
*/
@SuppressLint("RestrictedApi")
fun setCountryCode(countryString: String?) {
if (mCardWidget.postalCodeEnabled) {
val countryCode =
CountryCode.create(
value = countryString ?: LocaleListCompat.getAdjustedDefault()[0]?.country ?: "US",
)
mCardWidget.postalCodeRequired = CountryUtils.doesCountryUsePostalCode(countryCode)
setPostalCodeFilter(countryCode)
}
}
fun getValue(): MutableMap<String, Any?> = cardDetails
private fun onValidCardChange() {
mCardWidget.paymentMethodCard?.let {
cardParams = it
cardAddress =
Address
.Builder()
.setPostalCode(cardDetails["postalCode"] as String?)
.build()
} ?: run {
cardParams = null
cardAddress = null
}
mCardWidget.cardParams?.let {
cardDetails["brand"] = mapCardBrand(it.brand)
cardDetails["last4"] = it.last4
} ?: run {
cardDetails["brand"] = null
cardDetails["last4"] = null
}
sendCardDetailsEvent()
}
private fun sendCardDetailsEvent() {
UIManagerHelper
.getEventDispatcherForReactTag(context, id)
?.dispatchEvent(
CardChangeEvent(
context.surfaceId,
id,
cardDetails,
mCardWidget.postalCodeEnabled,
isCardValid,
dangerouslyGetFullCardDetails,
),
)
}
private fun setListeners() {
cardInputWidgetBinding.cardNumberEditText.setOnFocusChangeListener { _, hasFocus ->
currentFocusedField = if (hasFocus) CardInputListener.FocusField.CardNumber.name else null
onChangeFocus()
}
cardInputWidgetBinding.expiryDateEditText.setOnFocusChangeListener { _, hasFocus ->
currentFocusedField = if (hasFocus) CardInputListener.FocusField.ExpiryDate.name else null
onChangeFocus()
}
cardInputWidgetBinding.cvcEditText.setOnFocusChangeListener { _, hasFocus ->
currentFocusedField = if (hasFocus) CardInputListener.FocusField.Cvc.name else null
onChangeFocus()
}
cardInputWidgetBinding.postalCodeEditText.setOnFocusChangeListener { _, hasFocus ->
currentFocusedField = if (hasFocus) CardInputListener.FocusField.PostalCode.name else null
onChangeFocus()
}
mCardWidget.setCardValidCallback { isValid, invalidFields ->
isCardValid = isValid
fun getCardValidationState(
field: CardValidCallback.Fields,
editTextField: StripeEditText,
): String {
if (invalidFields.contains(field)) {
return if (editTextField.shouldShowError) {
"Invalid"
} else {
"Incomplete"
}
}
return "Valid"
}
cardDetails["validNumber"] =
getCardValidationState(
CardValidCallback.Fields.Number,
cardInputWidgetBinding.cardNumberEditText,
)
cardDetails["validCVC"] =
getCardValidationState(CardValidCallback.Fields.Cvc, cardInputWidgetBinding.cvcEditText)
cardDetails["validExpiryDate"] =
getCardValidationState(
CardValidCallback.Fields.Expiry,
cardInputWidgetBinding.expiryDateEditText,
)
cardDetails["brand"] = mapCardBrand(cardInputWidgetBinding.cardNumberEditText.cardBrand)
if (isValid) {
onValidCardChange()
} else {
cardParams = null
cardAddress = null
sendCardDetailsEvent()
}
}
mCardWidget.setCardInputListener(
object : CardInputListener {
override fun onCardComplete() {}
override fun onExpirationComplete() {}
override fun onCvcComplete() {}
override fun onPostalCodeComplete() {}
override fun onFocusChange(focusField: CardInputListener.FocusField) {}
},
)
mCardWidget.setExpiryDateTextWatcher(
object : TextWatcher {
override fun beforeTextChanged(
p0: CharSequence?,
p1: Int,
p2: Int,
p3: Int,
) {
}
override fun afterTextChanged(p0: Editable?) {}
override fun onTextChanged(
var1: CharSequence?,
var2: Int,
var3: Int,
var4: Int,
) {
val splitText = var1.toString().split("/")
cardDetails["expiryMonth"] = splitText[0].toIntOrNull()
if (splitText.size == 2) {
cardDetails["expiryYear"] = var1.toString().split("/")[1].toIntOrNull()
}
}
},
)
mCardWidget.setPostalCodeTextWatcher(
object : TextWatcher {
override fun beforeTextChanged(
p0: CharSequence?,
p1: Int,
p2: Int,
p3: Int,
) {
}
override fun afterTextChanged(p0: Editable?) {}
override fun onTextChanged(
var1: CharSequence?,
var2: Int,
var3: Int,
var4: Int,
) {
cardDetails["postalCode"] = var1.toString()
}
},
)
mCardWidget.setCardNumberTextWatcher(
object : TextWatcher {
override fun beforeTextChanged(
p0: CharSequence?,
p1: Int,
p2: Int,
p3: Int,
) {
}
override fun afterTextChanged(p0: Editable?) {}
override fun onTextChanged(
var1: CharSequence?,
var2: Int,
var3: Int,
var4: Int,
) {
if (dangerouslyGetFullCardDetails) {
cardDetails["number"] = var1.toString().replace(" ", "")
}
}
},
)
mCardWidget.setCvcNumberTextWatcher(
object : TextWatcher {
override fun beforeTextChanged(
p0: CharSequence?,
p1: Int,
p2: Int,
p3: Int,
) {
}
override fun afterTextChanged(p0: Editable?) {}
override fun onTextChanged(
var1: CharSequence?,
var2: Int,
var3: Int,
var4: Int,
) {
if (dangerouslyGetFullCardDetails) {
cardDetails["cvc"] = var1.toString()
}
}
},
)
}
@SuppressLint("RestrictedApi")
private fun setPostalCodeFilter(countryCode: CountryCode) {
cardInputWidgetBinding.postalCodeEditText.filters =
arrayOf(
*cardInputWidgetBinding.postalCodeEditText.filters,
createPostalCodeInputFilter(countryCode),
)
}
@SuppressLint("RestrictedApi")
private fun createPostalCodeInputFilter(countryCode: CountryCode): InputFilter {
return InputFilter { charSequence, start, end, _, _, _ ->
for (i in start until end) {
val isValidCharacter =
(
countryCode == CountryCode.US &&
PostalCodeUtilities.isValidUsPostalCodeCharacter(
charSequence[i],
)
) ||
(
countryCode != CountryCode.US &&
PostalCodeUtilities.isValidGlobalPostalCodeCharacter(
charSequence[i],
)
)
if (!isValidCharacter) {
return@InputFilter ""
}
}
return@InputFilter null
}
}
override fun requestLayout() {
super.requestLayout()
post(mLayoutRunnable)
}
private val mLayoutRunnable =
Runnable {
measure(
MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY),
)
layout(left, top, right, bottom)
}
}