Anthony Michelizzi Anthony Michelizzi - 1 month ago 10
Javascript Question

Koa and Stripe, wait to render page

I'm using koa and stripe to process a one time payment. It's working as it should, however it renders the page before

data
gets assigned. I would like to be able to render the page after data is assigned so that
id
will show up in the page view instead of it being undefined.

I tried rendering the page in the callback function, I got a
404 not found
. I tried using
.then
after the
stripe.charges.create
function, since stripe is compatible with promises but it gave the same result. The current code I have is below.

module.exports.payment = function* payment()
{
const params = this.request.body;
let data;

if (!params.stripeToken) {
this.throw(400, "Sorry, something has gone awry.");
}
if (!params.amount) {
this.throw(400, "A purchase amount must be supplied.");
}
const chargeAmount = params.amount * 100;

const charge = stripe.charges.create({
amount: chargeAmount,
currency: "USD",
source: params.stripeToken,
description: `${config.site.name} order#: ${this.session.id}`
}, (err, charge) => {
data = charge.id;
}

);

yield this.render("payment/payment_success", {
id: data
});
};

Answer

If the stripe library supports promises, your best bet is probably to yield stripe.charges.create.

module.exports.payment = function* payment()
{
    const params = this.request.body;

    if (!params.stripeToken) {
        this.throw(400, "Sorry, something has gone awry.");
    }
    if (!params.amount) {
        this.throw(400, "A purchase amount must be supplied.");
    }
    const chargeAmount = params.amount * 100;

    const charge = yield stripe.charges.create({
        amount: chargeAmount,
        currency: "USD",
        source: params.stripeToken,
        description: `${config.site.name} order#: ${this.session.id}`
    };

    yield this.render("payment/payment_success", {
        id: charge.id
    });
};

Now when you render your view, charge will be populated with the results of your stripe call.

Comments