Tuesday, 4 April 2017

How can I listen and post http requests from and to my website?

I am trying to implement Stripe connect API into my website. For that I need to make a request to Stripe server upon clicking on connect button , and get the customer token after request is back to the URI that is previously set in their server. Example below (origin) shows listening to a local port and make http requests using Node.js and express. All fine so far!

Now, where should I listen to for it to run? I'd like to have a back-end Node.js service to do the job but I don't know where to listen to instead of port 9111 the in code below!

'use strict';

var CLIENT_ID = '*********************';             
var API_KEY = '************************';                 
var TOKEN_URI = "https://connect.stripe.com/oauth/token";
var AUTHORIZE_URI = 'https://connect.stripe.com/oauth/authorize';

var qs = require('querystring');
var request = require('request');
var express = require('express');
var app = express();

app.get('/authorize', function(req, res) {
  // Redirect to Stripe /oauth/authorize endpoint
  res.redirect(AUTHORIZE_URI + '?' + qs.stringify({
    response_type: 'code',
    scope: 'read_write',
    client_id: CLIENT_ID
  }));
}); 

********
//after success , getting back from Strip to a url I provide 

app.get('/oauth/callback', function(req, res) {

  var code = req.query.code;
  console.log("code : "  , code); 
  // Make /oauth/token endpoint POST request
  request.post({
    url: TOKEN_URI,
    form: {
      grant_type: 'authorization_code',
      client_id: CLIENT_ID,
      code: code,
      client_secret: API_KEY
    }
  }, function(err, r, body) {

    if (err) {
      console.log("eror, " , err) ; 
    } else { 
      console.log("success resp", JSON.parse(body)); 

      const b = JSON.parse(body)
      const refresh_token          = b.refresh_token; 
      const access_token           = b.access_token; 
      const stripe_user_id         = b.stripe_user_id; 
      const stripe_publishable_key = b.stripe_publishable_key; 

      res.send({'refresh_token': refresh_token,
                  'access_token': access_token,
              'stripe_user_id': stripe_user_id,
        'stripe_publishable_key':  stripe_publishable_key}); 

    }; 
  });
});

//*************************
//what should I use instead of a port like this? 
app.listen(9311);



via TheeBen

No comments:

Post a Comment