How to get redirected query parameters into nodejs?

178 views Asked by At

I am working on an app to track our outbound UPS packages using the UPS API. For those that do not know, they are implementing a OAuth token system to authenticate requests. This article shows the flow of the process: https://developer.ups.com/api/reference/oauth/authorization-code?loc=en_US

I am writing this app in node.js and this is what I have so far:

import fetch from 'node-fetch';
import open, {openApp, apps} from 'open';

async function getURL() {
  const query = new URLSearchParams({
    client_id: 'myClientID',
    redirect_uri: 'https://example.com/outboundtracking'
  }).toString();

  const resp = await fetch(
    `https://onlinetools.ups.com/security/v1/oauth/validate-client?${query}`,
    {method: 'GET'}
  );

  const data = await resp.json();
  var reqType = data['type'];
  var redirect = data['LassoRedirectURL'];
  console.log(data);
  var params = new URLSearchParams({
      client_id: 'myClientID',
      redirect_uri: 'https://example.com/outboundtracking',
      response_type: 'code',
      scope: 'read',
      type: reqType
  }).toString();
    
  const resp2 = await fetch(redirect, {method:'POST', body: params});
  const data2 = await resp2.text();
  console.log(`https://www.ups.com/lasso/signin?${params}`);
  open(`https://www.ups.com/lasso/signin?${params}`, {app: {name:'chrome'}});
}

async function generateToken() {
    const formData = {
    grant_type: 'authorization_code',
    code: 'code_from_redirect',
    redirect_uri: 'https://eaxmple.com/outboundtracking'
  };
    
    const resp = await fetch(
    `https://onlinetools.ups.com/security/v1/oauth/token`,
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'x-merchant-id': 'myClientID',
        Authorization: 'Basic ' + Buffer.from('upsID:upsPassword').toString('base64')
      },
      body: new URLSearchParams(formData).toString()
    }
  );
    
    const data = await resp.text();
    console.log(data);
}

getURL();
generateToken();

My first function, getURL, works perfectly, chrome opens and after logging in with UPS credentials, I am redirected back to my site with the code in the url (https://example.com/outboundtracking?code=somelongrandomstring). How do I get the code from the redirected URL and pass it to the other functions? When I just copied the code from the URL and hardcoded it, it works.

0

There are 0 answers