How to use stripe - 10 common examples

To help you get started, we’ve selected a few stripe examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github opencollective / opencollective-api / test / graphql.createOrder.js View on Github external
});
      expect(transaction.FromCollectiveId).to.equal(xdamman.CollectiveId);
      expect(transaction.CollectiveId).to.equal(collective.id);
      expect(transaction.currency).to.equal(collective.currency);
      expect(transaction.hostFeeInHostCurrency).to.equal(0);
      expect(transaction.platformFeeInHostCurrency).to.equal(0.05 * order.totalAmount);
      expect(transaction.data.charge.currency).to.equal(collective.currency.toLowerCase());
      expect(transaction.data.charge.status).to.equal('succeeded');
      expect(transaction.data.balanceTransaction.net - transaction.hostFeeInHostCurrency).to.equal(transaction.netAmountInCollectiveCurrency);

      // make sure the payment has been recorded in the connected Stripe Account of the host
      const hostMember = await models.Member.findOne({ where: { CollectiveId: collective.id, role: 'HOST' } });
      const hostStripeAccount = await models.ConnectedAccount.findOne({
        where: { service: 'stripe', CollectiveId: hostMember.MemberCollectiveId }
      });
      const charge = await Stripe(hostStripeAccount.token).charges.retrieve(transaction.data.charge.id);
      expect(charge.source.last4).to.equal('4242');
    });
github strongloop / loopback-next / packages / cli / smoke-test / openapi / real-world-apis.smoke.js View on Github external
.get('/v2/list.json')
      .expect(200);
    if (!res.ok) {
      throw new Error('Unable to download API listing from apis.guru');
    }

    // Remove certain APIs that are known to cause problems
    const apis = res.body;

    // GitHub's CORS policy blocks this request
    delete apis['googleapis.com:adsense'];

    // These APIs cause infinite loops in json-schema-ref-parser.  Still investigating.
    // https://github.com/BigstickCarpet/json-schema-ref-parser/issues/56
    delete apis['bungie.net'];
    delete apis['stripe.com'];

    // Flatten the list, so there's an API object for every API version
    realWorldAPIs = [];
    for (const apiName in apis) {
      for (const version in apis[apiName].versions) {
        const api = apis[apiName].versions[version];
        api.name = apiName;
        api.version = version;
        realWorldAPIs.push(api);
      }
    }
  });
github APIDevTools / swagger-parser / test / specs / real-world / real-world.spec.js View on Github external
.end(function (err, res) {
        if (err || !res.ok) {
          return done(err || new Error('Unable to downlaod real-world APIs from apis.guru'));
        }

        // Remove certain APIs that are known to cause problems
        var apis = res.body;

        // GitHub's CORS policy blocks this request
        delete apis['googleapis.com:adsense'];

        // These APIs cause infinite loops in json-schema-ref-parser.  Still investigating.
        // https://github.com/BigstickCarpet/json-schema-ref-parser/issues/56
        delete apis['bungie.net'];
        delete apis['stripe.com'];

        // Flatten the list, so there's an API object for every API version
        realWorldAPIs = [];
        Object.keys(apis).forEach(function (apiName) {
          Object.keys(apis[apiName].versions).forEach(function (version) {
            var api = apis[apiName].versions[version];
            api.name = apiName;
            api.version = version;
            realWorldAPIs.push(api);
          });
        });

        done();
      });
  });
