# End-to-End Webhook Setup

This guide provides an overview of how to use Pitney Bowes webhook services for tracking events. Pitney Bowes supports tracking for shipments processed both **on-platform** (shipments handled by Pitney Bowes) and **off-platform** (shipments handled by other platforms).

- **on-platform**: Shipments created using Pitney Bowes APIs
- **off-platform**: shipments created outside Pitney Bowes but tracked through Pitney Bowes


## On-Platform Tracking Events

### Overview

These events are generated for shipments processed by Pitney Bowes. Developers can configure a webhook to receive tracking events automatically. Tracking numbers for on-platform shipments are automatically subscribed, and once a webhook is set up, related events are broadcast automatically.

### Setup Instructions:

- Configure webhooks to automate tracking event notifications.
- Provide an accurate URL and credentials during setup.
- Ensure secure communication via OAuth or Basic Authentication.


## Off-Platform Tracking Events

### Overview

These events are for shipments processed by other platforms but tracked through Pitney Bowes. Developers must subscribe to tracking numbers to receive updates for off-platform shipments.

### Setup Instructions:

- Configure webhooks to automate tracking event notifications.
- Provide an accurate URL and credentials during setup.
- Ensure secure communication via OAuth or Basic Authentication.
- Verify that the carrier is supported by Pitney Bowes before subscribing.
- Provide valid tracking numbers and carrier information to receive updates.


## Webhook Configuration

Developers can configure webhooks to receive tracking events as they occur. This allows real-time tracking updates for shipments associated with their account.

### Steps to Configure Webhook:

#### 1. Get Applicable Events

Use the `Get Applicable Event List for Webhook Configuration` API to retrieve a list of trackable events.

- **Endpoint**: `/api/v1/events`
- **Security**: `bearerAuth`
- **Response**: A list of event IDs and names, such as:
  - `Manifest`
  - `Acceptance`
  - `InTransit`
  - `DeliveryAttempt`
  - `OutForDelivery`
  - `Delivered`
  - `Exception`
  - `ReturnToSender`
  - `ReadyForPickup`
  - `PickupMissed`
  - `PickedUp`


**Sample Request:**

```bash
curl -i -X GET \
  https://api-sandbox.sendpro360.pitneybowes.com/webhook/api/v1/events \
  -H 'Authorization: Bearer <YOUR_TOKEN_HERE>'
```

**Sample Response:**

```json
[
    {
        "eventId": "Manifest",
        "name": "Manifest"
    },
    {
        "eventId": "Acceptance",
        "name": "Acceptance"
    },
    {
        "eventId": "InTransit",
        "name": "InTransit"
    },
    {
        "eventId": "DeliveryAttempt",
        "name": "DeliveryAttempt"
    },
    {
        "eventId": "OutForDelivery",
        "name": "OutForDelivery"
    },
    {
        "eventId": "Delivered",
        "name": "Delivered"
    },
    {
        "eventId": "Exception",
        "name": "Exception"
    },
    {
        "eventId": "ReturnToSender",
        "name": "ReturnToSender"
    },
    {
        "eventId": "ReadyForPickup",
        "name": "ReadyForPickup"
    },
    {
        "eventId": "PickupMissed",
        "name": "PickupMissed"
    },
    {
        "eventId": "PickedUp",
        "name": "PickedUp"
    }
]
```

#### 2. Create Webhook Configuration

Use the `Create Webhook Configuration` API to set up a webhook. Provide the events, URL, and authentication details.

- **Required Fields:**
  - **name**: The name of the webhook.
  - **type**: Must be set to `tracking`.
  - **events**: Array of event IDs to track.
  - **url**: The webhook URL where tracking events will be sent.
  - **authParams**: Authentication details:
    - **Custom**: Pass `apiKey` and `headerName`.
    - **Basic**: Pass `clientId` and `secret`.
    - **OAuth**: pass `clientId`, `secret` and `tokenUrl`.
> **tokenUrl**:	OAuth token endpoint where the PitneyBowes can request access tokens.
- **Optional Fields:**
- **timeout**: Timeout duration in seconds for webhook responses.
- **status**: Defaults to `active`. Use `inactive` to deactivate.
- **Endpoint:**
  - `/api/v1/webhookConfig`
- **Response:**
  - Returns a unique `webHookConfigID` for updating webhook details.


authType custom
```
curl -i -X POST \
    https://api-sandbox.sendpro360.pitneybowes.com/webhook/api/v1/webhookConfig \
    -H 'Authorization: Bearer <YOUR_TOKEN_HERE>' \
    -H 'Content-Type: application/json' \
    -d '{
    "name": "webhook1",
    "type": "tracking",
    "events": ["Manifest", "InTransit", "Delivered"],
    "url": "https://webhook.com",
    "timeOut": 5,
    "status": "active",
    "authParams": {
        "authType": "custom",
        "apiKey": "xxxxxxxx",
        "headerName": "webhook1"
    }
    }'
```

authType OAuth
```
curl -i -X POST \
https://api-sandbox.sendpro360.pitneybowes.com/webhook/api/v1/webhookConfig \
-H 'Authorization: Bearer <YOUR_TOKEN_HERE>' \
-H 'Content-Type: application/json' \
-d '{
    "name": "dev_webhook1",
    "type": "tracking",
    "events": [
    "Manifest",
    "InTransit",
    "Delivered"
    ],
    "url": "https://ccf8edc3-0c38-4e3a-ae94-86849a7c8895.mock.pstmn.io/hellowebhook",
    "timeOut": 5,
    "status": "active",
    "authParams": {
    "authType": "oauth",
    "clientID": "xxxxxxxxxxxxx",
        "secret": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
        "tokenUrl": "https://api.xxxxxxxxxxxx.com/auth/api/v1/token"
    }
}'
```

