2017 © Pedro Peláez
 

library sparkpost

Client library for interfacing with the SparkPost API.

image

sparkpost/sparkpost

Client library for interfacing with the SparkPost API.

  • Monday, March 12, 2018
  • by nornholdj
  • Repository
  • 58 Watchers
  • 165 Stars
  • 287,621 Installations
  • PHP
  • 16 Dependents
  • 1 Suggesters
  • 53 Forks
  • 8 Open issues
  • 16 Versions
  • 14 % Grown

The README.md

, (*1)

Sign up for a SparkPost account and visit our Developer Hub for even more content., (*2)

SparkPost PHP Library

Travis CI Coverage Status Downloads Packagist, (*3)

The official PHP library for using the SparkPost REST API., (*4)

Before using this library, you must have a valid API Key. To get an API Key, please log in to your SparkPost account and generate one in the Settings page., (*5)

Installation

Please note: The composer package sparkpost/php-sparkpost has been changed to sparkpost/sparkpost starting with version 2.0., (*6)

The recommended way to install the SparkPost PHP Library is through composer., (*7)

# Install Composer
curl -sS https://getcomposer.org/installer | php

Sparkpost requires php-http client (see Setting up a Request Adapter). There are several providers available. If you were using guzzle6 your install might look like this., (*8)

composer require php-http/guzzle6-adapter "^1.1"
composer require guzzlehttp/guzzle "^6.0"

Next, run the Composer command to install the SparkPost PHP Library:, (*9)

composer require sparkpost/sparkpost

After installing, you need to require Composer's autoloader:, (*10)

require 'vendor/autoload.php';
use SparkPost\SparkPost;

Note: Without composer the costs outweigh the benefits of using the PHP client library. A simple function like the one in issue #164 wraps the SparkPost API and makes it easy to use the API without resolving the composer dependencies., (*11)

Running with IDEs

When running with xdebug under an IDE such as VS Code, you may see an exception is thrown in file vendor/php-http/discovery/src/Strategy/PuliBetaStrategy.php:, (*12)

Exception has occurred.
Http\Discovery\Exception\PuliUnavailableException: Puli Factory is not available

This is usual. Puli is not required to use the library. You can resume running after the exception., (*13)

You can prevent the exception, by setting the discovery strategies, prior to creating the adapter object:, (*14)

// Prevent annoying "Puli exception" during work with xdebug / IDE
// See https://github.com/getsentry/sentry-php/issues/801
\Http\Discovery\ClassDiscovery::setStrategies([
        // \Http\Discovery\Strategy\PuliBetaStrategy::class, // Deliberately disabled
        \Http\Discovery\Strategy\CommonClassesStrategy::class,
        \Http\Discovery\Strategy\CommonPsr17ClassesStrategy::class,
]);

Setting up a Request Adapter

Because of dependency collision, we have opted to use a request adapter rather than requiring a request library. This means that your application will need to pass in a request adapter to the constructor of the SparkPost Library. We use the HTTPlug in SparkPost. Please visit their repo for a list of supported clients and adapters. If you don't currently use a request library, you will need to require one and create a client from it and pass it along. The example below uses the GuzzleHttp Client Library., (*15)

A Client can be setup like so:, (*16)

'YOUR_API_KEY']);
?>

Initialization

new Sparkpost(httpClient, options)

  • httpClient
    • Required: Yes
    • HTTP client or adapter supported by HTTPlug
  • options
    • Required: Yes
    • Type: String or Array
    • A valid Sparkpost API key or an array of options
  • options.key
    • Required: Yes
    • Type: String
    • A valid Sparkpost API key
  • options.host
    • Required: No
    • Type: String
    • Default: api.sparkpost.com
  • options.protocol
    • Required: No
    • Type: String
    • Default: https
  • options.port
    • Required: No
    • Type: Number
    • Default: 443
  • options.version
    • Required: No
    • Type: String
    • Default: v1
  • options.async
    • Required: No
    • Type: Boolean
    • Default: true
    • async defines if the request function sends an asynchronous or synchronous request. If your client does not support async requests set this to false
  • options.retries
    • Required: No
    • Type: Number
    • Default: 0
    • retries controls how many API call attempts the client makes after receiving a 5xx response
  • options.debug
    • Required: No
    • Type: Boolean
    • Default: false
    • If debug is true, then all SparkPostResponse and SparkPostException instances will return any array of the request values through the function getRequest

