Convert USPS Manager class C# code to JavaScript

76 Views Asked by At

I have some working USPS Manager C# code but need to execute it from Google Apps Script in JavaScript.

How would I convert the below to JavaScript format?

USPSManager m = new USPSManager("YOUR_USER_ID", true);
Address a = new Address();
a.Address2 = "6406 Ivy Lane";
a.City = "Greenbelt";
a.State = "MD";
Address addressWithZip = m.GetZipcode(a);
string zip = addressWithZip.Zip;

Thanks in advance for any tips.

Using the code outlined below in GAS I receive the below error: enter image description here

2

There are 2 best solutions below

0
mstephen19 On

Here it is "translated" into JavaScript. Thing is, if USPS doesn't have a USPSManager class written in JavaScript, then this isn't going to work - or you'll have to write one yourself.

const m = new USPSManager("YOUR_USER_ID", true);
const a = new Address();
a.Address2 = "6406 Ivy Lane";
a.City = "Greenbelt";
a.State = "MD";
const addressWithZip = m.GetZipcode(a);
const zip = addressWithZip.Zip;
3
Moshe Katz On

If you are writing code in JavaScript, using a C# library will not work. You need to use a JavaScript library.

A quick search on NPM found this usps-webtools package.

Here is how you would use it in code:

// Old CommonJS Modules syntax:
const USPS = require('usps-webtools');
// or, if your platform supports the newer ECMAScript Module syntax:
import USPS from 'usps-webtools';

const usps = new USPS({
    server: 'http://production.shippingapis.com/ShippingAPI.dll',
    userId: 'YOUR_USER_ID',
});

const address = {
  street2: '6406 Ivy Lane',
  city: 'Greenbelt',
  state: 'MD'
};

usps.zipCodeLookup(address, (error, address) => {
    if (error) {
        // handle error here
        return;
    }
    const zip = address.zip;
    // use that result here
});