I'm trying to setup a subscription service using React on the Frontend, and Node on the Backend. As of now, I've only had success passing the token.id that is generated from this.props.stripe.createToken. The problem I'm having is sending additional info about the customer to my server. How can I pass additional data from the frontend to the server?
I understand that
body: JSON.stringify({ token: token.id, email: 'xxx' })
helps me submit more data, but how do I extract that info on the server-side? If I console.log(req.body), an empty object is returned
Solved
I only had BodyParser processing text, when I really wanted it to be processing JSON. Adding app.use(bodyParser.json());
fixed it. No more empty req.body!!!
Frontend
import React, { Component } from 'react';
import { CardElement, injectStripe } from 'react-stripe-elements';
class CheckoutForm extends Component {
constructor(props) {
super(props);
this.state = { complete: false };
this.submit = this.submit.bind(this);
}
async submit(ev) {
let { token } = await this.props.stripe.createToken({ name: 'Bobby' });
console.log(token);
let response = await fetch('/charge', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token: token.id, email: 'xxx' })
});
if (response.ok) console.log('Purchase Complete!');
if (response.ok) this.setState({ complete: true });
}
render() {
if (this.state.complete) return <h1>Purchase Complete</h1>;
return (
<div className="checkout">
<p>Would you like to complete the purchase?</p>
<CardElement />
<button onClick={this.submit}>Send</button>
</div>
);
}
}
export default injectStripe(CheckoutForm);
Backend
const app = require('express')();
const stripe = require('stripe')('sk_test_vXWqlxlbpuHTqQgGIUtqOa9c');
const bodyParser = require('body-parser');
app.use(bodyParser.text());
app.use(bodyParser.json());
app.post('/charge', async (req, res) => {
let newVar = JSON.parse(req.body);
console.log('new var', newVar);
try {
// 1. Create Customer
stripe.customers.create(
// where do I pass this info from the frontend?
{
email: 'jenny.rosen@example.com',
source: 'tok_visa'
},
function(err, customer) {}
);
res.json({ status });
} catch (err) {
res.status(500).end();
}
});
app.listen(9000, () => console.log('Listening on port 9000'));