Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions paymentsheet-example/detekt-baseline.xml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
<ID>MagicNumber:AppearanceStore.kt:AppearanceStore.State.Embedded$0xFF0074D4</ID>
<ID>MagicNumber:AppearanceStore.kt:AppearanceStore.State.Embedded$0xFF007AFF</ID>
<ID>MagicNumber:CartProduct.kt:100</ID>
<ID>MagicNumber:CheckoutControllerExampleBackendRepository.kt:CheckoutControllerExampleBackendRepository$5000</ID>
<ID>MagicNumber:DrawablePainter.kt:DrawablePainter$255</ID>
<ID>MagicNumber:Payment.kt:0.5f</ID>
<ID>MagicNumber:SharedPaymentTokenPlaygroundActivity.kt:SharedPaymentTokenPlaygroundActivity$9999L</ID>
Expand Down
3 changes: 3 additions & 0 deletions paymentsheet-example/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,9 @@
<activity
android:name="com.stripe.android.paymentsheet.example.playground.checkout.CheckoutPlaygroundActivity"
android:theme="@style/AppTheme.NoActionBar" />
<activity
android:name="com.stripe.android.paymentsheet.example.playground.checkout.CheckoutControllerExampleActivity"
android:theme="@style/AppTheme.NoActionBar" />
<activity
android:name="com.stripe.android.paymentsheet.example.playground.PaymentSheetPlaygroundActivity"
android:theme="@style/AppTheme.NoActionBar"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import androidx.compose.ui.unit.dp
import com.stripe.android.core.version.StripeSdkVersion
import com.stripe.android.paymentsheet.example.databinding.ActivityMainBinding
import com.stripe.android.paymentsheet.example.playground.PaymentSheetPlaygroundActivity
import com.stripe.android.paymentsheet.example.playground.checkout.CheckoutControllerExampleActivity
import com.stripe.android.paymentsheet.example.playground.embedded.EmbeddedExampleActivity
import com.stripe.android.paymentsheet.example.samples.ui.SECTION_ALPHA
import com.stripe.android.paymentsheet.example.samples.ui.addresselement.AddressElementExampleActivity
Expand Down Expand Up @@ -60,6 +61,12 @@ class MainActivity : AppCompatActivity() {
klass = PaymentSheetPlaygroundActivity::class.java,
section = MenuItem.Section.Internal,
),
MenuItem(
titleResId = R.string.checkout_controller_example_title,
subtitleResId = R.string.checkout_controller_example_subtitle,
klass = CheckoutControllerExampleActivity::class.java,
section = MenuItem.Section.Internal,
),
MenuItem(
titleResId = R.string.paymentsheet_title,
subtitleResId = R.string.paymentsheet_subtitle,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,237 @@
@file:OptIn(CheckoutSessionPreview::class)

package com.stripe.android.paymentsheet.example.playground.checkout

import android.os.Bundle
import android.widget.Toast
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.Button
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.Divider
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.lifecycle.lifecycleScope
import com.stripe.android.checkout.CheckoutSession
import com.stripe.android.checkout.PaymentElement
import com.stripe.android.paymentelement.CheckoutSessionPreview
import com.stripe.android.paymentsheet.example.playground.PlaygroundTheme
import com.stripe.android.uicore.format.CurrencyFormatter
import kotlinx.coroutines.launch

internal class CheckoutControllerExampleActivity : AppCompatActivity() {

private val viewModel: CheckoutControllerExampleViewModel by viewModels {
CheckoutControllerExampleViewModel.factory
}

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val presenter = viewModel.controller.createPresenter(this)
val paymentElement = presenter.paymentElement()

lifecycleScope.launch {
viewModel.sessionComplete.collect {
Toast.makeText(this@CheckoutControllerExampleActivity, "Payment complete!", Toast.LENGTH_LONG).show()
finish()
}
}

setContent {
val status by viewModel.status.collectAsState()

PlaygroundTheme(
content = {
when (val currentStatus = status) {
is CheckoutControllerExampleViewModel.Status.Loading -> {
LoadingContent()
}
is CheckoutControllerExampleViewModel.Status.Error -> {
ErrorContent(currentStatus.message)
}
is CheckoutControllerExampleViewModel.Status.Configured -> {
val session = currentStatus.checkoutSession
if (session != null) {
LineItemsSection(session)
TotalSummarySection(session)
paymentElement.PaymentOptionsContent()
}
}
}
},
bottomBarContent = {
val configured = status as? CheckoutControllerExampleViewModel.Status.Configured
// PaymentOptionRow(configured?.paymentOption)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should this be un-commented?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not built yet! So paymentOption doesn't actually exist, but this is how I'd expect it to work going forward.

But storing the "state" of the selected payment option is a few weeks out, so I don't expect it to be done for a bit.

Spacer(modifier = Modifier.height(8.dp))
Button(
onClick = { paymentElement.presentPaymentOptions() },
enabled = configured != null,
modifier = Modifier.fillMaxWidth(),
) {
Text("Select Payment Method")
}
Spacer(modifier = Modifier.height(8.dp))
Button(
onClick = { presenter.confirm() },
modifier = Modifier.fillMaxWidth(),
) {
Text("Confirm")
}
},
)
}
}
}

