-
Notifications
You must be signed in to change notification settings - Fork 37
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Jetpack compose sample #186
Open
GibsonRuitiari
wants to merge
3
commits into
paypal:main
Choose a base branch
from
GibsonRuitiari:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 2 commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
194 changes: 194 additions & 0 deletions
194
...t-kotlin/src/main/java/com/paypal/checkoutsamples/order/KotlinJetpackComposeQuickStart.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,194 @@ | ||
package com.paypal.checkoutsamples.order | ||
|
||
import android.os.Bundle | ||
import android.util.Log | ||
import androidx.activity.ComponentActivity | ||
import androidx.activity.compose.setContent | ||
import androidx.compose.animation.AnimatedVisibility | ||
import androidx.compose.foundation.layout.Arrangement | ||
import androidx.compose.foundation.layout.Box | ||
import androidx.compose.foundation.layout.Column | ||
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.MaterialTheme | ||
import androidx.compose.material.Surface | ||
import androidx.compose.material.Text | ||
import androidx.compose.runtime.Composable | ||
import androidx.compose.runtime.LaunchedEffect | ||
import androidx.compose.runtime.collectAsState | ||
import androidx.compose.runtime.getValue | ||
import androidx.compose.runtime.mutableStateOf | ||
import androidx.compose.runtime.remember | ||
import androidx.compose.runtime.setValue | ||
import androidx.compose.ui.Alignment | ||
import androidx.compose.ui.Modifier | ||
import androidx.compose.ui.text.style.TextAlign | ||
import androidx.compose.ui.unit.dp | ||
import com.paypal.checkout.PayPalCheckout | ||
import com.paypal.checkout.approve.OnApprove | ||
import com.paypal.checkout.cancel.OnCancel | ||
import com.paypal.checkout.createorder.CreateOrder | ||
import com.paypal.checkout.createorder.CurrencyCode | ||
import com.paypal.checkout.createorder.OrderIntent | ||
import com.paypal.checkout.createorder.ShippingPreference | ||
import com.paypal.checkout.createorder.UserAction | ||
import com.paypal.checkout.error.OnError | ||
import com.paypal.checkout.order.CaptureOrderResult | ||
import com.paypal.checkoutsamples.order.usecase.CreateOrderRequest | ||
import com.paypal.checkoutsamples.order.usecase.CreateOrderUseCase | ||
import com.paypal.checkoutsamples.ui.theme.AndroidNativeCheckoutSamplesTheme | ||
import kotlinx.coroutines.flow.MutableStateFlow | ||
import kotlinx.coroutines.flow.StateFlow | ||
import kotlinx.coroutines.flow.update | ||
|
||
class KotlinJetpackComposeQuickStart : ComponentActivity() { | ||
private val checkoutState = MutableStateFlow<PaypalCheckoutState>(Loading) | ||
private val checkOutSdk:PayPalCheckout | ||
get() = PayPalCheckout | ||
private val createdItems = mutableListOf<CreatedItem>() | ||
override fun onCreate(savedInstanceState: Bundle?) { | ||
super.onCreate(savedInstanceState) | ||
registerPaypalCheckoutCallback(checkOutSdk) | ||
val createOrderUseCase by lazy { CreateOrderUseCase() } | ||
|
||
setContent { | ||
AndroidNativeCheckoutSamplesTheme { | ||
Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background) { | ||
PaymentScreen(paypalSdkInstance = checkOutSdk, orderUseCase = createOrderUseCase, | ||
checkoutState = checkoutState, | ||
createdItems = createdItems) | ||
} | ||
} | ||
} | ||
} | ||
|
||
/* represents the different states to be observed when payment is initiated */ | ||
sealed interface PaypalCheckoutState | ||
object Loading : PaypalCheckoutState | ||
object OrderPaidForSuccessfully : PaypalCheckoutState | ||
object OrderCapturingFailed : PaypalCheckoutState | ||
object OrderPaymentCancelled : PaypalCheckoutState | ||
|
||
@JvmInline | ||
value class OrderPaymentFailedWithAnError(val errorMsg: String) : PaypalCheckoutState | ||
|
||
fun registerPaypalCheckoutCallback(checkoutSdk: PayPalCheckout) { | ||
checkoutSdk.registerCallbacks(onApprove = OnApprove { approval -> | ||
approval.orderActions.capture { result -> | ||
val message = when (result) { | ||
is CaptureOrderResult.Success -> { | ||
checkoutState.update { OrderPaidForSuccessfully } | ||
"payment successful. Thank you for shopping with us" | ||
} | ||
|
||
is CaptureOrderResult.Error -> { | ||
checkoutState.update { OrderCapturingFailed } | ||
"failed to capture your order" | ||
} | ||
} | ||
Log.i("ComposeActivityTag",message) | ||
} | ||
}, onCancel = OnCancel { | ||
checkoutState.update { OrderPaymentCancelled } | ||
Log.i("ComposeActivityTag","payment cancelled") | ||
}, onError = OnError { errorInfo -> | ||
checkoutState.update { OrderPaymentFailedWithAnError(errorInfo.reason) } | ||
Log.i("ComposeActivityTag","the following error occurred while paying ${errorInfo.reason}") | ||
}) | ||
} | ||
@Composable | ||
fun PaymentScreen(modifier: Modifier=Modifier, | ||
paypalSdkInstance:PayPalCheckout, | ||
orderUseCase: CreateOrderUseCase, | ||
checkoutState:StateFlow<PaypalCheckoutState>, | ||
createdItems: List<CreatedItem>){ | ||
var observeCheckoutState by remember { mutableStateOf(false) } | ||
var checkoutStateMsg by remember { mutableStateOf("") } | ||
val _checkoutState by checkoutState.collectAsState(Loading) | ||
when(observeCheckoutState){ | ||
true->{ | ||
CircularProgressIndicator(modifier = Modifier.size(200.dp)) | ||
ObservePaypalCheckoutState(_checkoutState){ | ||
observeState,msg-> | ||
observeCheckoutState = observeState | ||
checkoutStateMsg=msg | ||
} | ||
} | ||
else->{ | ||
Box(modifier = modifier.fillMaxSize(), contentAlignment = Alignment.Center){ | ||
Column(modifier = Modifier, verticalArrangement = Arrangement.SpaceEvenly, horizontalAlignment = Alignment.CenterHorizontally){ | ||
Spacer(Modifier.height(20.dp)) | ||
AnimatedVisibility(visible = checkoutStateMsg.isNotEmpty()){ | ||
Text(checkoutStateMsg, textAlign = TextAlign.Center) | ||
} | ||
Spacer(Modifier.height(20.dp)) | ||
Button(modifier=Modifier.fillMaxWidth() | ||
.padding(horizontal = 20.dp), | ||
onClick = { | ||
// initiate payment | ||
observeCheckoutState=true | ||
initiatePaymentMethod(paypalSdkInstance, orderUseCase, createdItems) | ||
}){ | ||
Text("Complete Purchase") | ||
} | ||
} | ||
} | ||
} | ||
} | ||
} | ||
/* Observes the different check-out states and updates the screen with the correct message | ||
* Can be customized according to the user-needs */ | ||
@Composable | ||
private fun ObservePaypalCheckoutState(checkoutState:PaypalCheckoutState, | ||
updateObserveCheckoutState:(Boolean,String)->Unit){ | ||
LaunchedEffect(checkoutState){ | ||
when(checkoutState){ | ||
Loading -> Log.d("ComposeActivityTag","Initiating order capture..") | ||
OrderCapturingFailed -> { | ||
// stop observing and show the default view to enable the user to initiate payment again | ||
updateObserveCheckoutState(false,"Order capturing failed..") | ||
Log.d("ComposeActivityTag","Order capturing failed..") | ||
} | ||
OrderPaidForSuccessfully ->{ | ||
Log.d("ComposeActivityTag","Order capturing success") | ||
// stop observing and show the default view to enable the user to initiate payment again | ||
updateObserveCheckoutState(false, "Order capturing success") | ||
} | ||
OrderPaymentCancelled ->{ | ||
Log.d("ComposeActivityTag","Order payment cancelled!") | ||
updateObserveCheckoutState(false,"Order payment cancelled!") | ||
} | ||
is OrderPaymentFailedWithAnError ->{ | ||
updateObserveCheckoutState(false,"Order payment failed with the following error ${checkoutState.errorMsg}") | ||
Log.d("ComposeActivityTag","Order payment failed with the following error ${checkoutState.errorMsg}") | ||
} | ||
} | ||
} | ||
} | ||
/* Creates the order item needed by paypal checkout sdk */ | ||
private fun initiatePaymentMethod( | ||
paypalSdkInstance: PayPalCheckout, | ||
orderUseCase: CreateOrderUseCase, | ||
createdItems: List<CreatedItem> | ||
) { | ||
// create your order request | ||
val createOrderRequest = CreateOrderRequest( | ||
orderIntent = OrderIntent.CAPTURE, | ||
userAction = UserAction.PAY_NOW, shippingPreference = ShippingPreference.NO_SHIPPING, | ||
currencyCode = CurrencyCode.USD, createdItems = createdItems | ||
) | ||
val orderObject = orderUseCase.execute(createOrderRequest) | ||
// start check out process | ||
paypalSdkInstance.startCheckout(createOrder = CreateOrder.invoke { actions -> | ||
actions.create(orderObject) { orderId -> | ||
Log.d("ComposeActivityTag", "Order id $orderId") | ||
} | ||
}) | ||
} | ||
} |
8 changes: 8 additions & 0 deletions
8
quickstart-kotlin/src/main/java/com/paypal/checkoutsamples/ui/theme/Color.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
package com.paypal.checkoutsamples.ui.theme | ||
|
||
import androidx.compose.ui.graphics.Color | ||
|
||
val Purple200 = Color(0xFFBB86FC) | ||
val Purple500 = Color(0xFF6200EE) | ||
val Purple700 = Color(0xFF3700B3) | ||
val Teal200 = Color(0xFF03DAC5) |
11 changes: 11 additions & 0 deletions
11
quickstart-kotlin/src/main/java/com/paypal/checkoutsamples/ui/theme/Shape.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
package com.paypal.checkoutsamples.ui.theme | ||
|
||
import androidx.compose.foundation.shape.RoundedCornerShape | ||
import androidx.compose.material.Shapes | ||
import androidx.compose.ui.unit.dp | ||
|
||
val Shapes = Shapes( | ||
small = RoundedCornerShape(4.dp), | ||
medium = RoundedCornerShape(4.dp), | ||
large = RoundedCornerShape(0.dp) | ||
) |
44 changes: 44 additions & 0 deletions
44
quickstart-kotlin/src/main/java/com/paypal/checkoutsamples/ui/theme/Theme.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
package com.paypal.checkoutsamples.ui.theme | ||
|
||
import androidx.compose.foundation.isSystemInDarkTheme | ||
import androidx.compose.material.MaterialTheme | ||
import androidx.compose.material.darkColors | ||
import androidx.compose.material.lightColors | ||
import androidx.compose.runtime.Composable | ||
|
||
private val DarkColorPalette = darkColors( | ||
primary = Purple200, | ||
primaryVariant = Purple700, | ||
secondary = Teal200 | ||
) | ||
|
||
private val LightColorPalette = lightColors( | ||
primary = Purple500, | ||
primaryVariant = Purple700, | ||
secondary = Teal200 | ||
|
||
/* Other default colors to override | ||
background = Color.White, | ||
surface = Color.White, | ||
onPrimary = Color.White, | ||
onSecondary = Color.Black, | ||
onBackground = Color.Black, | ||
onSurface = Color.Black, | ||
*/ | ||
) | ||
|
||
@Composable | ||
fun AndroidNativeCheckoutSamplesTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) { | ||
val colors = if (darkTheme) { | ||
DarkColorPalette | ||
} else { | ||
LightColorPalette | ||
} | ||
|
||
MaterialTheme( | ||
colors = colors, | ||
typography = Typography, | ||
shapes = Shapes, | ||
content = content | ||
) | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I would better make a separate file for this Interface.
or might be better if we can keep the same callback message that is coming from
PayPal SDK
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Haha bet you to it.
I can make a separate file for this interface since relying on the callback message coming from
Paypal Sdk
might not be that flexible because of the tight coupling of the app andPaypal Sdk
. If thePaypal Sdk
callback message change, you'll might have to refactor a lot of code to match the new changes.Imo, making your own 'state' interface is better but I am open to guidance from you.