iOS应用通过Heroku对接Stripe支付返回502状态码错误该如何解决
问题分析与解决方法
核心错误点
1. 接口路径拼写错误
你在createPaymentIntent方法中拼接的后端接口路径存在拼写错误:
url?.appendPathComponent("create_paymrnt_intent")
此处的paymrnt为错误拼写,正确拼写应为payment,对应路径是create_payment_intent,和后端暴露的接口路径不匹配,导致Heroku无法找到对应接口返回502错误。
2. 加载逻辑写反
你在pay方法开头直接调用了self.stopLoading(),正确逻辑是发起支付请求前调用self.startLoading()开启加载动画,请求结束后再停止加载。
3. 缺少必要请求参数
调用创建支付意图接口时你传了空的参数字典,正常创建Stripe支付意图需要向后端传递金额、货币类型等必要参数,后端接收不到参数也会抛出异常导致502。
修正后核心代码示例
// 修正后的支付触发方法 @objc func pay(){ // 发起请求前开启加载 self.startLoading() self.createPaymentIntent{(paymentIntentResponse,error) in // 请求结束统一停止加载 self.stopLoading() if let error = error { self.diplayStatus(error.localizedDescription) print(error) return } guard let responseDictionary = paymentIntentResponse as? [String:AnyObject], let clientSecret = responseDictionary["secret"] as? String else { self.diplayStatus("后端返回数据格式错误") print("incorrect response") return } print(responseDictionary) // 后续补充调用Stripe确认支付的逻辑 } } // 修正后的创建支付意图方法 func createPaymentIntent(completion:@escaping STPJSONResponseCompletionBlock) { var url = URL(string: backendURL) // 修正路径拼写错误 url?.appendPathComponent("create_payment_intent") // 补充商品对应的金额、货币参数,示例为10.99美元对应1099美分 let params: [String: Any] = ["amount": 1099, "currency": "usd"] Alamofire.request(url as! URLConvertible,method:.post, parameters: params) .validate(statusCode: 200..<300) .responseJSON {(response) in switch(response.result) { case .failure(let error): completion(nil,error) case .success(let json): completion(json as? [String:Any], nil) } } }
额外排查建议
- 可直接用接口调试工具调用Heroku后端的
create_payment_intent接口,确认接口本身可以正常返回数据,排除后端逻辑错误 - 查看Heroku服务的运行日志,确认接口请求到达后端时的具体报错信息,可以更精准定位问题
内容的提问来源于stack exchange,提问作者askit
相关产品推荐
相关产品推荐

