Skip to content

Commit

Permalink
Adding files
Browse files Browse the repository at this point in the history
  • Loading branch information
vyshakhbabji committed Jul 27, 2022
0 parents commit 2c8d406
Show file tree
Hide file tree
Showing 6 changed files with 413 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .sample.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
PORT=8080
TOKEN=[REPLACE WITH TOKEN]
BASE_URL=https://api.goshippo.com/
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2022 Vyshakh Babji

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
192 changes: 192 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
# Shippo Webhooks Basic Sample App

This application is built to help provide developers with a clear understanding of how to utilize Shippo
Webhook Subscriptions.

In this app we are
* Creating a ngrok tunnel and return webhook url
* Creating a Shippo Webhook Subscription to webhooks url
* Creating a transaction using Shippo's Create Transaction API call
* Listening to Webhook events


## Prerequisites
* NPM installed locally
* Node.js installed locally
* ngrok or a web server which supports SSL/TLS v1.1 / v1.2

## Installation
* Clone the repository

`git clone https://github.com/goshippo/shippo-demos-webhooks.git`

* Install the dependency

```text
cd shippo-demos-webhooks
yarn install (or npm install)
```

## Configure your credentials

Copy the .sample.env to .env and fill in the values for the following variables:
```text
PORT=8080
TOKEN=[REPLACE WITH TOKEN]
BASE_URL=https://api.goshippo.com/
```

## Running the app

```
cp .sample.env .env
node index.js
```

## Configuring Webhook URL on Shippo API setting
When you run the app you will see instructions on the terminal/console as below. Please follow the instructions
as mentioned:

```javascript
Starting ngrok . Please wait ...
Webhook url is ready to use. Your webhook url is : https://afb9-2600-1700-dd90-14f0-e4f1-11d2-5a73-6ade.ngrok.io/webhook

To configure the webhook settings on Shippo WebApp follow the instructions:
1. Click on https://apps.goshippo.com/settings/api
2. Go to Webhooks configuration setting
3. Click on Add Webhook
4. Event Type: All Events (you can choose events you want to listen to as well)
5. Mode: Live / Test
6. URL: Add the webhook url - https://XXXXXX.ngrok.io/webhook
7. Hit Save

Now you should be able to recieve all the notification events to your locally setup webhook url
You can also inspect webhook events via ngrok WebInterface inspector on url : http://localhost:4040
```
## Testing

As you have now subscribed to `All Events` , you should be able to see incoming notifications by just
running a sample transaction.

```javascript

Eg: Here I am creating a transaction

```curl
curl --location --request POST 'https://api.goshippo.com/transactions' \
--header 'Authorization: ShippoToken [SHIPPO TOKEN (live or test)]' \
--header 'Content-Type: application/json' \
--data-raw '{
"rate": "XXXX",
"async": false,
"label_file_type": "PDF"
}'
```

You can replace the transaction object with your own transaction object in `index.js` file.

```javascript
function createTransaction(){
console.log('\n\n\nCreating transaction for Shippo API');
const transactionObject = {
"rate": "xxxxx",
"async": false,
"label_file_type": "PDF"
};
makeShippoPostRequest('/transactions', transactionObject);
}
````
If this endpoint return `HTTP 201 Created` response , you will see a notification on your console/terminal like this:
```text
Webhook event received =========================>
Transaction ID: 95a5936ebc0b4432ba04b2758d681b16
Tracking Status: UNKNOWN
Tracking URL Provider: https://tools.usps.com/go/TrackConfirmAction_input?origTrackNum=9201990182632251604002
ETA: null
Webhook event =========================>

```
***


# Issues and Improvements

* If you want me to improve this demo or if you find any issues , please open issue on the issue section
* I am open to improving and keeping this demo up to date to best of my knowledge
* This code is for demo purposes only. DONOT use this in production apps
* Feel free to send PRs if you want to make any changes to this repo.

***
# About ngrok

## _What is ngrok?_

The **_official_ description**
on the website https://ngrok.com/product is:

> "_**`ngrok`** exposes **`local`** servers behind NATs and firewalls
to the **`public`** internet over secure tunnels_."

In _**plain** (beginner friendly) **English**_:

> _**`ngrok`** is a small piece of software
that lets you **run** a **web application** <br />
on your **`local` computer**
and (securely) **share it** with the world
on a **`public` address** ("URL")_.

## How it works?

```npm install``` downloads the ngrok binary for your platform from the official ngrok hosting. To host binaries yourself set the `NGROK_CDN_URL` environment variable before installing ngrok. To force specific platform set `NGROK_ARCH`, eg `NGROK_ARCH=freebsdia32`.

The first time you create a tunnel the ngrok process is spawned and runs until you disconnect or when the parent process is killed. All further tunnels are connected or disconnected through the internal ngrok API which usually runs on http://127.0.0.1:4040.


## ngrok installation

#### Via homebrew formula

```bash
brew install --cask ngrok
```

#### Via npm
Install the package with npm:

```bash
npm install ngrok -g
```

