-
Notifications
You must be signed in to change notification settings - Fork 0
/
SpaydBankAppPaymentResolver.android.kt
222 lines (198 loc) · 8.51 KB
/
SpaydBankAppPaymentResolver.android.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
@file:Suppress("EXPECT_ACTUAL_CLASSIFIERS_ARE_IN_BETA_WARNING")
package io.stepuplabs.pvba
import android.app.Activity
import android.app.Application
import android.content.ClipData
import android.content.Intent
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Build
import androidx.core.content.FileProvider
import io.github.g0dkar.qrcode.QRCode
import io.ktor.http.Url
import okio.FileSystem
import okio.Path
import okio.Path.Companion.toPath
import okio.buffer
import java.lang.ref.WeakReference
/**
* This is the main entry point for paying directly via a bank app supporting SPAYD format.
*/
actual class SpaydPayViaBankAppResolver(
private val application: Application,
private val fileProviderAuthority: String,
private val bankAppPackages: List<String> = DEFAULT_BANK_APP_PACKAGES
) {
/**
* Shows whether the device supports Pay via Bank App and if the feature should be visible.
*/
actual fun isPayViaBankAppSupported(): Boolean {
return getSpaydReceivers().isNotEmpty() || getImageReceivers().isNotEmpty()
}
/**
* When there is just one bank app supporting bank app payment, this returns the icon of that bank app.
*/
fun getSupportedBankAppIcon(): Drawable? {
val spaydReceivers = getSpaydReceivers()
val imageReceivers = getImageReceivers()
return if (spaydReceivers.size == 1 && imageReceivers.isEmpty()) {
application.packageManager.getApplicationIcon(spaydReceivers.first())
} else if (imageReceivers.size == 1 && spaydReceivers.isEmpty()) {
application.packageManager.getApplicationIcon(imageReceivers.first())
} else {
null
}
}
/**
* Opens a supported bank app with a payment flow or shows a chooser with multiple apps.
*/
actual fun payViaBankApp(
spayd: String,
navigationParams: NavigationParameters
): Result<Unit> {
val spaydReceivers = getSpaydReceivers()
val imageReceivers = getImageReceivers()
val genericSpaydIntent = {
Intent().apply {
action = Intent.ACTION_VIEW
putExtra("spayd", spayd)
type = "application/x-shortpaymentdescriptor"
}
}
val genericImageIntent = { qrCodeUri: Url ->
Intent().apply {
action = Intent.ACTION_SEND
putExtra(Intent.EXTRA_STREAM, Uri.parse(qrCodeUri.toString()))
type = "image/*"
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
clipData = ClipData.newRawUri("", Uri.parse(qrCodeUri.toString()))
}
}
val spaydIntents = {
spaydReceivers.map {
Intent(genericSpaydIntent()).apply { `package` = it }
}
}
val imageIntents = { qrCodeUri: Url ->
imageReceivers.map {
Intent(genericImageIntent(qrCodeUri)).apply { `package` = it }
}
}
try {
when {
// only one spayd receiver, open straight away
spaydReceivers.size == 1 && imageReceivers.isEmpty() -> {
navigationParams.activityReference.get()?.startActivity(spaydIntents().first())
}
// only one image receiver, open straight away
imageReceivers.size == 1 && spaydReceivers.isEmpty() -> {
val qrCodeUri = generateQrCodeUri(spayd)
navigationParams.activityReference.get()
?.startActivity(imageIntents(qrCodeUri).first())
}
// many spayds receivers and no image receiver, show chooser with spayds prioritized (no QR preview)
spaydReceivers.isNotEmpty() && imageReceivers.isEmpty() -> {
val intent = Intent.createChooser(genericSpaydIntent(), "").apply {
putExtra(
Intent.EXTRA_INITIAL_INTENTS,
spaydIntents().toTypedArray()
)
}
navigationParams.activityReference.get()?.startActivity(intent)
}
// many image receivers and no spayd receiver, show chooser with image receivers prioritized (with QR preview)
imageReceivers.isNotEmpty() && spaydReceivers.isEmpty() -> {
val qrCodeUri = generateQrCodeUri(spayd)
val intent = Intent.createChooser(genericImageIntent(qrCodeUri), "").apply {
putExtra(
Intent.EXTRA_INITIAL_INTENTS,
imageIntents(qrCodeUri).toTypedArray()
)
}
navigationParams.activityReference.get()?.startActivity(intent)
}
// both image and spayd receivers are empty, show nondiscriminatory chooser with everything that can process image
else -> {
val qrCodeUri = generateQrCodeUri(spayd)
val intent = Intent.createChooser(genericImageIntent(qrCodeUri), "").apply {
putExtra(
Intent.EXTRA_INITIAL_INTENTS,
imageIntents(qrCodeUri).plus(spaydIntents())
.toTypedArray(),
)
}
navigationParams.activityReference.get()?.startActivity(intent)
}
}
return Result.success(Unit)
} catch (e: QrCodeFileException) {
return Result.failure(e)
} catch (e: Exception) {
return Result.failure(BankAppOpeningException(e))
}
}
private fun getSpaydReceivers(): List<String> {
return application.packageManager.intentReceivers(Intent(Intent.ACTION_VIEW).apply {
type = "application/x-shortpaymentdescriptor"
})
}
private fun getImageReceivers(): Set<String> {
return application.packageManager.intentReceivers(Intent(Intent.ACTION_SEND).apply {
type = "image/*"
}).intersect(bankAppPackages.toSet())
}
private fun generateQrCodeUri(spayd: String): Url {
try {
val cachePath = application.cacheDir.path
val dir = "$cachePath${Path.DIRECTORY_SEPARATOR}$DIR".toPath(true)
if (!FileSystem.SYSTEM.exists(dir)) {
FileSystem.SYSTEM.createDirectories(dir)
}
val path = "$dir${Path.DIRECTORY_SEPARATOR}$FILE".toPath(normalize = true)
FileSystem.SYSTEM.sink(path).use {
val outputStream = it.buffer().outputStream()
QRCode(spayd)
.render(30, 30)
.writeImage(outputStream)
outputStream.flush()
}
return Url(
(if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
Uri.fromFile(path.toFile())
} else {
FileProvider.getUriForFile(application, fileProviderAuthority, path.toFile())
}).toString()
)
} catch (e: Exception) {
throw QrCodeFileException(e)
}
}
companion object {
val DEFAULT_BANK_APP_PACKAGES = listOf(
"cz.rb.app.smartphonebanking", // Raiffeisenbank
"eu.inmite.prj.kb.mobilbank", // Komerční banka (old app)
"cz.kb.ndb", // Komerční banka (new app)
"cz.csas.georgego", // Česká spořitelna (George)
"cz.csob.smart", // ČSOB
"cz.moneta.smartbanka", // Moneta
"cz.fio.sb2", // Fio banka
"cz.airbank.android", // Air Bank
"cz.creditas.richee", // Banka CREDITAS
"cz.pbktechnology.partners.client" // Partners Banka
)
private const val DIR = "qr"
private const val FILE = "transfer-payment-qr.png"
}
}
/**
* This class should contain any platform-specific parameters which the system needs to launch navigation to the bank app or show a chooser.
*/
actual class NavigationParameters(val activityReference: WeakReference<Activity>)
/**
* This exception is returned when there is unexpected error when opening bank app Activity.
*/
class BankAppOpeningException(override val cause: Throwable?): Exception()
/**
* This exception is returned when there is unexpected error when creating a file for transfer QR code.
*/
class QrCodeFileException(override val cause: Throwable?): Exception()