Methods

request(method, uri [, payload [, headers]])

  • method
    • Required: Yes
    • Type: String
    • HTTP method for request
  • uri
    • Required: Yes
    • Type: String
    • The URI to receive the request
  • payload
    • Required: No
    • Type: Array
    • If the method is GET the values are encoded into the URL. Otherwise, if the method is POST, PUT, or DELETE the payload is used for the request body.
  • headers
    • Required: No
    • Type: Array
    • Custom headers to be sent with the request.

syncRequest(method, uri [, payload [, headers]])

Sends a synchronous request to the SparkPost API and returns a SparkPostResponse, (*17)

asyncRequest(method, uri [, payload [, headers]])

Sends an asynchronous request to the SparkPost API and returns a SparkPostPromise, (*18)

setHttpClient(httpClient)

  • httpClient
    • Required: Yes
    • HTTP client or adapter supported by HTTPlug

setOptions(options)

  • options
    • Required: Yes
    • Type: Array
    • See constructor

Endpoints

transmissions

  • post(payload)
    • payload - see request options
    • payload.cc
      • Required: No
      • Type: Array
      • Recipients to receive a carbon copy of the transmission
    • payload.bcc
      • Required: No
      • Type: Array
      • Recipients to discreetly receive a carbon copy of the transmission

Examples

Send An Email Using The Transmissions Endpoint

 getenv('SPARKPOST_API_KEY'), 'async' => false]);

