从我的iOS应用程序中,我将Firebase调用为1)创建一个Stripe客户(这样可行,我得到一个有效的客户ID)2)获得短暂的密钥。
第二部分是事情失败的地方。我得到的错误看起来像这样:
message = "No such customer: \"cus_CFRA95y1cKuNH7\"";
param = customer;
requestId = "req_TKAARUJqcDqecK";
statusCode = 400;
type = "invalid_request_error";
由于我已成功创建并能够在信息中心中查看客户ID,因此我非常确信我的iOS应用中有正确的测试可发布密钥以及我的Firebase .js文件中的正确密钥。我确实有#34;查看测试数据"设置为" ON"在我的Stripe仪表板中。
如果你看下面的代码,你觉得这里有什么不对吗?
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客户标签显示我创建的客户帐户真的存在......
答案 0 :(得分:2)
使用 cus_CFRA95y1cKuNH7 ,而非 \" cus_CFRA95y1cKuNH7 \"
您的customerId之前和之后都不需要cus_CFRA95y1cKuNH7
。 Stripe需要的customerId看起来应该是\"cus_CFRA95y1cKuNH7\"
而不是您发送No such customer: cus_CFRA95y1cKuNH7;
。毕竟这应该有用。
错误消息应该看起来像"No such customer: \"cus_CFRA95y1cKuNH7\"";
而不是for errimg in anomalylist:
print (errimg)
showimg = image.load_img(errimg, target_size=(224, 224))
plt.imshow(showimg)