github reactioncommerce / reaction / imports / plugins / included / payments-stripe / server / methods / stripe.js View on Github external
"stripe/refund/create"(paymentMethod, amount, reason = "requested_by_customer") {
    check(amount, Number);
    check(reason, String);

    // Call both check and validate because by calling `clean`, the audit pkg
    // thinks that we haven't checked paymentMethod arg
    check(paymentMethod, Object);
    PaymentMethodArgument.validate(PaymentMethodArgument.clean(paymentMethod));

    let result;
    try {
      const stripeKey = utils.getStripeApi(paymentMethod.paymentPackageId);
      const stripe = stripeNpm(stripeKey);
      const refundPromise = stripe.refunds.create({ charge: paymentMethod.transactionId, amount: formatForStripe(amount) });
      const refundResult = Promise.await(refundPromise);
      Logger.debug(refundResult);
      if (refundResult && refundResult.object === "refund") {
        result = {
          saved: true,
          response: refundResult
        };
      } else {
        result = {
          saved: false,
          response: refundResult
        };
        Logger.warn("Stripe call succeeded but refund not issued");
      }
    } catch (error) {
github green-bot / greenbot-core / kisst / cloud / app.js View on Github external
app.post('/billing', function (req, res) {
  var req_data = req.body
  console.log('Entered billing function -> ' + req_data.type)
  console.log(req_data)
  Stripe.initialize('sk_live_CDYuW7Nsp4dtyKXT7ifjZ47q')

  if (req_data.type === 'customer.subscription.created') {
    // First things first, get the customer record.
    Stripe.Customers.retrieve(req_data.data.object.customer, {
      success: function (customer) {
        // OK, got the customer and the subscription.
        console.log('customer.subscription.created')
        var Room = Parse.Object.extend('Room')
        var room = new Room()
        var notification_emails = [customer.email]
        room.set('notification_emails', notification_emails)
        var owners = [customer.metadata.owner_cell]
        room.set('owners', owners)
        room.set('owner_cmd', 'ruby owner_settings.rb')
        room.set('desc', customer.email)
        room.set('default_cmd', 'ruby default.rb')
        room.set('default_path', 'scripts')
        room.set('stripe_sub_id', req_data.data.object.id)
        room.set('stripe_cust_id', customer.id)
        room.set('settings', {})
github fixate / feathers-stripe-webhooks / src / index.js View on Github external
export default function feathersStripeWebhooks(handlers, config = {}) {
  const options = Object.assign(
    {
      // Set to false to disable event fetching from Stripe
      // https://stripe.com/docs/webhooks#verifying-events
      verifyEvents: true,
    },
    config
  );

  debug(`Creating feathers-stripe-webhooks service with options: ${JSON.stringify(options)}`);

  checkOpts(options);

  const api = options.secret ? stripe(options.secret) : null;
  return service(api, handlers, options);
}
github stripe / stripe-node / examples / webhook-signing / express-ts.ts View on Github external
import Stripe from 'stripe';
import express from 'express';
import bodyParser from 'body-parser';

const stripe = new Stripe(process.env.STRIPE_API_KEY!);

/**
 * You'll need to make sure this is externally accessible.  ngrok (https://ngrok.com/)
 * makes this really easy.s
 *
 * To run this file, just provide your Secret API Key and Webhook Secret, like so:
 * STRIPE_API_KEY=sk_test_XXX WEBHOOK_SECRET=whsec_XXX node express.js
 */

const webhookSecret: string = process.env.WEBHOOK_SECRET!;
const app: express.Application = express();

// Only use the raw body parser for webhooks
app.use(
  (
    req: express.Request,
github reactioncommerce / reaction / imports / plugins / included / payments-stripe / server / methods / stripe.js View on Github external
const customerAccount = Accounts.findOne({ _id: cart.accountId });
      if (customerAccount) {
        const defaultEmail = (customerAccount.emails || []).find((email) => email.provides === "default");
        if (defaultEmail) {
          customerEmail = defaultEmail.address;
        }
      }
    }

    if (!customerEmail) {
      throw new ReactionError("invalid-parameter", "No email associated with the cart");
    }

    // Initialize stripe api lib
    const stripeApiKey = stripePkg.settings.api_key;
    const stripe = stripeNpm(stripeApiKey);

    // get array of shopIds that exist in this cart
    const shopIds = cart.items.reduce((uniqueShopIds, item) => {
      if (uniqueShopIds.indexOf(item.shopId) === -1) {
        uniqueShopIds.push(item.shopId);
      }
      return uniqueShopIds;
    }, []);

    const transactionsByShopId = {};

    // TODO: If there is only one transactionsByShopId and the shopId is primaryShopId -
    // Create a standard charge and bypass creating a customer for this charge
    const primaryShop = Shops.findOne({ _id: primaryShopId });
    const { currency } = primaryShop;
github zeit / pkg / test / test-79-npm / stripe / stripe.js View on Github external
'use strict';

var stripe = require('stripe');
if (stripe.DEFAULT_HOST === 'api.stripe.com') {
  console.log('ok');
}
github reactioncommerce / reaction / imports / plugins / included / payments-stripe / server / methods / stripe.js View on Github external
function stripeCaptureCharge(paymentMethod) {
  let result;
  const captureDetails = {
    amount: formatForStripe(paymentMethod.amount)
  };


  const stripeKey = utils.getStripeApi(paymentMethod.paymentPackageId);
  const stripe = stripeNpm(stripeKey);

  try {
    const capturePromise = stripe.charges.capture(paymentMethod.transactionId, captureDetails);
    const captureResult = Promise.await(capturePromise);

    if (captureResult.status === "succeeded") {
      result = {
        saved: true,
        response: captureResult
      };
    } else {
      result = {
        saved: false,
        response: captureResult
      };
    }