Ios 应用程序创建条带客户,但可以';由于“无法获取临时密钥”;“没有这样的客户”;

Ios 应用程序创建条带客户,但可以';由于“无法获取临时密钥”;“没有这样的客户”;,ios,node.js,stripe-payments,stripe.js,Ios,Node.js,Stripe Payments,Stripe.js,从我的iOS应用程序中,我打电话给Firebase,1)创建一个条带客户(这样做很有效,我得到了一个外观有效的客户ID),2)获得临时密钥 第二部分是失败的地方。我返回的错误如下所示: message = "No such customer: \"cus_CFRA95y1cKuNH7\""; param = customer; requestId = "req_TKAARUJqcDqecK"; statusCode = 400; type = "invalid_request_error";

从我的iOS应用程序中,我打电话给Firebase,1)创建一个条带客户(这样做很有效,我得到了一个外观有效的客户ID),2)获得临时密钥

第二部分是失败的地方。我返回的错误如下所示:

message = "No such customer: \"cus_CFRA95y1cKuNH7\"";
param = customer;
requestId = "req_TKAARUJqcDqecK";
statusCode = 400;
type = "invalid_request_error";
因为我成功地创建并能够在仪表板中查看客户ID,所以我非常确信我在iOS应用程序中拥有正确的测试可发布密钥,在Firebase.js文件中拥有正确的密钥。在我的仪表板中,我确实将“查看测试数据”设置为“打开”

如果你仔细阅读下面的代码,你会发现这里有什么错误吗

index.js

const functions = require('firebase-functions');
const stripe_key = "sk_test_y1otMY_SECRET_KEY"
var stripeFire = require("stripe-fire")(stripe_key);

// The Firebase Admin SDK to access the Firebase Realtime Database. 
const admin = require('firebase-admin');
var stripe = require('stripe')(stripe_key);
admin.initializeApp(functions.config().firebase);

exports.newCustomer = functions.https.onRequest((req, res) => {
    console.log("Creating new customer account...")
    var body = req.body

    stripe.customers.create(
        { email: body.email }
    ).then((customer) => {
          console.log(customer)
          // Send customerId -> Save this for later use
          res.status(200).json(customer.id)
    }).catch((err) => {
           console.log('error while creating new customer account' + err)
           res.status(400).send(JSON.stringify({ success: false, error: err }))
    });
});

// Express
exports.StripeEphemeralKeys = functions.https.onRequest((req, res) => {
  const stripe_version = req.body.api_version;
  const customerId = req.body.customerId
  if (!stripe_version) {
    console.log('I did not see any api version')
    res.status(400).end()
    return;
  }

  stripe.ephemeralKeys.create(
    {customer: customerId},
    {stripe_version: stripe_version}
  ).then((key) => {
     console.log("Ephemeral key: " + key)
     res.status(200).json(key)
  }).catch((err) => {
    console.log('stripe version is ' + stripe_version + " and customer id is " + customerId + " for key: " + stripe_key + " and err is " + err.message )
    res.status(500).json(err)
  });
});
在Swift端,在MyAPIClient.Swift中:

func createNewCustomer(withAPIVersion apiVersion : String, completion: @escaping STPJSONResponseCompletionBlock)
{
    // using our Facebook account's e-mail for now...
    let facebookDictionary = FacebookInfo.sharedInstance.graphDictionary
    if let facebookemail = facebookDictionary["email"] as? String {

        guard let key = Stripe.defaultPublishableKey() , !key.contains("#") else {
            let error = NSError(domain: StripeDomain, code: 50, userInfo: [
                NSLocalizedDescriptionKey: "Please set stripePublishableKey to your account's test publishable key in CheckoutViewController.swift"
                ])

            completion(nil, error)

            return
        }
        guard let baseURLString = self.baseURLString, let baseURL = URL(string: baseURLString) else {

            print("something broken... what should I do?")
            // how about some kind of error in the second parameter??
            completion(nil, nil)

            return
        }

        let path = "newCustomer"
        let url = baseURL.appendingPathComponent(path)
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        let parameters = ["email" : facebookemail]
        do {
            request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
        } catch let error {
            print("error while serialization parameters is \(error.localizedDescription)")
        }

        let task = self.session.dataTask(with: request) { (data, urlResponse, error) in

            if let actualError = error {
                print("error from createNewCustomer API is \(actualError)")
            }

            if let httpResponse = urlResponse as? HTTPURLResponse {
                print("httpResponse is \(httpResponse.statusCode)")

                if (httpResponse.statusCode == 200)
                {
                    // eventually we'll want to get this into an actual complex JSON response / structure
                    if let actualData = data
                    {
                        if let customerIDString = String(data: actualData, encoding: .utf8) {
                            print("customer id string is \(customerIDString)")

                            let defaults = UserDefaults.standard

                            let originalcustomerid = defaults.string(forKey: "CustomerID")
                            if customerIDString != originalcustomerid
                            {
                                defaults.set(customerIDString, forKey: "CustomerID")
                                defaults.set(facebookemail, forKey: "CustomerEmail")
                            }
                        }
                    }
                    self.createCustomerKey(withAPIVersion: apiVersion, completion: completion)
                }
            } else {
                assertionFailure("unexpected response")
            }
        }
        task.resume()
    }
}

