条纹无法创建临时密钥

时间:2017-11-30 00:23:10

标签: javascript node.js swift stripe-payments stripe.js

我正在制作一个使用Stripe的iOS项目。我正在使用STPCustomerContext,创建实例的参数是下面的MainAPI的对象。当我创建实例时,它会自动调用createCustomerKey(),但会抛出错误(404)。这个网址是“http://localhost:1337/ephemeral_keys”,我相信这就是我到处都有的但它却抛出了404.这是MainAPI.swift,index.js和&的代码。 api.js。

代码是:

MainAPI.swift

class MainAPI:NSObject, STPEphemeralKeyProvider {

 //   override init(){}

    static let shared = MainAPI()

    var baseURLString = Constants.BASE_URL



    // MARK: STPEphemeralKeyProvider

    enum CustomerKeyError: Error {
        case missingBaseURL
        case invalidResponse
    }
    func createCustomerKey(withAPIVersion apiVersion: String, completion: @escaping STPJSONResponseCompletionBlock) {

        // the request

        func request(id: String) {
            print("creating a eph key request with customerId: \(id)") // good
            let url = self.baseURLString.appending("/ephemeral_keys")

            Alamofire.request(url, method: .post, parameters: [
                "api_version": apiVersion,
                "customerId": id
                ])
                .validate(statusCode: 200..<300)
                .responseJSON { responseJSON in

                    switch responseJSON.result {
                    case .success(let json):
                        print("created customer ephemeral key!")
                        completion(json as? [String: AnyObject], nil)
                    case .failure(let error):
                        print("could not customer ephemeral key!\n Error info: ")
                        print(error.localizedDescription)
                        completion(nil, error)

                    }

            }
        }


        print("attempting to create customer ephemeral key . . .(createCustomerKey())")

         let customerId = . . . // get customer id
         request(id: costumerId) // this passes on the CORRECT customerId each time

    }


}

api.js

var express = require('express')
var router = express.Router()

var stripe_key = process.env.STRIPE_KEY || "sk_test_myTestKey"
var stripe = require('stripe')(stripe_key);
var request = require("request-promise-native")

//API
router.get('/', function (req, res) {
  res.status(200).send(JSON.stringify({ message: 'API Gateway', success: true, error: null }));
}) // Just for testing, just for error-handling

//1. Create a customer account
router.post('/new_customer', function (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).send(JSON.stringify({ success: true, error: null, customerId: customer.id }));
    })
    .catch((err) => {  
      console.log(err)
      res.status(400).send(JSON.stringify({ success: false, error: err }))
    });
})

//2. Save Credit Card with token
router.post('/new_card', function (req, res) {
  var customerId = req.body.customerId
  var token = req.body.token

  stripe.customers.update(customerId, { source: token })
    .then((customer) => {
      console.log(customer)
      res.status(200).send(JSON.stringify({ success: true, error: null }));
    })
    .catch((err) => {  
      console.log(err)
      res.status(400).send(JSON.stringify({ success: false, error: err }))
    });

})

//3. Use customerId to post a charge
router.post('/new_charge', function (req, res) {
  var customerId = req.body.customerId
  var amount = req.body.amount
  var source = req.body.source
  stripe.charges.create({
    amount: amount,           //in cents
    currency: "usd",
    customer: customerId,      //CUSTOMER_STRIPE_ACCOUNT_ID
    source: source, // obtained with Stripe.js
  }).then((charge) => {
    res.status(200).send(JSON.stringify({ message: 'Sucess.', success: true, error: null }));
  }).catch((error) =>{
    res.status(400).send(JSON.stringify({ message: 'Error', success: false, error: error }));
  })
})

// here is the error I am assuming
router.post('/ephemeral_keys', (req, res) => {
  const stripe_version = req.body.api_version;
  var customerId = req.body.customerId;

  if (!stripe_version) {
    res.status(400).end();
    return;
  }
  console.log(stripe_version)
  // This function assumes that some previous middleware has determined the
  // correct customerId for the session and saved it on the request object.
  stripe.ephemeralKeys.create(
    {customer: customerId},
    {stripe_version: stripe_version}
  ).then((key) => {

    console.log("Ephemeral key: " + key)
    res.status(200).json(key);
    res.status(200).send(JSON.stringify({ message: 'AAAAhh', success: true, error: null }));
  }).catch((err) => {
    console.log("Ephemeral key error: " + err)
    res.status(200).send(JSON.stringify({ message: 'ABBBBBB', success: true, error: null }));
    res.status(500).end();
  });
});

module.exports = router;

index.js

//Environment Vars
var uri = process.env.NODE_ENV || "development"
console.log(uri + " environment")

//Express App
var express = require('express');
var app = express();

//Api for reading http post request body in express
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json())

//Log Connections
app.use(function timeLog (req, res, next) {
  console.log('incoming connection . . . ')
  next()
})

//API middelware
var api = require('./api')
app.use('/api', api)

app.get('/', function (req, res) {
  res.status(200).send(JSON.stringify({ message: 'Welcome!', success: true, error: null }));
}); 

//Create Server
var port = process.env.PORT || 1337;
var httpServer = require('http').createServer(app);
httpServer.listen(port, function () {
  console.log('server running on port ' + port + '.');
});

当我创建一个STPCustomerContext(像这样)时:

    let apiKeyObject = MainAPI.shared
    customerContext = STPCustomerContext(keyProvider: apiKeyObject)

打印以下错误(稍后不允许显示STPPaymentContext):

Response status code was unacceptable: 404.

2 个答案:

答案 0 :(得分:2)

请尝试使用下面的nodejs代码,因为您的代码使用的语法可能不正确,我使用的代码与您相同,但后来更改了实现&amp;部署到firebase CLI

exports.createEphemeralKeys = functions.https.onRequest((req, res) => {
var api_version = req.body.api_version;
var customerId = req.body.customerId;

if (!api_version) {
   res.status(400).end();
   return;
}

 stripe.ephemeralKeys.create(
    { customer: customerId },
    { stripe_version: api_version }, 

   function(err, key) {
     return res.send(key);
   });   
});

你可能会得到以下类型的日志。

 { 
 id: 'ephkey_1BramAFjruqsvjkVQGdZLiV5',
 object: 'ephemeral_key',
 associated_objects: [ { type: 'customer', id: 'cus_CEPMtLbshv7EaP' } ],
 created: 1517701830,
 expires: 1517705430,
 livemode: false,
 secret: 'ek_test_YWNjdF8xQmxUb0FGanJ1cXN2amtWLHVPcUdMN3d4UEhncW1sQkNJYmlOdzhwUGdjVUxOd1Y' 
 }

对于.swift文件

Please Click here

答案 1 :(得分:0)

请查看https://www.youtube.com/watch?v=NdszUvzroxQ

我认为你需要使用一些远程服务器,而不是本地服务器,

在我的Swift文件中,我使用的是.responseString而不是.responseJSON,因为我得到了success,但响应是请求 Google Signin