responses

authType custom
```
{
"webHookConfigID": "D6yEwX1zaZjj",
"name": "dev_webhook1",
"type": "tracking",
"events": [
    "Manifest",
    "InTransit",
    "Delivered"
],
"url": "https://webhook.com",
"authParams": {
    "authType": "custom",
    "apiKey": "xxxxxxxx",
    "headerName": "webhook1"
},
"timeOut": 5,
"status": "active",
"developerPartnerId": "sacxxxx"
}
```

authType OAuth
```
{
"webHookConfigID": "KPe5Rx44nyb6",
"name": "dev_webhook1",
"type": "tracking",
"events": [
    "Manifest",
    "InTransit",
    "Delivered"
],
"url": "https://ccf8edc3-xxxx-xxxx-xxxx-86849a7c8895.mock.pstmn.io/hellowebhook",
"authParams": {
    "authType": "oauth",
    "clientID": "xxxxxxxxxxxxx",
    "secret": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    "tokenUrl": "https://api.xxxxxxxxxxxx.com/auth/api/v1/token"
},
"timeOut": 5,
"status": "active",
"developerPartnerId": "sacd0e7"
}
```

#### Internal OAuth Flow:

Once the webhook is registered with `authType: oauth`, Pitney Bowes internally handles authentication as follows:

1. **Token Request**


Pitney Bowes makes a POST request to the provided `tokenUrl`, using your `clientID` and `secret` to obtain an access token.

1. **Expected OAuth Response**


After receiving the POST request sent by Pitney Bowes, The token server should respond with the similar response with access token below:

```json
{
"access_token": "<access-token>",
"tokenType": "BearerToken",
"issuedAt": "1735802883000",
"expiresIn": "28800",
"clientID": "xxxxxxxxxxxxx",
}
```

> This `access-token` is valid for the period specified in the `expiresIn` response field. Token is refreshed automatically when expired.


1. **Webhook Delivery**


Pitney Bowes includes the `access-token` in the Authorization header when sending webhook events:

```
  Authorization: Bearer <access_token>
```

#### 3. Receive Tracking Events

Once the webhook is set up, Pitney Bowes sends tracking events to your configured URL as they occur.

**Expected Behavior:**

- **Authorization:** Webhooks use OAuth or Basic Authentication for secure communication.
- **Response Acknowledgment:** Acknowledge POST requests by returning the X-PB-developerPartnerId in the response.
- **Retries:** If Pitney Bowes does not receive a 2XX status code, it retries the request at intervals up to 16 hours.


## Off-Platform Tracking Events

For **Off-Platform shipments**, tracking details must be subscribed to using the **Subscribe Tracking Details API**.

- **Carrier Support:** Tracking is available only if Pitney Bowes supports the specified carrier service.
- **Unsubscribe event:** To stop receiving updates for a tracking number, use the same API with subscribe set to false.


### Steps to Subscribe Tracking Details:

#### 1. Subscribe to Tracking Details

Use the `Subscribe Tracking Details` API to request tracking updates for an off-platform shipment.

**Required Fields**:

- **trackingNumber**: The shipment's tracking number.
- **carrier**: The carrier's ID (e.g., USPS, UPS, FedEx).
- **subscribe**: Set to `true` to enable tracking updates.
- **Endpoint**: `/api/v1/track/{trackingNumber}/subscribe`
- **Security**: `bearerAuth`


**Sample Request**:

```bash
curl -i -X GET \
  'https://api-sandbox.sendpro360.pitneybowes.com/shippingtracking/api/v1/track/{trackingNumber}/subscribe?carrier=USPS&subscribe=true' \
  -H 'Authorization: Bearer <YOUR_TOKEN_HERE>' \
  -H 'X-PB-Developer-Partner-ID: string'
```

**Sample Response**:

```json
{
    "message": "Tracking number subscribed successfully",
    "trackingEvents": {
      "carrier": "FEDEX",
      "currentLocation": {
        "city": "Miami",
        "country": "US",
        "description": "Delivered",
        "postalCode": "33122",
        "stateOrProvince": "FL"
      },
      "currentStatus": {
        "carrierEventCode": "DL",
        "carrierEventDescription": "Delivered",
        "eventCode": "AWP- Awaiting Pickup",
        "eventDate": "2023-06-28T16:55:00.000Z",
        "eventDescription": "Delivered",
        "eventLocation": {
          "city": "Miami",
          "country": "US",
          "description": "",
          "postalCode": "33122",
          "stateOrProvince": "FL"
        },
        "status": "Delivered"
      },
      "deliveryDate": "2023-06-28T16:55:00.000Z",
      "deliveryProofUrl": "",
      "estimatedDeliveryDate": "1901-01-01T00:00:00.000Z",
      "serviceCode": "",
      "serviceName": "FedEx Ground",
      "shipDate": "1901-01-01T00:00:00.000Z",
      "trackingHistory": [
        {
          "carrierEventCode": "DL",
          "carrierEventDescription": "Delivered",
          "eventCode": "DLD",
          "eventDate": "2023-06-28T16:55:00.000Z",
          "eventDescription": "Delivered",
          "eventLocation": {
            "city": "Miami",
            "country": "US",
            "description": "",
            "postalCode": "33122",
            "stateOrProvince": "FL"
          },
          "status": "Delivered"
        }
      ]
    }
  }
```

#### 2.	Receive Tracking Details

Once subscribed, Pitney Bowes broadcasts tracking information for the off-platform shipment, such as the current status, estimated delivery date, and event history.