Skip to content

Commit

Permalink
Create rememberLauncher to use Launchers in Compose (#5274)
Browse files Browse the repository at this point in the history
  • Loading branch information
brnunes-stripe authored Jul 27, 2022
1 parent 58408c8 commit 2c4e0e8
Show file tree
Hide file tree
Showing 12 changed files with 530 additions and 75 deletions.
8 changes: 5 additions & 3 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@
## X.X.X

### PaymentSheet
[FIXED][5321](https://github.com/stripe/stripe-android/pull/5321) Fixed issue with forever loading and mochi library.
* [FIXED][5321](https://github.com/stripe/stripe-android/pull/5321) Fixed issue with forever loading and mochi library.

### Payments
[FIXED][5308](https://github.com/stripe/stripe-android/pull/5308) OXXO so that processing is considered a successful terminal state, similar to Konbini and Boleto.
[FIXED][5138](https://github.com/stripe/stripe-android/pull/5138) Fixed an issue where PaymentSheet will show a failure even when 3DS2 Payment/SetupIntent is successful
* [FIXED][5308](https://github.com/stripe/stripe-android/pull/5308) OXXO so that processing is considered a successful terminal state, similar to Konbini and Boleto.
* [FIXED][5138](https://github.com/stripe/stripe-android/pull/5138) Fixed an issue where PaymentSheet will show a failure even when 3DS2 Payment/SetupIntent is successful.
* [ADDED][5274](https://github.com/stripe/stripe-android/pull/5274) Create `rememberLauncher` method enabling usage of `GooglePayLauncher`, `GooglePayPaymentMethodLauncher` and `PaymentLauncher` in Compose.
* [DEPRECATED][5274](https://github.com/stripe/stripe-android/pull/5274) Deprecate `PaymentLauncher.createForCompose` in favor of `PaymentLauncher.rememberLauncher`.

## 20.7.0 - 2022-07-06
* This release adds additional support for Afterpay/Clearpay in PaymentSheet.
Expand Down
2 changes: 2 additions & 0 deletions example/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,9 @@
<activity android:name=".activity.PaymentSessionActivity" />
<activity android:name=".activity.GooglePayLauncherIntegrationActivity" />
<activity android:name=".activity.GooglePayLauncherPlaygroundActivity" />
<activity android:name=".activity.GooglePayLauncherComposeActivity" />
<activity android:name=".activity.GooglePayPaymentMethodLauncherIntegrationActivity" />
<activity android:name=".activity.GooglePayPaymentMethodLauncherComposeActivity" />
<activity android:name=".activity.PaymentAuthActivity" />
<activity android:name=".activity.FragmentExamplesActivity" />
<activity android:name=".activity.ConfirmSepaDebitActivity" />
Expand Down
2 changes: 2 additions & 0 deletions example/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@
<string name="customer_payment_data_example">Customer Payment Selection</string>
<string name="launch_customer_session">Customer Session</string>
<string name="googlepaylauncher_example">Confirm payment with GooglePayLauncher</string>
<string name="googlepaycomposelauncher_example">Confirm payment in Compose with GooglePayLauncher</string>
<string name="googlepayplayground_example">Test GooglePayLauncher Configurations</string>
<string name="googlepaypaymentmethodlauncher_example">Create payment method with GooglePayPaymentMethodLauncher</string>
<string name="googlepaypaymentmethodcomposelauncher_example">Create payment method in Compose with GooglePayPaymentMethodLauncher</string>
<string name="launch_payment_session">Payment Session</string>
<string name="launch_payment_session_from_fragment">Fragment Examples</string>
<string name="create_payment_method">Create Payment Method</string>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
Expand Down Expand Up @@ -45,73 +46,89 @@ class ComposeExampleActivity : AppCompatActivity() {
fun ComposeScreen() {
val inProgress by viewModel.inProgress.observeAsState(false)
val status by viewModel.status.observeAsState("")
val paymentLauncher = rememberPaymentLauncher()

createPaymentLauncher().let { paymentLauncher ->
Column(modifier = Modifier.padding(horizontal = 10.dp)) {
if (inProgress) {
LinearProgressIndicator(
modifier = Modifier.fillMaxWidth()
)
}
Text(
stringResource(R.string.payment_auth_intro),
modifier = Modifier.padding(vertical = 5.dp)
)
ConfirmButton(
params = confirmParams3ds1,
buttonName = R.string.confirm_with_3ds1_button,
paymentLauncher = paymentLauncher,
inProgress = inProgress
)
ConfirmButton(
params = confirmParams3ds2,
buttonName = R.string.confirm_with_3ds2_button,
paymentLauncher = paymentLauncher,
inProgress = inProgress
ComposeScreen(
inProgress = inProgress,
status = status,
onConfirm = { paymentLauncher.confirm(it) }
)
}

@Composable
private fun ComposeScreen(
inProgress: Boolean,
status: String,
onConfirm: (ConfirmPaymentIntentParams) -> Unit
) {
Column(modifier = Modifier.padding(horizontal = 10.dp)) {
if (inProgress) {
LinearProgressIndicator(
modifier = Modifier.fillMaxWidth()
)
Divider(modifier = Modifier.padding(vertical = 5.dp))
Text(text = status)
}
Text(
stringResource(R.string.payment_auth_intro),
modifier = Modifier.padding(vertical = 5.dp)
)
ConfirmButton(
params = confirmParams3ds1,
buttonName = R.string.confirm_with_3ds1_button,
onConfirm = onConfirm,
inProgress = inProgress
)
ConfirmButton(
params = confirmParams3ds2,
buttonName = R.string.confirm_with_3ds2_button,
onConfirm = onConfirm,
inProgress = inProgress
)
Divider(modifier = Modifier.padding(vertical = 5.dp))
Text(text = status)
}
}

/**
* Create [PaymentLauncher] in a [Composable]
*/
@Composable
fun createPaymentLauncher(): PaymentLauncher {
val settings = Settings(LocalContext.current)
return PaymentLauncher.createForCompose(
private fun rememberPaymentLauncher(): PaymentLauncher {
val context = LocalContext.current
val settings = remember { Settings(context) }
return PaymentLauncher.rememberLauncher(
publishableKey = settings.publishableKey,
stripeAccountId = settings.stripeAccountId
) {
when (it) {
is PaymentResult.Completed -> {
viewModel.status.value += "\n\nPaymentIntent confirmation succeeded\n\n"
viewModel.inProgress.value = false
}
is PaymentResult.Canceled -> {
viewModel.status.value += "\n\nPaymentIntent confirmation cancelled\n\n"
viewModel.inProgress.value = false
}
is PaymentResult.Failed -> {
viewModel.status.value += "\n\nPaymentIntent confirmation failed with " +
"throwable ${it.throwable} \n\n"
viewModel.inProgress.value = false
}
stripeAccountId = settings.stripeAccountId,
callback = ::onPaymentResult
)
}

private fun onPaymentResult(paymentResult: PaymentResult) {
when (paymentResult) {
is PaymentResult.Completed -> {
viewModel.status.value += "\n\nPaymentIntent confirmation succeeded\n\n"
viewModel.inProgress.value = false
}
is PaymentResult.Canceled -> {
viewModel.status.value += "\n\nPaymentIntent confirmation cancelled\n\n"
viewModel.inProgress.value = false
}
is PaymentResult.Failed -> {
viewModel.status.value += "\n\nPaymentIntent confirmation failed with " +
"throwable ${paymentResult.throwable} \n\n"
viewModel.inProgress.value = false
}
}
}

@Composable
fun ConfirmButton(
private fun ConfirmButton(
params: PaymentMethodCreateParams,
@StringRes buttonName: Int,
paymentLauncher: PaymentLauncher,
inProgress: Boolean
inProgress: Boolean,
onConfirm: (ConfirmPaymentIntentParams) -> Unit
) {
Button(
onClick = { createAndConfirmPaymentIntent(params, paymentLauncher) },
onClick = { createAndConfirmPaymentIntent(params, onConfirm) },
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 5.dp),
Expand All @@ -123,7 +140,7 @@ class ComposeExampleActivity : AppCompatActivity() {

private fun createAndConfirmPaymentIntent(
params: PaymentMethodCreateParams,
paymentLauncher: PaymentLauncher
onConfirm: (ConfirmPaymentIntentParams) -> Unit
) {
viewModel.createPaymentIntent("us").observe(
this
Expand All @@ -135,7 +152,7 @@ class ComposeExampleActivity : AppCompatActivity() {
clientSecret = responseData.getString("secret"),
shipping = SHIPPING
)
paymentLauncher.confirm(confirmPaymentIntentParams)
onConfirm(confirmPaymentIntentParams)
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
package com.stripe.example.activity

import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.material.LinearProgressIndicator
import androidx.compose.material.Scaffold
import androidx.compose.material.ScaffoldState
import androidx.compose.material.rememberScaffoldState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import com.stripe.android.googlepaylauncher.GooglePayEnvironment
import com.stripe.android.googlepaylauncher.GooglePayLauncher
import kotlinx.coroutines.launch

class GooglePayLauncherComposeActivity : StripeIntentActivity() {
private val googlePayConfig = GooglePayLauncher.Config(
environment = GooglePayEnvironment.Test,
merchantCountryCode = COUNTRY_CODE,
merchantName = "Widget Store",
billingAddressConfig = GooglePayLauncher.BillingAddressConfig(
isRequired = true,
format = GooglePayLauncher.BillingAddressConfig.Format.Full,
isPhoneNumberRequired = false
),
existingPaymentMethodRequired = false
)

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)

setContent {
GooglePayLauncherScreen()
}
}

@Composable
private fun GooglePayLauncherScreen() {
val scaffoldState = rememberScaffoldState()
val scope = rememberCoroutineScope()

var clientSecret by rememberSaveable { mutableStateOf("") }
var googlePayReady by rememberSaveable { mutableStateOf<Boolean?>(null) }
var completed by rememberSaveable { mutableStateOf(false) }

LaunchedEffect(Unit) {
if (clientSecret.isBlank()) {
viewModel.createPaymentIntent(COUNTRY_CODE).observe(
this@GooglePayLauncherComposeActivity
) { result ->
result.fold(
onSuccess = { json ->
clientSecret = json.getString("secret")
},
onFailure = { error ->
scope.launch {
scaffoldState.snackbarHostState.showSnackbar(
"Could not create PaymentIntent. ${error.message}"
)
}
completed = true
}
)
}
}
}

val googlePayLauncher = GooglePayLauncher.rememberLauncher(
config = googlePayConfig,
readyCallback = { ready ->
if (googlePayReady == null) {
googlePayReady = ready

if (!ready) {
completed = true
}

scope.launch {
scaffoldState.snackbarHostState.showSnackbar("Google Pay ready? $ready")
}
}
},
resultCallback = { result ->
when (result) {
GooglePayLauncher.Result.Completed -> {
"Successfully collected payment."
}
GooglePayLauncher.Result.Canceled -> {
"Customer cancelled Google Pay."
}
is GooglePayLauncher.Result.Failed -> {
"Google Pay failed. ${result.error.message}"
}
}.let {
scope.launch {
scaffoldState.snackbarHostState.showSnackbar(it)
completed = true
}
}
}
)

GooglePayLauncherScreen(
scaffoldState = scaffoldState,
clientSecret = clientSecret,
googlePayReady = googlePayReady,
completed = completed,
onLaunchGooglePay = { googlePayLauncher.presentForPaymentIntent(it) }
)
}

@Composable
private fun GooglePayLauncherScreen(
scaffoldState: ScaffoldState,
clientSecret: String,
googlePayReady: Boolean?,
completed: Boolean,
onLaunchGooglePay: (String) -> Unit
) {
Scaffold(scaffoldState = scaffoldState) {
Column(Modifier.fillMaxWidth()) {
if (googlePayReady == null || clientSecret.isBlank()) {
LinearProgressIndicator(Modifier.fillMaxWidth())
}

Spacer(
Modifier
.height(8.dp)
.fillMaxWidth()
)

AndroidView(
factory = { context ->
GooglePayButton(context)
},
modifier = Modifier
.wrapContentWidth()
.clickable(
enabled = googlePayReady == true &&
clientSecret.isNotBlank() && !completed,
onClick = {
onLaunchGooglePay(clientSecret)
}
)
)
}
}
}

private companion object {
private const val COUNTRY_CODE = "US"
}
}
Loading

0 comments on commit 2c4e0e8

Please sign in to comment.