简体   繁体   中英

How do I pass additional data from the client-side Stripe Checkout to the server with Fetch

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'));

You can simply pass an abject to JSON.stringify (JSON) to the body attribute of your fetch request.

...
let response = await fetch('/charge', {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({
        token: '',
        name: '',
        userid: 123,
    }),
})
...

You have to update the header Content-Type to pass application/json .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM