android - Jetpack compose 中的 Google pay Api - 如何

标签 android kotlin android-jetpack-compose google-pay

我在互联网上找不到有关如何将 Google API 集成到基于 Compose 的应用中的资源。

我需要帮助,特别是在 AutoResolveHelper.resolveTask 方面,如何在 compose 中执行此操作。

感谢您的回答。

(令人震惊的是,没有关于此 API 的更多文档,实现起来非常困难)。

编辑:

这是传统的方法 ->

private fun requestPayment() {

    // Disables the button to prevent multiple clicks.
    googlePayButton.isClickable = false

    // The price provided to the API should include taxes and shipping.
    // This price is not displayed to the user.
    val garmentPrice = selectedGarment.getDouble("price")
    val priceCents = Math.round(garmentPrice * PaymentsUtil.CENTS.toLong()) + SHIPPING_COST_CENTS

    val paymentDataRequestJson = PaymentsUtil.getPaymentDataRequest(priceCents)
    if (paymentDataRequestJson == null) {
        Log.e("RequestPayment", "Can't fetch payment data request")
        return
    }
    val request = PaymentDataRequest.fromJson(paymentDataRequestJson.toString())

    // Since loadPaymentData may show the UI asking the user to select a payment method, we use
    // AutoResolveHelper to wait for the user interacting with it. Once completed,
    // onActivityResult will be called with the result.
    if (request != null) {
        AutoResolveHelper.resolveTask(
                paymentsClient.loadPaymentData(request), this, LOAD_PAYMENT_DATA_REQUEST_CODE)
    }
}

/**
 * Handle a resolved activity from the Google Pay payment sheet.
 *
 * @param requestCode Request code originally supplied to AutoResolveHelper in requestPayment().
 * @param resultCode Result code returned by the Google Pay API.
 * @param data Intent from the Google Pay API containing payment or error data.
 * @see [Getting a result
 * from an Activity](https://developer.android.com/training/basics/intents/result)
 */
public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    when (requestCode) {
        // Value passed in AutoResolveHelper
        LOAD_PAYMENT_DATA_REQUEST_CODE -> {
            when (resultCode) {
                RESULT_OK ->
                    data?.let { intent ->
                        PaymentData.getFromIntent(intent)?.let(::handlePaymentSuccess)
                    }

                RESULT_CANCELED -> {
                    // The user cancelled the payment attempt
                }

                AutoResolveHelper.RESULT_ERROR -> {
                    AutoResolveHelper.getStatusFromIntent(data)?.let {
                        handleError(it.statusCode)
                    }
                }
            }

            // Re-enables the Google Pay payment button.
            googlePayButton.isClickable = true
        }
    }
}

最佳答案

我最近遇到了同样的问题。我不想将代码添加到 Activity 中并生成丑陋、不可读的代码,所以我最终这样做了:

在您的可组合项中,将此代码添加到点击修饰符或其他内容中:

val task = paymentsClient.loadPaymentData(request)
task.addOnCompleteListener { completedTask ->
   if (completedTask.isSuccessful) {
      completedTask.result.let{
         //Do whatever you want
      }
   } else {
      when (val exception = completedTask.exception) {
         is ResolvableApiException -> {
            resolvePaymentForResult.launch(
                IntentSenderRequest.Builder(exception.resolution).build()
            )
         }
         is ApiException -> {
            Log.e("Google Pay API error", "Error code: ${exception.statusCode}, Message: ${exception.message}")
         }
         else -> {
            Log.e("Unexpected non API exception")
         }
      }
   }
}

其中 resolvePaymentForResult 为:

val resolvePaymentForResult = rememberLauncherForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) {
        result: ActivityResult ->
    when (result.resultCode) {
        RESULT_OK ->
            result.data?.let { intent ->
                PaymentData.getFromIntent(intent)?.let{
                   //Do whatever you want
                }
            }

        RESULT_CANCELED -> {
            // The user cancelled the payment attempt
        }
    }
}

如果您的架构也是如此,您可以随时将 paymentClient.loadPaymentData(request) 移至您的 ViewModel!

希望这能让你的代码更加简洁:)

关于android - Jetpack compose 中的 Google pay Api - 如何,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72341728/

相关文章:

android - Jetpack compose 中如何让懒惰的列项占据整个高度?

android - Jetpack Compose pointerInput detectTapGestures 设置onLongPress超时?

android - Phonegap + Jquery Mobile运行时从点击图标到主index.html

android - 无法完成 Activity

spring-boot - Spring Boot gradle多模块项目 Unresolved reference 错误

android - 如何使用 popUpToSaveState 和 restoreState 在导航组件 Android Kotlin 中保存和保持状态?

java - 不幸的是 MyApp 已经停止。我该如何解决这个问题?

android - 显示键盘修复底部框架布局

java - setOnItemClickListener“RecyclerView”的问题

android - 将 Compose 语义树打印到日志