@Composable
private fun LoadingContent() {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center,
) {
CircularProgressIndicator()
}
}

@Composable
private fun ErrorContent(message: String) {
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
) {
Text(
text = "Error",
style = MaterialTheme.typography.h6,
color = Color.Red,
)
Spacer(modifier = Modifier.height(8.dp))
Text(text = message)
}
}

@Composable
private fun PaymentOptionRow(paymentOption: PaymentElement.PaymentOptionDisplayData?) {
if (paymentOption != null) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
Image(
painter = paymentOption.iconPainter,
contentDescription = null,
modifier = Modifier.size(32.dp),
)
Text(
text = paymentOption.label,
style = MaterialTheme.typography.body1,
)
}
} else {
Text(
text = "No payment method selected",
style = MaterialTheme.typography.body2,
color = Color.Gray,
)
}
}

@Composable
private fun LineItemsSection(session: CheckoutSession) {
Column(modifier = Modifier.fillMaxWidth()) {
Text(text = "Line Items", style = MaterialTheme.typography.h6)
Spacer(modifier = Modifier.height(8.dp))

for (item in session.lineItems) {
Row(
modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp),
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text(
text = "${item.name} x${item.quantity}",
style = MaterialTheme.typography.body2,
)
Text(
text = formatAmount(item.total, session.currency),
style = MaterialTheme.typography.body2,
)
}
}
}
}

@Composable
private fun TotalSummarySection(session: CheckoutSession) {
val summary = session.totalSummary ?: return

Column(modifier = Modifier.fillMaxWidth()) {
Divider(modifier = Modifier.padding(vertical = 12.dp))

SummaryRow(label = "Subtotal", amount = formatAmount(summary.subtotal, session.currency))

for (discount in summary.discountAmounts) {
SummaryRow(
label = discount.displayName,
amount = "-${formatAmount(discount.amount, session.currency)}",
)
}

summary.shippingRate?.let { shipping ->
val amountText = if (shipping.amount == 0L) "Free" else formatAmount(shipping.amount, session.currency)
SummaryRow(label = "Shipping", amount = amountText)
}

for (tax in summary.taxAmounts) {
val label = if (tax.inclusive) "${tax.displayName} (included)" else tax.displayName
SummaryRow(label = label, amount = formatAmount(tax.amount, session.currency))
}

Divider(modifier = Modifier.padding(vertical = 8.dp))

Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text(text = "Total", style = MaterialTheme.typography.subtitle1)
Text(
text = formatAmount(summary.totalDueToday, session.currency),
style = MaterialTheme.typography.subtitle1,
)
}
}
}

@Composable
private fun SummaryRow(label: String, amount: String) {
Row(
modifier = Modifier.fillMaxWidth().padding(vertical = 2.dp),
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text(text = label, style = MaterialTheme.typography.body2)
Text(text = amount, style = MaterialTheme.typography.body2)
}
}

private fun formatAmount(amount: Long, currency: String): String {
return CurrencyFormatter.format(amount, currency)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package com.stripe.android.paymentsheet.example.playground.checkout

import android.content.Context
import com.github.kittinunf.fuel.Fuel
import com.github.kittinunf.fuel.core.extensions.jsonBody
import com.github.kittinunf.fuel.core.requests.suspendable
import com.github.kittinunf.result.Result
import com.stripe.android.PaymentConfiguration
import com.stripe.android.paymentsheet.example.Settings
import com.stripe.android.paymentsheet.example.playground.model.CheckoutRequest
import com.stripe.android.paymentsheet.example.playground.model.CheckoutResponse
import com.stripe.android.paymentsheet.example.samples.networking.awaitModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.json.Json

internal class CheckoutControllerExampleBackendRepository(
private val applicationContext: Context,
) {
private val json = Json { ignoreUnknownKeys = true }
private val backendUrl = Settings(applicationContext).playgroundBackendUrl

suspend fun fetchCheckoutSessionClientSecret(): kotlin.Result<String> {
val requestBody = CheckoutRequest.Builder()
.initialization("checkout_session")
.useCheckoutSession(true)
.mode("payment")
.currency("usd")
.amount(5000)
.customer("new")
.build()

val apiResponse = withContext(Dispatchers.IO) {
Fuel.post(backendUrl + "checkout")
.jsonBody(json.encodeToString(CheckoutRequest.serializer(), requestBody))
.suspendable()
.awaitModel(CheckoutResponse.serializer(), json)
}

return when (apiResponse) {
is Result.Failure -> {
kotlin.Result.failure(apiResponse.getException())
}
is Result.Success -> {
val response = apiResponse.value

withContext(Dispatchers.IO) {
PaymentConfiguration.init(applicationContext, response.publishableKey)
}

val clientSecret = response.checkoutSessionClientSecret
?: return kotlin.Result.failure(
IllegalStateException("No checkout session client secret in response")
)

kotlin.Result.success(clientSecret)
}
}
}
}
Loading
Loading