Android集成Stripe Payment Sheet报错:无效API密钥问题
问题解决:Stripe Payment Sheet弹出后立即关闭,报AuthenticationException
问题根源
报错Invalid API Key provided: ephkey_1 Jpgh的核心原因是:你传入Payment Sheet的临时密钥(ephemeral key)格式错误。当前代码用Customermodel接收临时密钥的API响应,错误地取了id字段(格式为ephkey_xxx),但Stripe要求临时密钥必须使用响应中的secret字段(格式为ek_test_xxx)。
修复步骤
1. 创建临时密钥专属数据模型
新增EphemeralKeyModel.kt,用于正确解析临时密钥的API响应:
package com.example.gps_kotlin.Registration.Stripe.models data class EphemeralKeyModel( val secret: String )
2. 修改API接口的返回类型
更新API_interface.kt中getEphermal方法的返回值,替换为新的模型:
@Headers("Authorization: Bearer $SECRET_KEY","Stripe-Version: 2023-10-16") @POST("v1/ephemeral_keys") suspend fun getEphermal( @Query("customer") customer : String ) : Response<EphemeralKeyModel>
3. 修正临时密钥的获取逻辑
在StripePaymentGateway.kt的getEphermaralKey方法中,改为读取secret字段赋值:
private fun getEphermaralKey(customerId : String) { lifecycleScope.launch(Dispatchers.IO) { val res = apiInterface.getEphermal(customerId) withContext(Dispatchers.Main){ if(res.isSuccessful && res.body() != null) { // 替换为读取secret字段,而非id ephemeral = res.body()!!.secret getPaymentIntent(customerId,ephemeral ) } } } }
额外注意事项
- 确保Stripe API版本(2023-10-16)与客户端SDK版本兼容,避免版本不匹配引发隐性错误
- 验证
clientSecret是否正确获取,Payment Sheet需要有效的支付意图密钥才能正常加载
内容的提问来源于stack exchange,提问作者Darshan Shetty
相关产品推荐
相关产品推荐

