Stripejs on express part II

After we can our token from stripe.js, now we need to send this token to stripe API with our server. Then our charge will be complete.

  1. Install stripe through npm

    1
    npm install stripe
  2. Implement request - here’s example request from Stripe API

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    var stripe = require("stripe")(
    "sk_test_UawoxUENSN7VkeeMIXXXXX"
    );

    stripe.charges.create({
    amount: 2000,
    currency: "usd",
    source: "tok_187waCF6w9JvbRHHBeCqMoBg", // obtained with Stripe.js
    description: "Charge for liam.johnson@example.com"
    }, function(err, charge) {
    // asynchronously called
    });
  3. We need to modify a couple things

    • amount is measured in cents therefore we need to multiple our amounts by 100.
    • source is the token generated from our frontend validation
    • I’m getting these info from my session cart
    • images from stripe

    Here’s what my code look like.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    stripe.charges.create({
    amount: cart.totalPrice * 100,
    currency: "usd",
    source: req.body.stripeToken, // obtained with Stripe.js
    description: "Test Charge"
    }, function(err, charge) {
    if (err) {
    req.flash('error', err.messages)
    return res.redirect('/checkout')
    }
    // This is where we save our orders
    var order = new Order({
    name: req.body.name,
    address: req.body.address,
    cart: cart,
    paymentId: charge.id
    })
    order.save(function(err, result){
    req.flash('success', 'Successfully bought product')
    req.session.cart = null
    res.redirect('/')
    })
    });
    })

That should be it man. Your stripe should be charged. Now we need to save our orders.