Support Portal

Welcome
Login

Subscribing to shipment events via SQS

Overview

If you want to subscribe in real time to status and events happening during the life-cycle of your shipments, the solution is to subscribe to our Amazon SQS Queue.

Whenever an event/status is created for a shipment, we will send a message to SQS corresponding to this event.

A status describes a state in which the shipment is on a high level. It displays the key information for the customer. Events are happening on a more detailed level. Multiple events can happen meanwhile the shipment is in a certain status. There are events initiating a status switch and some that do not come with a status change. Consequently, the status field is not necessarily be completed.

A detailed list with all events and status can be found here

If you want to pull tracking updates back to your system, the easiest solution will be to use our ShipmentTrackingHistory endpoint instead of SQS. Please contact your Key account manager if you want to set it up.

What is SQS queue

SQS Queue is a message queue that allows to accumulate messages from different services by creating a buffer where the messages are temporarily stored. SQS queue allows different parts of the system to communicate and process operations in asynchronous manner.

Image: AWS Amazon (1)

The messages in SQS are usually small, they can be requests, errors, status changes or any other information. To send a message, a component called a producer adds a message to the queue. The message is stored on the queue until another component called a consumer retrieves the message and does something with it.

Many producers and consumers can use the queue, but each message is processed only once, by a single consumer. 

SQS helps to improve performance - the endpoints that are producing and consuming messages interact with the queue, not each other. Producers can add requests to the queue without waiting for them to be processed. Consumers process messages only when they are available. No component in the system is ever stalled waiting for another, optimizing data flow.

Source: 
1. AWS Amazon, Amazon Simple Queue Service https://aws.amazon.com/sqs/

Activation/Deactivation

If you'd like to activate or deactivate the SQS queue, please contact your integration or key account manager at Seven Senders.

Connection

Use the SDK from Amazon Web Services. You will need your API-KEY to connect.

API KEY: This information was given to you when you created your Seven Senders account.

PHP Example

This example uses the AWS PHP SDK. For a complete sample see: github.com/SevenSenders/sqs-sample-php

<?php
 
require_once __DIR__.'/vendor/autoload.php';
 
$credentials = [
    'region' => 'eu-central-1',
    'version' => 'latest',
    'endpoint' => 'https://sqs.sevensenders.com/api/v1/shipment-events',
    'credentials' => [
        'key'    => '<API-KEY>',
        'secret' => '',
   ]
];
 
$client = new \Aws\Sqs\SqsClient($credentials);
 
$result = $client->receiveMessage(['QueueUrl' => '']);

$messages = $result->get('Messages') ?: [];

echo sprintf("Messages in Queue: %d\n", count($messages));

foreach($messages as $message) {
    echo $message['MessageId'] . "\n";
    echo $message['Body'] . "\n";
}
// Example for deleting messages one by one
foreach($messages as $message) {
$client->deleteMessage(['QueueUrl' => $message, 'ReceiptHandle' => $message['ReceiptHandle']]);
}

// Example for deleting messages in batch
$entries = [];
foreach ($messages as $message) {
$entries[] = [
'Id' => $message['MessageId'], // A unique identifier
'ReceiptHandle' => $message['ReceiptHandle'] // The receipt handle
];
}

$client->deleteMessageBatch(['QueueUrl' => $messages, 'Entries' => $entries]);

Java Example

This example uses the AWS Java SDK. For a complete sample see: github.com/SevenSenders/sqs-sample-java

package com.sevensenders.samples;

import java.util.List;

import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration;
import com.amazonaws.services.sqs.AmazonSQS;
import com.amazonaws.services.sqs.AmazonSQSClientBuilder;
import com.amazonaws.services.sqs.model.Message;

public class SQSSample {

    public static void main(String[] args) {
BasicAWSCredentials awsCredentials = new BasicAWSCredentials("your-sevensenders-api-key", "");
AmazonSQS sqs = AmazonSQSClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(awsCredentials))
.withEndpointConfiguration(new EndpointConfiguration("https://sqs.sevensenders.com/api/v1/shipment-events", ""))
.build();

try {
System.out.println("Getting Queue URL");
String queue_url = sqs.getQueueUrl("").getQueueUrl();
System.out.println("Result: " + queue_url);

System.out.println("Receiving messages...\n");

List<Message> messages = sqs.receiveMessage("").getMessages();

for (Message m : messages) {
System.out.println(m.getMessageId() + ":");
System.out.println(m.getBody());

// Process the message...

// Example for deleting messages one by one
sqs.deleteMessage(queueUrl, m.getReceiptHandle());
System.out.println("Message deleted: " + m.getMessageId());
}

// Example for deleting messages in batch
List<DeleteMessageBatchRequestEntry> deleteEntries = new ArrayList<>();
for (Message m : messages) {
deleteEntries.add(new DeleteMessageBatchRequestEntry(m.getMessageId(), m.getReceiptHandle()));
}

if (!deleteEntries.isEmpty()) {
DeleteMessageBatchRequest deleteRequest = new DeleteMessageBatchRequest(queueUrl, deleteEntries);
sqs.deleteMessageBatch(deleteRequest);
System.out.println("Messages deleted in batch");
}


} catch (AmazonServiceException ase) {
System.out.println("AmazonServiceException: Your request made it to SQS Proxy, but was rejected");
System.out.println("Error Message: " + ase.getMessage());
System.out.println("HTTP Status Code: " + ase.getStatusCode());
System.out.println("AWS Error Code: " + ase.getErrorCode());
System.out.println("Error Type: " + ase.getErrorType());
System.out.println("Request ID: " + ase.getRequestId());
} catch (AmazonClientException ace) {
System.out.println("AmazonClientException: Request failed.");
System.out.println("Error Message: " + ace.getMessage());
}
}