func createCustomerKey(withAPIVersion apiVersion: String, completion: @escaping STPJSONResponseCompletionBlock)
{
    // first, let's see if we have a valid customer ID for the facebook e-mail we're using

    if weHaveCustomerIDSaved() == false
    {
        createNewCustomer(withAPIVersion: apiVersion, completion: completion)
        return
    }

    guard let key = Stripe.defaultPublishableKey() , !key.contains("#") else {
        let error = NSError(domain: StripeDomain, code: 50, userInfo: [
            NSLocalizedDescriptionKey: "Please set stripePublishableKey to your account's test publishable key in CheckoutViewController.swift"
            ])

        completion(nil, error)

        return
    }
    guard let baseURLString = baseURLString, let baseURL = URL(string: baseURLString) else {

        print("something broken... what should I do?")
        // how about some kind of error in the second parameter??
        completion(nil, nil)

        return
    }

    let defaults = UserDefaults.standard

    if let customerid = defaults.string(forKey: "CustomerID")
    {
        let path = "StripeEphemeralKeys"
        let url = baseURL.appendingPathComponent(path)
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        let parameters = ["api_version" : apiVersion, "customerId" : customerid]
        do {
            request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
        } catch let error {
            print("error while serialization parameters is \(error.localizedDescription)")
        }

        let task = self.session.dataTask(with: request) { (data, urlResponse, error) in

            if let httpResponse = urlResponse as? HTTPURLResponse {
                print("httpResponse is \(httpResponse.statusCode)")
            } else {
                assertionFailure("unexpected response")
            }

            if let actualError = error {
                print("error from EphemeralKey API is \(actualError)")
            }

            DispatchQueue.main.async {
                do {
                    if let actualData = data
                    {
                        if let json = try JSONSerialization.jsonObject(with: actualData) as? [AnyHashable : Any]
                        {
                            print("json is \(json)")
                            completion(json, nil)
                        }
                    }
                } catch let error {
                    print("error from json \(error.localizedDescription)")
                }
            }
        }
        task.resume()
    }
}
这是我的Firebase仪表盘

还有我的Stripe customer选项卡,显示我创建的客户帐户确实存在

最后,这里是一个典型的临时密钥事务的日志:

使用cus\u CFRA95y1cKuNH7,而不是\“cus\u CFRA95y1cKuNH7\”

您不需要在customerId之前和之后使用
\“
。Stripe需要的customerId应该看起来像
cus\u CFRA95y1cKuNH7
,而不是您发送
\“cus\u CFRA95y1cKuNH7\”
。这终究会起作用


错误消息应类似于
无此类客户:cus\u CFRA95y1cKuNH7;
“无此类客户:\“cus\u CFRA95y1cKuNH7\”";

index.js看起来不错……我会设置一个简单的node.js脚本,创建一个客户,然后尝试生成临时密钥,只是为了检查服务器端正在做它应该做的事情。您的问题似乎是密钥不匹配,或者您创建了一个客户并立即要求创建临时密钥,而stripe存在缓存/其他问题。我猜你也可以在仪表板上查看请求id。@BrianPutt谢谢你的快速关注。我无法想象这是一个关键的不匹配,因为新的客户id已经成功创建。当我在60多秒后启动应用程序时,我之前保存了客户id,它绕过了新帐户的创建,仍然在Firebase控制台中获得“无此类客户”行,即使这些值在我看来都非常有效。我确实编辑了这个问题,以便在条带日志中显示请求输入和输出。@MichaelDautermann您是如何创建这个if语句的。如果weHaveCustomerIDSaved()==false{createNewCustomer(带apiVersion:apiVersion,完成:完成)返回}。我正在尝试重新创建您的代码,但我不断收到此weHaveCustomerIDSaved()的错误。一开始我以为它只是一个BoolHi@Markinson函数——这个函数基本上是看我以前是否将客户ID保存到UserDefaults中。是的,这就是问题所在(也就在我面前)。我需要弄清楚报价是如何进入我正在保存的客户id的,但现在我只是将它们从发送给Firebase/Stripe的字符串中剥离出来。