Skip to content

Commit

Permalink
initial import
Browse files Browse the repository at this point in the history
  • Loading branch information
Adam Grohs authored and Adam Grohs committed Apr 12, 2019
1 parent 491f33f commit 2f94304
Show file tree
Hide file tree
Showing 10 changed files with 407 additions and 1 deletion.
40 changes: 40 additions & 0 deletions .github/ISSUE_TEMPLATE/bug_report.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---

**Describe the bug**
A clear and concise description of what the bug is.

**To Reproduce**
Steps to reproduce the behavior:

1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error

**Expected behavior**
A clear and concise description of what you expected to happen.

**Screenshots**
If applicable, add screenshots to help explain your problem.

**Desktop (please complete the following information):**

- OS: [e.g. iOS]
- Browser [e.g. chrome, safari]
- Version [e.g. 22]

**Smartphone (please complete the following information):**

- Device: [e.g. iPhone6]
- OS: [e.g. iOS8.1]
- Browser [e.g. stock browser, safari]
- Version [e.g. 22]

**Additional context**
Add any other context about the problem here.
19 changes: 19 additions & 0 deletions .github/ISSUE_TEMPLATE/feature_request.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---

**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

**Describe the solution you'd like**
A clear and concise description of what you want to happen.

**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.

**Additional context**
Add any other context or screenshots about the feature request here.
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# dependencies
node_modules

# misc
.env
*.log
5 changes: 5 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"singleQuote": true,
"semi": false,
"trailingComma": "none"
}
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) 2019-2025 UNIQUELY PARTICULAR LLC and Adam Grohs

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.
66 changes: 65 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,65 @@
# sync-shipengine-to-zendesk
# @particular./sync-shipengine-to-zendesk

