0

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.

matthh
  • 47
  • 4
  • have you getURL function return an object and pass it to generateToken function, that should get you to next step.. also do add the output of console.log you receive at each step – sid May 31 '23 at 17:45
  • @sid My main issue is I dont know how to get the value of the code in the redirected URL – matthh Jun 01 '23 at 16:41
  • refer to this fiddle, https://jsfiddle.net/qLvh97to/1. you should be able to get the code after being redirected – sid Jun 01 '23 at 17:27

0 Answers0