Stripe cannot create Ephemeral Key - javascript

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.

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

Please have a look at https://www.youtube.com/watch?v=NdszUvzroxQ
I believe you need to use some remote server, instead of local server,
In my Swift file I am using .responseString instead of .responseJSON by this is I am getting success but the response is a HTML file of requesting Google Signin

Related

Koa.js request-promise return [ The property , ' ' , in the request body is invalid ]

I try to post json to Line' messaging api with koa.js and request-promise but got error as attached image :
I'm using heroku with koa.js to connect with Line messaging api.
Here is my code :
const Koa = require('koa');
const Router = require('koa-router');
const logger = require('koa-logger');
const bodyParser = require('koa-bodyparser');
const app = new Koa();
const router = new Router();
const port = process.env.PORT || 4000;
app.use(logger());
app.use(bodyParser());
app.on('error', (err, ctx) => {
console.log('server error', err, ctx)
});
app.use(router.routes());
app.use(router.allowedMethods());
router
.get('/', (ctx, next) => {
console.log(ctx);
ctx.body = ctx;
})
.post('/webhook', async (ctx, next) => {
var reply_Token = ctx.request.body.events[0].replyToken;
console.log('token = ' , ctx.request.body.events[0].replyToken);
var rp_body = JSON.stringify({
replyToken: reply_Token,
messages: [{
type: 'text',
text: 'Hello'
},
{
type: 'text',
text: 'How are you?'
}]
});
var options = {
method: 'POST',
url: 'https://api.line.me/v2/bot/message/reply',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer {xxxxxxxx}'
},
json: true,
body: rp_body
};
var rp = require('request-promise');
rp(options)
.then(function (parsedBody){
console.log('rq success');
})
.catch(function (err) {
console.log('server error', err, ctx);
});
});
app.listen(port);
module.exports = { app }
After try to solving with changing variable but seem doesn't work at all. This is what I try to adapt from using Node.Js to Koa.js.
Solving the problems!, thanks to #num8er for pointing to it.
As the body entity has 'json : true' so the body is already stringify by this. There's no need to do stringify before.
So removing it like :
var rp_body = JSON.stringify({
replyToken: reply_Token,
messages: [{
to
var rp_body = ({
replyToken: reply_Token,
messages: [{
However after pull off stringify from body you might encounter 'Invalid Token' if process api.line.me verification.
It's what it should be, because api.line.me will throw zeros as reply token for verification and Koa.js look at it like an error.
So checking for if token is zeros then send status 200 to complete the verification, otherwise do the POST METHOD if token is not zeros.
if(reply_Token === '00000000000000000000000000000000') {
ctx.status = 200;
} else {
//POST METHOD
}

How can I send the fields in the json body in a parametric way to node js api?

The rest api I use with express js below sends an electronic signature request to the defined user mail. He makes this request with his email address in the json body. The e-mail addresses to be sent may be different. How can I send the email_address and name fields in the opts body in a parametric way to api? The main problem I have is how do I send the parameters of email_address and name to json body parametrically. I don't want to send hard coded.
Express JS API:
const express = require('express');
const router = express.Router();
const hellosign = require('hellosign-sdk')({ key: 'key123' });
const fs = require('fs');
hellosign.account.update({
callback_url: process.env.HOST_URL+'api/callback'
}).then((res) => {
// handle response
console.log("--- sign res ---");
console.log(res);
}).catch((err) => {
// handle error
console.log(err)
});
router.post('/sign',(req,res)=>{
res.send('Sign request is called');
const opts = {
test_mode: 1,
title: 'PDF Sign via Node Server',
subject: 'PDF Sign via Node Server',
message: 'Please sign this pdf.',
signers: [
{
email_address: 'example#gmail.com',
name: 'Mr Okoreni'
}
],
files: ['nda.pdf']
};
hellosign.signatureRequest.send(opts).then((res) => {
// handle response
console.log(res);
}).catch((err) => {
// handle error
console.log(err)
});
});
router.post('/callback',(req,res)=>{
res.send('Hello API Event Received');
console.log('callback request is called');
try{
res.send(res.data);
console.log(res.data);
console.log(res.body);
}catch (e) {
console.log(e)
}
});
router.get('/download/',(req,res)=>{
res.send('download request is called');
try {
console.log('download request is called');
var signatureRequestId = 'sign123';
hellosign.signatureRequest.download(signatureRequestId, { file_type: 'zip' }, (err, res) => {
const file = fs.createWriteStream("./downloads/"+signatureRequestId+"files.zip");
res.pipe(file);
file.on('finish', () => {
file.close();
console.log("finish");
});
});
}catch (e) {
console.log(e);
}
});
router.get('/', (req, res) => {
res.send("Server is listening...")
});
module.exports = router;
Totally depends where you're getting the parameterised fields from
From the request..
const opts = {
test_mode: 1,
title: 'PDF Sign via Node Server',
subject: 'PDF Sign via Node Server',
message: 'Please sign this pdf.',
signers: [
{
email_address: req.email_address,
name: req.name,
},
],
files: ['nda.pdf'],
}

FCC - Glitch problem. Cannot get req.body

Problem is that in my second post request I cannot get req.body. Neither console.log nor req.body show something.
In the first post request, everything seems to work just fine. And it was also working before I start to re-arrange code. I even change the type of the reply to send, but receiving the old message (status ok).
I do not understand what's going on. Any help, please?
Glitch: https://uatyroni-exercise-tracker.glitch.me - live app
code: https://glitch.com/~uatyroni-exercise-tracker
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const shortid = require('shortid');
const cors = require("cors");
//Setting MongoDB
const mongoose = require("mongoose");
mongoose.connect(process.env.MONGO_URI);
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static("public"));
app.get("/", (req, res) => {
res.sendFile(__dirname + "/views/index.html");
});
//Defining Schema & Model
let Schema = mongoose.Schema;
let userSchema = new Schema({
id: { type: String, unique: true, default: shortid.generate },
user: String,
exercise: [{
description: String,
duration: Number,
date: {}
}]
});
let userModel = mongoose.model("Users", userSchema);
let exerciseSchema = new Schema({
userId: String,
description: String,
duration: Number,
date: String
});
let exerciseModel = mongoose.model("Exercies", exerciseSchema);
//THE POST PROCESS
app.post("/api/exercise/new-user", (req, res) => {
let userName = req.body.username;
let userNew = new userModel({ user: userName });
userModel
.find()
.exec()
.then(data => {
data = data.filter(obj => obj["user"] === userName);
console.log("I am the data: " + data);
if (data.length === 0) {
userNew
.save()
.then(result => {
res.json(result);
})
.catch(err => {
console.log(err);
res.json({ error: err });
});
} else {
res.json({ Error: "User is already registered in the database" });
}
});
});
app.post("/api/exercise/add", (req, res) => {
console.log('reqbody is: ' + req.body.description)
let newDate = '';
if (req.body.date == '') {
newDate = new Date().getFullYear() + '-' + new Date().getMonth() + '-' + new Date().getDate();
}
let newExercise = {
description: req.body.description,
duration: req.body.duration,
date: newDate
}
userModel.findById(req.body.userid, (err, data) => {
if (data.length == null)
res.json({
error: "User is not registered. Please register a user first."
});
else {
res.json(data)
}
});
});
// Not found middleware
app.use((req, res, next) => {
return next({ status: 404, message: "not found" });
});
// Error Handling middleware
app.use((err, req, res, next) => {
let errCode, errMessage;
if (err.errors) {
// mongoose validation error
errCode = 400; // bad request
const keys = Object.keys(err.errors);
// report the first validation error
errMessage = err.errors[keys[0]].message;
} else {
// generic or custom error
errCode = err.status || 500;
errMessage = err.message || "Internal Server Error";
}
res
.status(errCode)
.type("txt")
.send(errMessage);
});
const listener = app.listen(process.env.PORT || 4000, () => {
console.log("Your app is listening on port " + listener.address().port);
});

Unable to use the Request Body from POST

I'm trying to develop api with node.js express api for my angular web front end.This code worked when I used the params (http://localhost:5000/login/admin/00606006350066500673 ).
But I don't know why I'm getting an error while using the Request raw body data ({ strUserID: "admin" , strUserPwd: "00606006350066500673"})
router.post('/login', function (req, res, next) {
let User = {
strUserID : req.body.strUserID,
strUserPwd : req.body.strUserPwd };
function getUserPwd(strUID){
var sqlConfig = {
user: 'sa',
password: 'XXXXX',
server: 'XXXXXXXXXXXXXX.us-east-2.rds.amazonaws.com',
database: 'XXXXX'
};
sql.connect(sqlConfig, function () {
var request = new sql.Request();
var strquery = "select fUserPwd from tblUser where fUserID ='"+User.strUserID+"'"
request.query(strquery, function (err, recordset) {
return(recordset);
});
sql.close();
});
}
if ( User.strUserPwd == getUserPwd(User.strUserID)) {
let token = jwt.sign(User, global.config.secretKey, {
algorithm: global.config.algorithm,
expiresIn: '15m'
});
console.log("Token Generated : "+ token + User );
res.status(200).json({
token , User
});
}
else {
res.status(401).json({
message: 'Login Failed'
});
}
});

session management for multiple concurrent users in node+express js

I am trying to login as admin using mobile device and after successful login, I am setting cookie in response header. Mean while, when I try to access routes from other device(laptop), I get all admin access from other device.
How do I maintain session for multiple users ?
Also the problem is I am trying to maintain the view state in global object(login/logout button based on if user in logged-in or not) which get lost with server-side rendering.
I mean all the JavaScript variable data(DataMixin object in my case) is lost.
How to develop isomorphic riotjs app? See similar issue fixed in reactJs: https://github.com/reactjs/react-chartjs/issues/57
State:
document.addEventListener('DOMContentLoaded', function (e) {
DataMixin = { //Global object
setAuthentication: function(){
if(arguments[0] != null){
localStorage.setItem('role', arguments[0][0]);
localStorage.setItem('loginStatus', arguments[0][1]);
}
},
getRole: function(){
return localStorage.getItem('role');
},
}
}
View:
ADMIN LOGIN
<li if="{DataMixin.getRole() == 'ROLE_ADMIN'}">
<a onclick="{logout}">LOGOUT</a>
</li>
Loading pages from server-side using node+express:
function urlDataApiResponse(url, params, req, res) {
swig = require('swig');
var header_tag = require('./public_html/tags/header_tag.tag');
var blog_post_details_tag = require('./public_html/tags/blog_post_details.tag');
var footer_tag = require('./public_html/tags/footer_tag.tag');
var blog_sidebar_tag = require('./public_html/tags/blog_sidebar.tag');
var slide_menu_tag = require('./public_html/tags/slide_menu.tag');
app.engine('html', swig.renderFile);
app.set('view engine', 'html');
app.set('views',__dirname + '/public_html/tags/');
var postDetails = {};
console.log('url inside getApiResponse ', url);
var options = {
method: 'GET',
uri: url,
qs: params,
headers: {
'User-Agent': 'Request-Promise'
},
json: true // Automatically parses the JSON string in the response
};
rp(options)
.then(function (response) {
createJWT(req,res);
var postDetails, categories, blog_sidebar_tag_rendered, slide_menu_tag_rendered,
header_tag_rendered, blog_tag_rendered, footer_tag_rendered;
postDetails = (response[0].attributes);
console.log('.............................................................');
console.log('.............SERVER-SIDE-RENDERING:START.....................');
console.log('.............................................................');
header_tag_rendered = riot.render(header_tag, {role: storage.getItemSync('role'), loginStatus: storage.getItemSync('loginStatus') });
slide_menu_tag_rendered = riot.render(slide_menu_tag, {role: storage.getItemSync('role'), loginStatus: storage.getItemSync('loginStatus') });
blog_tag_rendered = riot.render(blog_post_details_tag, {details: postDetails, role: storage.getItemSync('role')});
blog_sidebar_tag_rendered = riot.render(blog_sidebar_tag);
footer_tag_rendered = riot.render(footer_tag);
var meta_details = {
postImageUrl: postDetails.userImage,
title: postDetails.title + " - Rootscopeit.in",
description: postDetails.details.substring(0,200)+"...",
details: postDetails.details,
url: postDetails.url
};
res.render('blog_post_details', {
open_graph: meta_details,
header_details: header_tag_rendered,
slide_details: slide_menu_tag_rendered,
article_details: blog_tag_rendered,
sidebar_details: blog_sidebar_tag_rendered,
footer_details: footer_tag_rendered});
console.log('............................................................');
console.log('............SERVER-SIDE-RENDERING:END.......................');
console.log('............................................................');
})
.catch(function (err) {
console.log('=================================');
console.error('POST error ', err.stack);
console.log('=================================');
return res.status(res.statusCode).send(err);
});
}
Setting cookie in passport js:
//==============
//TOKEN CREATION
//==============
function createJWT(req, res){
var claims = {
sub: 'Social Authentication',
iss: 'https://rootscopeit.in',
};
var jwt = nJwt.create(claims, secretKey);
jwt.setExpiration(new Date().getTime() + (60 * 60 * 1000 * 1)); // One hour from now
var token = jwt.compact();
var cookies = new Cookies(req, res).set('access_token', token, {
//httpOnly: true,
//secure: true // for your production environment
});
}
//=======================================
//===Google Authentication
//=======================================
var passport = require('passport');
var GoogleStrategy = require('passport-google-oauth20').Strategy;
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function (user, done) {
done(null, user);
});
passport.deserializeUser(function (obj, done) {
var user = USERS[id];
done(null, user);
});
app.get('/auth/google', passport.authenticate('google',
{scope: ['profile', 'https://www.googleapis.com/auth/plus.login',
'https://www.googleapis.com/auth/plus.profile.emails.read',
'https://www.googleapis.com/auth/blogger']}));
app.get('/auth/google/callback', passport.authenticate('google', {failureRedirect: '/', failureFlash: true}),
function (req, res) {
console.log('success authentication');
createJWT(req,res);
res.send(popupTools.popupResponse(req.user));
}
);

Categories

Resources