[![npm version](https://badge.fury.io/js/%40particular.%2Fsync-shipengine-to-moltin.svg)](https://badge.fury.io/js/%40particular.%2Fsync-shipengine-to-moltin)

> Add a Zendesk Sunshine Event whenever a Shipping Status change is triggered in ShipEngine
Asynchronous microservice that is triggered by [ShipEngine](https://www.shipengine.com/) webhooks to create a Sunshine Event inside of [Zendesk](https://zendesk.com).

Built with [Micro](https://github.com/zeit/micro)! 🤩

## 🛠 Setup

Both a [Zendesk](https://zendesk.com) _and_ [ShipEngine](https://www.shipengine.com/) account are needed for this to function.

Create a `.env` at the project root with the following credentials:

```dosini
ZENDESK_SUBDOMAIN=
ZENDESK_INTEGRATION_EMAIL=
ZENDESK_INTEGRATION_SECRET=
```

`ZENDESK_SUBDOMAIN` is the first part of the URL for your Zendesk account (ie. https://{ZENDESK_SUBDOMAIN}.zendesk.com/).

While logged in to your Zendesk instance create a new User to run the Webhooks under by going to `Settings` > `People` > `Add User` > `Role: Staff`; this email address will be used as your `ZENDESK_INTEGRATION_EMAIL` above.

Find your `ZENDESK_INTEGRATION_SECRET` within your Zendesk instance by going to `Settings` > `API` > enable `Token Access` > add `Active API Tokens [+]` > `API Token`.

## 📦 Package

Run the following command to build the app

```bash
yarn install
```

Start the development server

```bash
yarn dev
```

The server will typically start on PORT `3000`, if not, make a note for the next step.

Start ngrok (change ngrok port below from 3000 if yarn dev deployed locally on different port above)

```bash
ngrok http 3000
```

Make a note of the https `ngrok URL` provided.

## ⛽️ Usage

Next head over to the ShipEngine [API Management>Webhooks](https://app.shipengine.com/#/portal/apimanagement) area, add a new webhook with the following details:

| Events | Webhook URL | Status |
| ------------------ | ------------------ | ------ |
| Any tracking event | `ngrok URL` above_ | On |

## 🚀 Deploy

You can easily deploy this function to [now](https://now.sh).

_Contact [Adam Grohs](https://www.linkedin.com/in/adamgrohs/) @ [Particular.](https://uniquelyparticular.com) for any questions._
183 changes: 183 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
const { json, send } = require('micro')
const moment = require('moment-timezone')
const fetch = require('node-fetch')

const cors = require('micro-cors')({
allowMethods: ['POST']
})

const _toJSON = error => {
return !error
? ''
: Object.getOwnPropertyNames(error).reduce(
(jsonError, key) => {
return { ...jsonError, [key]: error[key] }
},
{ type: 'error' }
)
}

process.on('unhandledRejection', (reason, p) => {
console.error(
'Promise unhandledRejection: ',
p,
', reason:',
JSON.stringify(reason)
)
})

module.exports = cors(async (req, res) => {
if (req.method === 'OPTIONS') {
return send(res, 204)
}

/*
"carrier": "usps",
"tracking_number": "9205590164917312751089",
"address_from": {
"city": "Las Vegas",
"state": "NV",
"zip": "89101",
"country": "US"
},
"address_to": {
"city": "Spotsylvania",
"state": "VA",
"zip": "22551",
"country": "US"
},
"transaction": "1275c67d754f45bf9d6e4d7a3e205314",
"original_eta": "2016-07-23T00:00:00Z",
"eta": "2016-07-23T00:00:00Z",
"servicelevel": {
"token": "usps_priority",
"name": "Priority Mail"
},
"metadata": null,
"tracking_status": {
"object_created": "2016-07-23T20:35:26.129Z",
"object_updated": "2016-07-23T20:35:26.129Z",
"object_id": "ce48ff3d52a34e91b77aa98370182624",
"status": "DELIVERED",
"status_details": "Your shipment has been delivered at the destination mailbox.",
"status_date": "2016-07-23T13:03:00Z",
"location": {
"city": "Spotsylvania",
"state": "VA",
"zip": "22551",
"country": "US"
}
},
*/

try {
const tracking_update = await json(req)
const {
data: {
carrier,
tracking_number,
servicelevel: { name: service_type },
eta,
tracking_status: {
status,
status_details,
status_date,
location: {
city: location_city,
state: location_state,
zip: location_zip
}
}
}
} = tracking_update

let tracking_extra = {}
if (tracking_update.extra) {
tracking_extra = tracking_update.extra
}
let { billing_email, order_id } = tracking_extra
// if (!order_id) {
// order_id = '730589c9-ee68-44b4-a201-bb38a9468abe'
// }
// if (!billing_email) {
// billing_email = '[email protected]'
// }

if (order_id) {
if (billing_email) {
const payload = {
profile: {
source: 'support',
identifiers: {
email: billing_email
}
},
event: {
source: 'shipengine',
type: 'shipping-status-change',
description:
status === 'DELIVERED' ? 'Order Delivered' : 'Shipping Update',
created_at: moment(status_date),
properties: {
'Shipping Carrier': carrier,
'Tracking Status': status, //TODO: format case
'Order ID': order_id,
'Tracking Number': tracking_number,
'Service Type': service_type,
'Estimated Delivery': moment(eta).format('MM/DD/YYYY'),
'Tracking Notes': status_details,
'Tracking Location': `${location_city}, ${location_state} ${location_zip}`
}
}
}

fetch(
`https://${
process.env.ZENDESK_SUBDOMAIN
}.zendesk.com/api/sunshine/track`,
{
headers: {
Authorization: `Basic ${Buffer.from(
`${process.env.ZENDESK_INTEGRATION_EMAIL}/token:${
process.env.ZENDESK_INTEGRATION_SECRET
}`
).toString('base64')}`,
Accept: 'application/json',
'Content-Type': 'application/json'
},
method: 'POST',
body: JSON.stringify(payload)
}
)
.then(response => {
if (response.ok && response.status < 299) {
return send(
res,
200,
JSON.stringify({ received: true, order_id })
)
} else {
return send(res, 500, 'Error')
}
})
.catch(error => {
const jsonError = _toJSON(error)
return send(res, 500, jsonError)
})
} else {
console.error('missing billing_email')
return send(res, 200, JSON.stringify({ received: true, order_id }))
}
} else {
console.error('missing order_id')
return send(
res,
200,
JSON.stringify({ received: true, order_id: 'null' })
)
}
} catch (error) {
const jsonError = _toJSON(error)
return send(res, 500, jsonError)
}
})
16 changes: 16 additions & 0 deletions now.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"name": "demo-sync-shipengine-to-zendesk",
"alias": "particular-demo-sync-shipengine-to-zendesk.now.sh",
"env": {
"NODE_ENV": "production",
"ZENDESK_SUBDOMAIN": "@demo-zendesk-subdomain",
"ZENDESK_INTEGRATION_EMAIL": "@demo-zendesk-integration-email",
"ZENDESK_INTEGRATION_SECRET": "@demo-zendesk-integration-secret"
},
"builds": [
{
"src": "*.js",
"use": "@now/node"
}
]
}
Loading

0 comments on commit 2f94304

Please sign in to comment.