For global installation on Linux, you might need to run `sudo npm install --unsafe-perm -g ngrok` due to the [nature](https://github.com/bubenshchykov/ngrok/issues/115#issuecomment-380927124) of npm postinstall script.

### Running ngrok locally
```bash
ngrok http [port]
eg. ngrok http 8080
```



## To know more about ngrok
[**How it works?**](https://ngrok.com/product)

[**Learn more**](https://github.com/dwyl/learn-ngrok)


## _Why use ngrok?_

You are working on a Web App/Site on your **`localhost`**,
but it's "not yet ready" to be "deployed"

> _**Note**: once you are **ready**
to make your App/MVP "**official**",
you should consider using **Heroku**
as it does not require you to have your `localhost` running_
(_and it has good logging, "monitoring", "free tier", etc._). <br />
See:
[github.com/dwyl/**learn-heroku**](https://github.com/dwyl/learn-heroku)


Empty file added Shippo Webhooks FAQ.md
Empty file.
177 changes: 177 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
//create a webhook url with ngrok
require('dotenv').config();
const ngrok = require('ngrok');
const request = require('request');
const express = require('express');
const bodyParser = require('body-parser');

const BASE_URL = process.env.BASE_URL;
let webhookUrl = '';

/*
* Init ngrok and get the webhook url
*/

async function init(options) {
console.log('Starting ngrok . Please wait ...');
const url = await ngrok.connect(process.env.PORT);
webhookUrl = url + '/webhook';
console.log('Webhook url is ready to use. Your webhook url is : ', webhookUrl);
console.log('\n\n\nTo configure the webhook settings on Shippo WebApp follow the instructions: \n' +
' 1. Click on https://apps.goshippo.com/settings/api\n' +
' 2. Go to Webhooks configuration setting \n' +
' 3. Click on Add Webhook\n' +
' 4. Event Type: All Events (you can choose events you want to listen to as well) \n' +
' 5. Mode: Live / Test \n' +
' 6. URL: Add the webhook url - '+ webhookUrl +'\n' +
' 7. Hit Save\n' +
'\n' +
' Now you should be able to recieve all the notification events to your locally setup webhook url\n' +
' You can also inspect webhook events via ngrok WebInterface inspector on url : http://localhost:4040\n' +
' ');
console.log('\n\n\nStarting express server....');
}

/*
Start the express server
*/

function startNodeServer() {
const app = express();
const port = process.env.PORT;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));

app.get('/', (req, res) => {
res.send('Hello World!');
});

app.post('/webhook', (req, res) => {

console.log('\n\nWebhook event received =========================>');
let responseBody = req.body;
// console.log('Webhook Raw Event ',responseBody);
switch (responseBody.event) {
case 'transaction_created':
console.log('Transaction ID: ', responseBody.data.object_id);
console.log('Tracking Status: ', responseBody.data.tracking_status)
console.log('Tracking URL Provider: ', responseBody.data.tracking_url_provider)
console.log('ETA: ', responseBody.data.eta);
break;
case 'transaction_updated':
//write your code here
break;
case 'track_updated':
//write your code here
break;
case 'batch_purchased':
//write your code here
break;
case 'batch_created':
//write your code here
break;

default:
console.log('Default Respomse body', responseBody);

}
// console.log(req.body);
console.log('Webhook event =========================>\n\n');
res.send('OK');
});

app.listen(port, () => {
console.log(`App is listening at http://localhost:${port}`);
});
}

/**
* Quick function to make POST request to Shippo API
*/
function makeShippoPostRequest(endpoint, data) {
const url = BASE_URL + endpoint;
const options = {
url: url,
headers: {
'Authorization': process.env.TOKEN,
'Content-Type': 'application/json'
},
body: data,
json: true
};

request.post(options, function (error, response, body) {

if (!error) {
console.log('Successful Response Body for API Call :'+options.url +' is :', body);
} else {
console.log('Error Response Code is : ',response.statusCode);
console.log('Error: ', error);
}
});
}

/*
Here you are creating a Webhook
https://goshippo.com/docs/reference#tracks-create
POST /webhooks HTTP/1.1
Host: api.goshippo.com
Authorization: ShippoToken SHIPPOTOKEN
Content-Type: application/json
{
"url": "http://www.example.com",
"event": "track_updated"
}
*/
function createWebhook() {
console.log('\n\n\nCreating webhook for Shippo API');
const webhookBody = {
"url": webhookUrl,
"event": "transaction_created",//,transaction_updated,track_updated,batch_created,batch_updated",
'is_test': false
};
makeShippoPostRequest('/webhooks', webhookBody);
}

/*
Here you are creating a Shipping label
https://goshippo.com/docs/reference#transactions-create
POST /transactions HTTP/1.1
Host: api.goshippo.com
Authorization: ShippoToken SHIPPOTOKEN
Content-Type: application/json
{
"rate": "d9629f248ea24bc786ed921fff0c55ff",
"async": false,
"label_file_type": "PDF"
}
*/
function createTransaction(){
console.log('\n\n\nCreating transaction for Shippo API');
const transactionObject = {
"rate": "d9629f248ea24bc786ed921fff0c55ff",
"async": false,
"label_file_type": "PDF"
};
makeShippoPostRequest('/transactions', transactionObject);
}

async function start() {
await init();
startNodeServer();
console.log('Your webhookURL is: ', webhookUrl);

//create webhook via SHIPPO API
createWebhook();

//create transaction via SHIPPO API
createTransaction();

}

start().then(r => {
console.log('Started Server.... ');
});
Loading

0 comments on commit 2c8d406

Please sign in to comment.