Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stripe cannot create Ephemeral Key

I am making an iOS project which uses Stripe. I am using a STPCustomerContext and the parameter to create an instance is an object of MainAPI below. When I create the instance, it automatically calls createCustomerKey() but an error (404) is throwing. The URL is "http://localhost:1337/ephemeral_keys" and I believe that is what I have everywhere but yet it is throwing a 404. Here is the code for MainAPI.swift, index.js, & api.js.

The code is:

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 + '.');
});

When I create a STPCustomerContext (like this):

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

The following error prints (not allowing the STPPaymentContext later to display):

Response status code was unacceptable: 404.
like image 305
Ryan Cocuzzo Avatar asked Nov 30 '17 00:11

Ryan Cocuzzo


Video Answer


1 Answers

Please try with the below nodejs code, because syntax which your code is using might not be correct, I was using the same code as you, but later changed the implementation & deployed to 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);
   });   
});

You might get below kind of logs.

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

For .swift file

Please Click here

like image 157
Nasir Avatar answered Oct 17 '22 01:10

Nasir