Using Webtask.io with Stripe for React-Static

143 Views Asked by At

I am building a small website using React-Static. Site is all built, but I need to integrate basic donation functionality. I have a few questions that have me stumped. Following the guide here by Thomasz Jancuk I've run into a few hurdles.

1.) When the page initially loads as html, the button is created. However once react kicks in it removes my button. I imagine I need to integrate the form JS through React rather than the current inline.

    <form action="WEBTASK.IO_URL" method="POST">
      <script
        src="https://checkout.stripe.com/checkout.js" class="stripe-button"
        data-key={my_public_stripe_key}
        data-image=""
        data-name=""
        data-description=""
        data-amount="2500"
        data-zip-code="true"
        data-currency="usd"
        data-locale="auto"
        data-panel-label="Donate"
        data-label="">
      </script>
    </form>

2.) If I force a button and click it, I get through the initial Stripe Checkout stuff and it POSTs to the webtask.io url. However I am getting an error:

"code": 500,
"error": "Script generated an unhandled synchronous exception.",
"details": "TypeError: Cannot read property 'stripeToken' of undefined"

Here is my webtask.io script. I've included the NPM Modules and the correct Secrets.

'use latest';

import bodyParser from 'body-parser';
import stripe from 'stripe';

bodyParser.urlencoded();

module.exports = function (ctx, req, res) {
    stripe(ctx.secrets.stripeSecretKey).charges.create({
        amount: 2500,
        currency: 'usd',
        source: ctx.body.stripeToken,
        description: 'Contribute to the Campaign'
    }, function (error, charge) {
        var status = error ? 400 : 200;
        var message = error ? error.message : 'Thank You for your Contribution!'; 
        res.writeHead(status, { 'Content-Type': 'text/html' });
        return res.end('<h1>' + message + '</h1>');
    });
};
2

There are 2 best solutions below

0
On

Instead of taking the stripeToken from ctx try using req.body.stripeToken

module.exports = function (ctx, req, res) {
    stripe(ctx.secrets.stripeSecretKey).charges.create({
        amount: 2500,
        currency: 'usd',
        source: req.body.stripeToken,
        description: 'Contribute to the Campaign'
    }, function (error, charge) {
        var status = error ? 400 : 200;
        var message = error ? error.message : 'Thank You for your Contribution!'; 
        res.writeHead(status, { 'Content-Type': 'text/html' });
        return res.end('<h1>' + message + '</h1>');
    });
};
0
On

When exporting an express app (as opposed to a simple function) you're going to need to explicitly define the programming model with the argument --meta wt-compiler=webtask-tools/express (or you can use webtask-tools).

So the final command line becomes:

$ wt create index.js --meta wt-compiler=webtask-tools/express