{"size": 3939, "ext": "js", "max_stars_repo_path": "stripe/stripe_charge.js", "max_stars_repo_name": "auth0/webtask-scripts", "max_stars_repo_stars_event_min_datetime": "2015-08-18T18:47:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T20:25:15.000Z", "max_issues_repo_path": "stripe/stripe_charge.js", "max_issues_repo_name": "auth0/webtask-scripts", "max_issues_repo_issues_event_min_datetime": "2015-08-05T14:25:10.000Z", "max_issues_repo_issues_event_max_datetime": "2016-05-26T14:21:12.000Z", "max_forks_repo_path": "stripe/stripe_charge.js", "max_forks_repo_name": "auth0/webtask-scripts", "max_forks_repo_forks_event_min_datetime": "2015-08-03T18:00:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-01T16:09:29.000Z"}
{"max_stars_count": 68, "max_issues_count": 5, "max_forks_count": 25, "avg_line_length": 37.1603773585, "max_line_length": 115, "alphanum_fraction": 0.4407209952}
// Raw version of this file: https://raw.githubusercontent.com/auth0/webtask-scripts/master/stripe/stripe_charge.js

var request = require('request')
    , async = require('async')
    , querystring = require('querystring');

return function (context, req, res) {
    console.log('Stripe payment request', {
        referer: req.headers['referer']        
    });
    async.series([
        function (callback) {
            // Collect www-form-urlencoded paylod of a HTTPS form POST
            // FUTURE: This will be part of Auth0 Webtask core functionality
            var body = '';
            req.on('data', function (chunk) { body += chunk; });
            req.on('end', function () {
                try {
                    body = querystring.parse(body);
                    if (!body || typeof body !== 'object')
                        throw error(400, 'Unexpected payload.');
                    for (var p in body)
                        if (!context.data[p])
                            context.data[p] = body[p];
                }
                catch (e) {
                    return callback(e);
                }
                return callback();
            });
            req.on('error', callback);
        },
        function (callback) {
            // Validate input parameters
            if (!context.data.callback)
                context.data.callback = req.headers['referer'];
            var required_params = ['stripeToken', 'callback', 'amount', 'currency', 'STRIPE_SECRET_KEY'];
            for (var p in required_params)
                if (!context.data[required_params[p]])
                    return callback(
                        error(400, new Error('The `' + required_params[p] + '` parameter must be provided.')));
            callback();
        },
        function (callback) {
            // Process charge through Stripe
            request({ 
                url: 'https://api.stripe.com/v1/charges',
                method: 'POST',
                auth: {
                    user: context.data.STRIPE_SECRET_KEY,
                    pass: ''
                },
                form: {
                    source: context.data.stripeToken,
                    amount: context.data.amount,
                    currency: context.data.currency
                }
            }, function (error, sres, body) {
                if (error)
                    return callback(error);
                try {
                    body = JSON.parse(body);
                }
                catch (e) {
                    return callback(new Error('Unable to parse Stripe response as JSON.'));
                }
                var redirect_hash;
                if (sres.statusCode === 200) {
                    redirect_hash = querystring.stringify({
                        status: body.status,
                        id: body.id
                    });
                }
                else {
                    redirect_hash = querystring.stringify({
                        error: (body.error && body.error.message) 
                            ? body.error.message
                            : 'Unexpected HTTP response ' + sres.statusCode + ' from Stripe'
                    });                    
                }
                var redirect_url = context.data.callback + '#' + redirect_hash;
                res.writeHead(302, { Location: redirect_url });
                res.end();
                return callback();
            });
        }
    ], function (error) {
        if (error) {
            try {
                console.log('ERROR', error);
                res.writeHead(error.code || 500);
                res.end(error.stack || error.message || error.toString());
            }
            catch (e) {
                // ignore
            }
        }
    });
}

function error(code, message) {
    var e = new Error(message);
    e.code = code;
    return e;
}
