• Stars
    star
    195
  • Rank 198,218 (Top 4 %)
  • Language
    PHP
  • License
    MIT License
  • Created almost 10 years ago
  • Updated 11 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

SparkPost client library for PHP

Sign up for a SparkPost account and visit our Developer Hub for even more content.

SparkPost PHP Library

Travis CI Coverage Status Downloads Packagist

The official PHP library for using the SparkPost REST API.

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.

Installation

Please note: The composer package sparkpost/php-sparkpost has been changed to sparkpost/sparkpost starting with version 2.0.

The recommended way to install the SparkPost PHP Library is through composer.

# 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.

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:

composer require sparkpost/sparkpost

After installing, you need to require Composer's autoloader:

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.

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:

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.

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

// 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.

A Client can be setup like so:

<?php
require 'vendor/autoload.php';

use SparkPost\SparkPost;
use GuzzleHttp\Client;
use Http\Adapter\Guzzle6\Client as GuzzleAdapter;

$httpClient = new GuzzleAdapter(new Client());
$sparky = new SparkPost($httpClient, ['key'=>'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

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

Sends an asynchronous request to the SparkPost API and returns a SparkPostPromise

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

<?php
require 'vendor/autoload.php';

use SparkPost\SparkPost;
use GuzzleHttp\Client;
use Http\Adapter\Guzzle6\Client as GuzzleAdapter;

$httpClient = new GuzzleAdapter(new Client());
// Good practice to not have API key literals in code - set an environment variable instead
// For simple example, use synchronous model
$sparky = new SparkPost($httpClient, ['key' => getenv('SPARKPOST_API_KEY'), 'async' => false]);

try {
    $response = $sparky->transmissions->post([
        'content' => [
            'from' => [
                'name' => 'SparkPost Team',
                'email' => '[email protected]',
            ],
            'subject' => 'First Mailing From PHP',
            'html' => '<html><body><h1>Congratulations, {{name}}!</h1><p>You just sent your very first mailing!</p></body></html>',
            '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:

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.

<?php
require 'vendor/autoload.php';

use SparkPost\SparkPost;
use GuzzleHttp\Client;
use Http\Adapter\Guzzle6\Client as GuzzleAdapter;

$httpClient = new GuzzleAdapter(new Client());
$sparky = new SparkPost($httpClient, [
    'key' => 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.

For complete list of resources, refer to API documentation.

Handling Responses

The API calls either return a SparkPostPromise or SparkPostResponse depending on if async is true or false

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.

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.

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.

More Repositories

1

heml

HEML is an open source markup language for building responsive email.
JavaScript
4,329
star
2

node-sparkpost

SparkPost client library for Node.js
JavaScript
180
star
3

matchbox

πŸ”₯ A react UI component library
TypeScript
109
star
4

python-sparkpost

SparkPost client library for Python
Python
92
star
5

gosparkpost

SparkPost client library for the Go Programming Language
Go
63
star
6

elixir-sparkpost

SparkPost client library for Elixir https://developers.sparkpost.com
Elixir
44
star
7

java-sparkpost

SparkPost client library for Java
Java
39
star
8

nodemailer-sparkpost-transport

Sparkpost transport for Nodemailer
JavaScript
26
star
9

wordpress-sparkpost

WordPress plugin to use SparkPost email
PHP
20
star
10

pizza-bot

Learn how to order πŸ• from Slack
JavaScript
20
star
11

developers.sparkpost.com

SparkPost Developer Site and Documentation
API Blueprint
18
star
12

heml.io

HEML website
JavaScript
17
star
13

code-snippets

A repository with helpful programming resources for SparkPost developers.
JavaScript
17
star
14

bouncy-sink

A PMTA-based sink application that does opens, clicks, bounces, OOBs and FBLs
Python
16
star
15

github-alerts-to-slack

Sends a report of Github security alerts to Slack
JavaScript
11
star
16

gitplus

Generic tools and instructions for making it easier to work with git as a team.
Shell
11
star
17

support-docs

SparkPost support articles
TypeScript
11
star
18

auditmated

Automated npm auditing
Shell
10
star
19

gimli

Gimli is a crash tracing/analysis framework. It is available under a 3-clause BSD style license.
C
9
star
20

sp-forwarding-service

A small Heroku service that will consume inbound message webhook POSTs and forward them through SparkPost.
JavaScript
8
star
21

raffles

Email-driven raffle service
JavaScript
8
star
22

slack-etiquette

Kind of like Emily Post, but for Slack
7
star
23

umem

Portable umem Slab allocator
C
7
star
24

sparkpost-cli

A CLI to perform various tasks using the SparkPost API
Go
6
star
25

eriksen

A model marshaling library for dual-write/single-read data migration
JavaScript
6
star
26

mandrill-sparkpost-templates

Translate Mandrill Handlebars templates into SparkPost templates
JavaScript
6
star
27

template-library

A collection of example email templates for use with SparkPost
HTML
5
star
28

node-sparkpost-cli

A command-line interface to SparkPost.
JavaScript
5
star
29

elixir-webhook-sample

A report of recipient OS usage from SparkPost click events and the User-Agent header, with Elixir and Phoenix
Elixir
4
star
30

sparkpost-csv2tx

BASH script to import a CSV and convert it to a Recipient List and delivery a Transmission with SparkPost.
Shell
3
star
31

community-bot

A bot for the SparkPost community Slack team
JavaScript
3
star
32

event-data

self-hosted message events
JavaScript
3
star
33

azure-csharp-webhook-sample

A .NET Core sample that receives and processes SparkPost webhook events
C#
3
star
34

httpdump

Store HTTP request data, and provide a simple framework for post-processing in parallel.
Go
3
star
35

momentum-documentation

Repository for Momentum Documentation
JavaScript
3
star
36

csharp

Community-maintained C# SparkPost client library
3
star
37

eslint-config-sparkpost

ESLint configuration for Javascript based SparkPost projects
JavaScript
3
star
38

mbot

our hubot
CoffeeScript
2
star
39

sparkyEvents-Gmail-bounces-Dec2020

Python
2
star
40

momentum-scriptlets

Lua
2
star
41

postman-collection

A Postman collection for SparkPost
2
star
42

campaign-sparkpost

✨ SparkPost email provider for Campaign
JavaScript
2
star
43

msys-jlog-tools

Miscellaneous tools for JLog (journalled log) files
Perl
2
star
44

momentum_sample_policy

Example policy for Momentum
Perl
2
star
45

sparkybluemix-poc

An example of using Sparkpost.com for sending email via IBM Bluemix PaaS
JavaScript
2
star
46

AzureFunctionsWebhooksDemo

Consume webhooks with Azure Functions
C#
1
star
47

design.sparkpost.com

SparkPost Design Documentation Site
HTML
1
star
48

lua-policies

Example business policies, implemented in the Momentum Business Policy Framework
Lua
1
star
49

bower-sinon

Bower repo for Sinon.js
JavaScript
1
star
50

styles

CSS
1
star
51

relaymsgdb

Persist, parse, and present subject lines, organized by sender localpart
Go
1
star
52

node-red-contrib-sparkpost

Letting SparkPost go with the flow in node-red
JavaScript
1
star
53

AnalyticsTakeHomeTest

A place to showcase your abilities
1
star
54

codeland

1
star
55

webhook-report-sample

Build a report of recipient OS usage from SparkPost click events and the User-Agent header
PHP
1
star
56

events-search-example

Example code for integrating with SparkPost Events Search API
JavaScript
1
star
57

ux-github-slack-alerts

JavaScript
1
star
58

puppet-openresty

Ruby
1
star
59

appengine-flexible-python-sample

Sample app using Python, Flask and SparkPost in the Google App Engine flexible environment
Python
1
star