Toomaime
Toomaime

Reputation: 21

Stripe Checkout with React and Express Js

I am trying to solve the following problem. On the Frontend I use React and installed the React-Stripe-Checkout package. I created a Checkout.js file which I am importing then into a FromContainer- Here is the logic for Checkout.js

onToken(token) {
    fetch('/postajob', {
        method: 'POST',
        body: JSON.stringify(token),
    }).then(response => {
        response.json().then(data => {
            alert(`We are in business, ${data.email}`);
        });
    });
}
render() {
    return (
        <StripeCheckout
            name="Teacherjobs.io"
            description="Job Post on Teacherjobs.io"
            ComponentClass="div"
            panelLabel="Post Job"
            amount={1000}
            currency="USD"
            stripeKey="pk_test_vfjVQjaiduhHGt9OY3lUB1yz"
            locale="auto"
            email="[email protected]"
            zipCode={false}
            alipay={true}
            allowRememberMe
            token={this.onToken}
            reconfigureOnUpdate={false}
            triggerEvent="onClick">

            <button
                className="submitbtn"
                onClick={this.handleFormSubmit}
                type="submit"
                value="Submit">Submit
            </button>

        </StripeCheckout>
    )
}

In my FormContainer I import Checkout.js which is a submit button to save data. So by clicking the button you can save the information giving in the form (const formPayload).

handleFormSubmit(e) {
    e.preventDefault();

    const formPayload = {
        jobTitle: this.state.jobTitle,
        country: this.state.location,
        city: this.state.city,
        apply: this.state.apply,
        categories: this.state.categories,
        description: this.state.description

    };
    // post a job - logic coming from services
    jobsService.postJob(formPayload, (err, result) => {
        if(result) {
            console.log('job posted');
            console.log('here');
        } else {
            alert('Could not post a job');
        }
    });

Furthermore I have an Api based on Express router to handle the post requests

 router.route('/postajob')
    .post((req, res) => {
        console.log(req.body);
        JobList.insertOne(req.body, (err,  stat) => {
            if(err) {
                res.status(500).send({ msg: 'Job upload failed' });
            } else  {
                res.status(202).send({ msg: 'Job posted successfully' });
            }
        });
    });

And a Services folder for the postJob functionality in the FormContainer.

function postJob(jobInfo, callback) {
console.log(jobInfo);
fetch('/api/postajob', {
    method: 'POST',
    headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
    },
    body: JSON.stringify(jobInfo)
})
    .then((response) => {
        response.json().then((data) => {
            console.log(data);
            if (response.ok) {
                callback(null, data);
            } else {
                callback({});
            }
        });
    })
    .catch((error) => {
        console.log(error);
    });

}

What do I have to change in this logic to let the customer save data, but only if fulfilled stripe checkout and paid for the service?

Upvotes: 1

Views: 1993

Answers (3)

CesarCarbajo
CesarCarbajo

Reputation: 11

router.post('/stripe', requireAuth, async (req, res) => {
    const { token } = req.body
    const charge = await stripe.charges.create({
        amount: 10000,//100€
        currency: 'EUR',
        source: token.id, // obtained with Stripe.js in the frontend
    })

    console.log("charge", charge)
    //Aqui el cargo ya esta realizado con exito.
    //We return a confirmation so that the process continues in the frontend.
    res.send(charge)
})

Upvotes: 0

Robin Wieruch
Robin Wieruch

Reputation: 15898

Your frontend only generates the token and all the necessary information for the payment. When the request reaches your backend, you would have to use your Stripe Secret Key (while you would use the Stripe Public Key in the frontend) to make another request to the Stripe API. If you need further guidance on this topic, this article describes the minimum steps it takes to setup React with Express and Stripe. It comes with an open source boilerplate project too.

Upvotes: 1

hpar
hpar

Reputation: 738

It's important to know that Stripe Checkout does not create charges, it only creates card tokens. Your backend code at /postajob needs to read the token sent from the frontend and then attempt to create a charge, something like:

router.route('/postajob') .post((req, res) => { stripe.charges.create({ amount: 2000, currency: "usd", source: req.token, description: "Charge for [email protected]" }, function(err, charge) { // asynchronously called, check if charge was created successfully // ... // Insert job, or return error to frontend }); });

More on this here: https://stripe.com/docs/api/node#create_charge

There's a full example of using Express + Checkout here: https://stripe.com/docs/checkout/express

Upvotes: 0

Related Questions