try {
    $response = $sparky->transmissions->post([
        'content' => [
            'from' => [
                'name' => 'SparkPost Team',
                'email' => 'from@sparkpostbox.com',
            ],
            'subject' => 'First Mailing From PHP',
            'html' => '

Congratulations, {{name}}!

You just sent your very first mailing!, (*19)

', 'text' => 'Congratulations, {{name}}!! You just sent your very first mailing!', ], 'substitution_data' => ['name' => 'YOUR_FIRST_NAME'], 'recipients' => [ [ 'address' => [ 'name' => 'YOUR_NAME', 'email' => 'YOUR_EMAIL', ], ], ], 'cc' => [ [ 'address' => [ 'name' => 'ANOTHER_NAME', 'email' => 'ANOTHER_EMAIL', ], ], ], 'bcc' => [ [ 'address' => [ 'name' => 'AND_ANOTHER_NAME', 'email' => 'AND_ANOTHER_EMAIL', ], ], ], ]); } catch (\Exception $error) { var_dump($error); } print($response->getStatusCode()); $results = $response->getBody()['results']; var_dump($results); ?>

More examples here:, (*20)

Transmissions

  • Create with attachment
  • Create with recipient list
  • Create with cc and bcc
  • Create with template
  • Create
  • Delete (scheduled transmission by campaign_id only)

Templates

  • Create
  • Get
  • Get (list) all
  • Update
  • Delete

Message Events

  • get
  • get (with retry logic)

Send An API Call Using The Base Request Function

We provide a base request function to access any of our API resources., (*21)

 getenv('SPARKPOST_API_KEY'),
    'async' => false]);

$webhookId = 'afd20f50-865a-11eb-ac38-6d7965d56459';
$response = $sparky->request('DELETE', 'webhooks/' . $webhookId);
print($response->getStatusCode());
?>

Be sure to not have a leading / in your resource URI., (*22)

For complete list of resources, refer to API documentation., (*23)

Handling Responses

The API calls either return a SparkPostPromise or SparkPostResponse depending on if async is true or false, (*24)

Synchronous

$sparky->setOptions(['async' => false]);
try {
    $response = ... // YOUR API CALL GOES HERE

    echo $response->getStatusCode()."\n";
    print_r($response->getBody())."\n";
}
catch (\Exception $e) {
    echo $e->getCode()."\n";
    echo $e->getMessage()."\n";
}

Asynchronous

Asynchronous an be handled in two ways: by passing callbacks or waiting for the promise to be fulfilled. Waiting acts like synchronous request., (*25)

Wait (Synchronous)

$promise = ... // YOUR API CALL GOES HERE try { $response = $promise->wait(); echo $response->getStatusCode()."\n"; print_r($response->getBody())."\n"; } catch (\Exception $e) { echo $e->getCode()."\n"; echo $e->getMessage()."\n"; } echo "I will print out after the promise is fulfilled";
Then (Asynchronous)
$promise = ... // YOUR API CALL GOES HERE

$promise->then(
    // Success callback
    function ($response) {
        echo $response->getStatusCode()."\n";
        print_r($response->getBody())."\n";
    },
    // Failure callback
    function (Exception $e) {
        echo $e->getCode()."\n";
        echo $e->getMessage()."\n";
    }
);

echo "I will print out before the promise is fulfilled";

// You can combine multiple promises using \GuzzleHttp\Promise\all() and other functions from the library.
$promise->wait();

Handling Exceptions

An exception will be thrown in two cases: there is a problem with the request or the server returns a status code of 400 or higher., (*26)

SparkPostException

  • getCode()
    • Returns the response status code of 400 or higher
  • getMessage()
    • Returns the exception message
  • getBody()
    • If there is a response body it returns it as an Array. Otherwise it returns null.
  • getRequest()
    • Returns an array with the request values method, url, headers, body when debug is true

Contributing

See contributing., (*27)

The Versions

12/03 2018

dev-master

9999999-dev

Client library for interfacing with the SparkPost API.

  Sources   Download

Apache 2.0

The Requires

 

The Development Requires

by Avatar SparkPost

08/05 2017

dev-temp-composer-fix

dev-temp-composer-fix

Client library for interfacing with the SparkPost API.

  Sources   Download

Apache 2.0

The Requires

 

The Development Requires

by Avatar SparkPost

10/01 2017

2.1.0

2.1.0.0

Client library for interfacing with the SparkPost API.

  Sources   Download

Apache 2.0

The Requires

 

The Development Requires

by Avatar SparkPost

29/07 2016

2.0.3

2.0.3.0

Client library for interfacing with the SparkPost API.

  Sources   Download

Apache 2.0

The Requires

 

The Development Requires

by Avatar SparkPost

28/07 2016

2.0.2

2.0.2.0

Client library for interfacing with the SparkPost API.

  Sources   Download

Apache 2.0

The Requires

 

The Development Requires

by Avatar SparkPost

30/06 2016

2.0.1

2.0.1.0

Client library for interfacing with the SparkPost API.

  Sources   Download

Apache 2.0

The Requires

 

The Development Requires

by Avatar SparkPost

24/06 2016

2.0.0

2.0.0.0

Client library for interfacing with the SparkPost API.

  Sources   Download

Apache 2.0

The Requires

 

The Development Requires

by Avatar SparkPost

27/05 2016

1.2.1

1.2.1.0

Client library for interfacing with the SparkPost API.

  Sources   Download

Apache 2.0

The Requires

 

The Development Requires

by Avatar SparkPost

04/05 2016

1.2.0

1.2.0.0

Client library for interfacing with the SparkPost API.

  Sources   Download

Apache 2.0

The Requires

 

The Development Requires

by Avatar SparkPost

02/05 2016

1.1.0

1.1.0.0

Client library for interfacing with the SparkPost API.

  Sources   Download

Apache 2.0

The Requires

 

The Development Requires

by Message Systems, Inc.

25/03 2016

1.0.3

1.0.3.0

Client library for interfacing with the SparkPost API.

  Sources   Download

Apache 2.0

The Requires

 

The Development Requires

by Message Systems, Inc.

28/02 2016

1.0.2

1.0.2.0

Client library for interfacing with the SparkPost API.

  Sources   Download

Apache 2.0

The Requires

 

The Development Requires

by Message Systems, Inc.

25/02 2016

1.0.1

1.0.1.0

Client library for interfacing with the SparkPost API.

  Sources   Download

Apache 2.0

The Requires

 

The Development Requires

by Message Systems, Inc.

14/10 2015

1.0.0

1.0.0.0

SDK for interfacing with SparkPost APIs

  Sources   Download

Apache 2.0

The Requires

 

The Development Requires

by Message Systems, Inc.

14/11 2014

0.1.1

0.1.1.0

SDK for interfacing with SparkPost APIs

  Sources   Download

Apache 2.0

The Requires

 

The Development Requires

by Message Systems, Inc.

10/11 2014

0.1.0

0.1.0.0

SDK for interfacing with SparkPost APIs

  Sources   Download

Apache 2.0

The Requires

 

The Development Requires

by Message Systems, Inc.