Python Example

This example uses Boto3. For a complete sample see: github.com/SevenSenders/sqs-sample-python.
import boto3

# SQS CLIENT
sqs = boto3.client(
    'sqs',
    region_name='eu-central-1',
    endpoint_url='https://sqs.sevensenders.com/api/v1/shipment-events',
    aws_access_key_id='your-7s-api-key-here', # 7S Shop API Key
    aws_secret_access_key='', # Keep it blank
)

# QUEUE URL
queue_url = sqs.get_queue_url(QueueName='').get('QueueUrl')
print('Queue URL: {}'.format(queue_url))

# Example for receiving messages
response = sqs.receive_message(QueueUrl=queue_url)
messages = response.get('Messages')
print('Messages in Queue: {}'.format(len(messages)))

if messages:
    # Process each message
    for message in messages:
        message_id = message.get('MessageId')
        body = message.get('Body')

        print('{}: {}'.format(message_id, body))

        # Process the message here...

        # Example for deleting messages one by one
        sqs.delete_message(QueueUrl=queue_url, ReceiptHandle=message['ReceiptHandle'])

    # Example for deleting messages in batch
    # messages_to_delete = [{'Id': str(i), 'ReceiptHandle': msg['ReceiptHandle']} for i, msg in enumerate(messages)]
    # sqs.delete_message_batch(QueueUrl=queue_url, Entries=messages_to_delete)
else:
    print("No messages in the queue.")

.NET Example

This example uses the AWS .NET SDK. For a complete sample see: https://github.com/SevenSenders/sqs-sample-dotnet

Task.Run(async () => {
var credentials = new BasicAWSCredentials("<API-KEY>", "---");
var config = new AmazonSQSConfig {
ServiceURL = "https://analytics-api.7senders.com"
};

var client = new AmazonSQSClient(credentials, config);

var receiveMessageRequest = new ReceiveMessageRequest {
QueueUrl = "https://sqs.sevensenders.com/api/v1/shipment-events",
MaxNumberOfMessages = 10
};

var response = await client.ReceiveMessageAsync(receiveMessageRequest);
var messages = response.HttpStatusCode == HttpStatusCode.OK ? response.Messages : new List<Message>();

foreach (var message in messages) {
Console.WriteLine("Message ID: " + message.MessageId);
Console.WriteLine(message.Body + "\n\n");

}
})
.GetAwaiter()
.GetResult();



Message format

Each message contains a JSON object with the properties described below.

FieldTypeDescription
idstringSeven Senders shipment identifier
order_idstringThe order reference inside your system
tracking_codestringThe shipment tracking number from the carrier
carrierstringSelected carrier to ship the parcel
carrier_countrystringCountry where the parcel is handed over to selected carrier / scanned for the first time by the selected carrier
statusstringCurrent shipment status. Possible values are:
"" (empty string)
New
Info
Pickup
Out for delivery
Delivered
Lost
Delivered to pickup point
Hub scan at LMC
(First) scan at LMC
Return created
Return dropped off 
Return picked up
Return in transit
Return delivered
Return lost


status_timedate (dd.mm.yyyy hh:mm:ss)Date and time when the current shipment status was set
ticketsarray of ticket objectsDeprecated - A list of tickets, related to this milestone:
FieldType
idstring
namestring
creation_timedate (dd.mm.yyyy hh:mm:ss)
This property will be removed, please use the events property.
eventsarray of event objectsA list of events, related to this milestone:
FieldType
namestring
creation_timedate (dd.mm.yyyy hh:mm:ss)

Example Response Body

{
    "id": "s3030665",
    "order_id": "818213398889282",
    "tracking_code": "394024NRETZ7OMZJ4C02XN",
    "carrier": "dhl",
    "carrier_country": "de",
    "status": "Delivered",
    "status_time": "06.08.2017 12:01:08",
    "tickets": [{
        "id": "123456789",
        "name": "Light damage",
        "creation_time": "04.08.2017 10:01:09"
    }],
    "events": [{
        "name": "Light damage",
        "creation_time": "04.08.2017 10:01:09"
    }]
}

                                                                                    


Did you find it helpful? Yes No