【问题标题】:Swift & Stripe fetch payment method from customerSwift & Stripe 从客户那里获取付款方式
【发布时间】:2020-05-11 06:33:09
【问题描述】:

我正在尝试使用客户保存的条带付款方式进行付款,但我遇到了两个问题。

1)。我无法解码服务器端调用发送到应用程序的 JSON 响应并获取 Payment Method Id。我得到了完整的 JSON 响应,但是当我尝试打印出 ID 时,它返回 nil。

2)。如果用户保存了多种付款方式,我如何知道他们在解码 JSON 响应以获取 Payment Method Id 时打算使用哪一种?

预期结果是用户能够使用他们之前使用STPPaymentOptionsViewController 保存的已保存付款方式进行付款,但上述两个问题仍然存在。

服务器端:

exports.listUserSavedCards = functions.https.onRequest(async (req, res) => {

var customerId = req.body.customer_id

const paymentMethods = await stripe.paymentMethods.list({
  customer: customerId,
  type: 'card',
}).then(function(paymentMethods) {
  // asynchronously called
  return res.send(paymentMethods);
});
})

应用端:

func listUserSavedCards(customerId: String) {

    let URLString = "https://us-central1-example.cloudfunctions.net/" + "listUserSavedCards" as String

    var requestData : [String : String]? = [String : String]()
    requestData?.updateValue(customerId, forKey: "customer_id");

    submitDataToURL(URLString, withMethod: "POST", requestData: requestData!) { (jsonResponse, err) in
        if err != nil {
            print(err)
            return
        }
        else {

            let response = jsonResponse["id"]


        }
    }
}

JSON 响应:

["url": /v1/payment_methods, "object": list, "has_more": 0, "data": <__NSSingleObjectArrayI 
0x600002c46800>(
{
"billing_details" =     {
    address =         {
        city = "<null>";
        country = "<null>";
        line1 = "<null>";
        line2 = "<null>";
        "postal_code" = 4553;
        state = "<null>";
    };
    email = "<null>";
    name = "<null>";
    phone = "<null>";
};
card =     {
    brand = mastercard;
    checks =         {
        "address_line1_check" = "<null>";
        "address_postal_code_check" = pass;
        "cvc_check" = pass;
    };
    country = US;
    "exp_month" = 2;
    "exp_year" = 2021;
    fingerprint = OqzEjapFroTZ3Lqn;
    funding = credit;
    "generated_from" = "<null>";
    last4 = 4444;
    "three_d_secure_usage" =         {
        supported = 1;
    };
    wallet = "<null>";
};
created = 1588901399;
customer = "cus_HDdTb2Me8W6MUM";
  id = "pm_1GgL2JB7pjuLNBFRl48k0nyg";
  livemode = 0;
  metadata =     {
  };
  object = "payment_method";
  type = card;
}
)
]

提交数据到网址:

do {
      guard let url = URL(string: urlString) else {return};

      let defaultSession = URLSession(configuration: .default)

      var urlRequest = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 540)

      urlRequest.httpMethod = method;
      urlRequest.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")  // the request is JSON
      urlRequest.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept")        // the expected response is also JSON

      let httpBodyData : Data?

    try httpBodyData = JSONSerialization.data(withJSONObject: data, options: [.fragmentsAllowed]);

      urlRequest.httpBody = httpBodyData;

      let dataTask = defaultSession.dataTask(with: urlRequest, completionHandler: { (responseData, urlResponse, error) in

          if error == nil {
              do {
                let response = try JSONSerialization.jsonObject(with: responseData!, options: [.fragmentsAllowed]) as! [String : Any];
                  completion(response, nil);
              }
              catch {
                  print("Exception")
                  let response : [String : Any] = [String : Any]()
                  completion(response, error);
              }
          }
          else {
              let response : [String : Any] = [String : Any]()
              completion(response, error);
          }
      });

      dataTask.resume();
  }
  catch {
      print("Excetion in submitDataToURL")
  }
}

【问题讨论】:

    标签: swift stripe-payments


    【解决方案1】:

    paymentMethods.list 返回一个具有data 属性的对象,该属性包含一个 PaymentMethods 数组。在您的代码中,您可以通过以下方式访问它:

    jsonResponse["data"][0]["id]

    假设您在 submitDataToURL 函数中正确序列化 JSON 对象。

    【讨论】:

    • 我收到Value of type 'Any?' has no subscripts。如果您认为这可能导致问题,我已使用我的 submitDataToUrl 函数更新了我的问题。
    【解决方案2】:

    我使用下面的代码获取了Id

    let response = jsonResponse
    
    let results = response["data"] as? [[String: Any]]
    
    let firstDict = results?.first
    
    guard let id = firstDict?["id"] as? String else { return }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-23
      • 2015-03-01
      • 2021-03-26
      • 2014-08-04
      • 2014-12-29
      • 2022-01-21
      • 1970-01-01
      • 2019-11-11
      相关资源
      最近更新 更多