Android集成Stripe支付遇NullPointerException问题求助
错误核心原因
你遇到的NullPointerException是因为调用paymentFlow()时,EphericalKey还没被赋值——getEmphericalKey()是异步网络请求,按钮点击后立刻执行paymentFlow(),此时请求还没完成,EphericalKey还是null,导致构造PaymentSheet.CustomerConfiguration时传入了非空要求的null参数。
具体修复步骤
1. 修正异步请求顺序,确保参数就绪后再触发支付
把paymentFlow()的调用移到getClientSecret()的回调里,等ClientSecret、CustomerId、EphemeralKey都获取完成后再启动支付流程:
// 修改按钮点击事件 payment.setOnClickListener(new View.OnClickListener(){ public void onClick(View view){ // 只触发密钥获取,支付流程在回调里启动 getEmphericalKey(); } }); // 修改getClientSecret的回调逻辑 private void getClientSecret(String customerId, String ephemeralKey){ StringRequest request = new StringRequest(Request.Method.POST, "https://api.stripe.com/v1/payment_intents", new Response.Listener<String>() { @Override public void onResponse(String response) { try{ JSONObject object = new JSONObject(response); ClientSecret = object.getString("client_secret"); Toast.makeText(MoneyDonation2.this, ClientSecret, Toast.LENGTH_SHORT).show(); // 所有参数就绪,触发支付流程 paymentFlow(); } catch (JSONException e) { e.printStackTrace(); } } }, ...); // 其他代码保持不变 }
2. 修正Ephemeral Key的获取字段
Stripe的Ephemeral Key需要取secret字段,不是id,修改getEmphericalKey()里的赋值逻辑:
EphericalKey = object.getString("secret"); // 替换原来的object.getString("id")
3. 修复参数传递错误
getEmphericalKey()和getClientSecret()里的参数把变量名写成了字符串"CustomerId",要传实际的变量值:
// getEmphericalKey里的params params.put("customer", CustomerId); // 去掉引号,传递变量值 // getClientSecret里的params params.put("customer", CustomerId); // 同样去掉引号
4. 修正货币代码
Stripe要求使用标准ISO 4217货币代码,马来西亚林吉特的正确代码是MYR,不是RM:
params.put("currency", "MYR");
5. (可选)修正变量拼写规范
把EphericalKey改成EphemeralKey(拼写错误,不影响运行但更规范):
String EphemeralKey; // 替换原来的EphericalKey // 所有用到该变量的地方同步修改
额外重要提醒
绝对不要在客户端直接暴露Stripe的SecretKey!这是严重的安全风险,所有需要SecretKey的请求(创建Customer、Ephemeral Key、Payment Intent)都应该放在你的后端服务中,客户端只调用自己的后端接口获取必要的参数(比如CustomerId、EphemeralKey、ClientSecret)。
内容的提问来源于stack exchange,提问作者user19914311

