Sign up for a SparkPost account and visit our Developer Hub for even more content.
A fork of 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.
This fork uses PSR-18 HTTP Client standard instead of HTTPlug. See PSR-18 Migration for upgrade instructions.
The recommended way to install the SparkPost PHP Library is through composer.
# Install Composer
curl -sS https://getcomposer.org/installer | phpSparkPost requires a PSR-18 HTTP client implementation. We recommend Symfony HTTP Client:
composer require sparkpost/sparkpost
composer require symfony/http-client nyholm/psr7Alternatively, you can use Guzzle 7 or any other PSR-18 compatible client:
composer require guzzlehttp/guzzle "^7.0"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.
SparkPost requires a PSR-18 compatible HTTP client. The library uses PSR-18 (HTTP Client), PSR-17 (HTTP Factories), and PSR-7 (HTTP Messages) standards.
<?php
require 'vendor/autoload.php';
use SparkPost\SparkPost;
use Symfony\Component\HttpClient\Psr18Client;
// Symfony HTTP Client implements all three required interfaces
$httpClient = new Psr18Client();
$sparky = new SparkPost(
$httpClient, // ClientInterface
$httpClient, // RequestFactoryInterface
$httpClient, // StreamFactoryInterface
['key' => 'YOUR_API_KEY']
);<?php
require 'vendor/autoload.php';
use SparkPost\SparkPost;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\HttpFactory;
$guzzle = new Client();
$factory = new HttpFactory();
$sparky = new SparkPost(
$guzzle, // ClientInterface
$factory, // RequestFactoryInterface
$factory, // StreamFactoryInterface
['key' => 'YOUR_API_KEY']
);httpClient- Required: Yes
- Type:
Psr\Http\Client\ClientInterface - PSR-18 HTTP client implementation
requestFactory- Required: Yes
- Type:
Psr\Http\Message\RequestFactoryInterface - PSR-17 request factory
streamFactory- Required: Yes
- Type:
Psr\Http\Message\StreamFactoryInterface - PSR-17 stream factory
options- Required: Yes
- Type:
Array - Configuration array with API key and other 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 asyncdefines if therequestfunction sends an asynchronous or synchronous request. If your client does not support async requests set this tofalse
options.retries- Required: No
- Type:
Number - Default:
0 retriescontrols how many API call attempts the client makes after receiving a 5xx response
options.debug- Required: No
- Type:
Boolean - Default:
false - If
debugis true, then allSparkPostResponseandSparkPostExceptioninstances will return any array of the request values through the functiongetRequest
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
GETthe values are encoded into the URL. Otherwise, if the method isPOST,PUT, orDELETEthe payload is used for the request body.
headers- Required: No
- Type:
Array - Custom headers to be sent with the request.
Sends a synchronous request to the SparkPost API and returns a SparkPostResponse
Sends an asynchronous request to the SparkPost API and returns a SparkPostPromise
httpClient- Required: Yes
- HTTP client or adapter supported by HTTPlug
options- Required: Yes
- Type:
Array - See constructor
- post(payload)
payload- see request optionspayload.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
<?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' => 'from@sparkpostbox.com',
],
'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:
- Create with attachment
- Create with recipient list
- Create with cc and bcc
- Create with template
- Create
- Delete (scheduled transmission by campaign_id only)
- Create
- Get
- Get (list) all
- Update
- Delete
- get
- get (with retry logic)
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.
The API calls either return a SparkPostPromise or SparkPostResponse depending on if async is true or false
$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";
}The library throws SparkPostException when there is a problem with the request or the server returns a status code of 400 or higher.
- getCode()
- Returns the response status code of
400or higher
- Returns the response status code of
- getMessage()
- Returns the exception message
- getBody()
- If there is a response body it returns it as an
Array. Otherwise it returnsnull.
- If there is a response body it returns it as an
- getRequest()
- Returns an array with the request values
method,url,headers,bodywhendebugistrue
- Returns an array with the request values
See contributing.
This fork migrated from HTTPlug to PSR-18 HTTP Client standard.
-
Constructor signature changed:
// Old (v2.x with HTTPlug) $sparky = new SparkPost($httpClient, ['key' => 'YOUR_API_KEY']); // New (v3.x with PSR-18) use Symfony\Component\HttpClient\Psr18Client; $psr18Client = new Psr18Client(); $sparky = new SparkPost( $psr18Client, // ClientInterface $psr18Client, // RequestFactoryInterface $psr18Client, // StreamFactoryInterface ['key' => 'YOUR_API_KEY'] );
-
Async support removed: PSR-18 does not support asynchronous requests. All requests are now synchronous.
- Removed
asyncRequest()method - Removed
asyncoption from constructor - Removed
SparkPostPromiseclass - The
request()method now always returnsSparkPostResponseinstead ofSparkPostPromise - Use
->wait()is no longer needed/available
- Removed
-
HTTP client discovery removed: HTTP client and factories must be explicitly provided. No auto-discovery.
-
Dependencies changed:
- Removed:
php-http/httplug,php-http/message,php-http/discovery - Added:
psr/http-client,psr/http-factory,psr/http-message - Recommended:
symfony/http-client,nyholm/psr7
- Removed:
-
Update composer dependencies:
composer remove php-http/httplug php-http/message php-http/discovery composer require symfony/http-client nyholm/psr7
-
Update SparkPost instantiation:
// Replace HTTPlug adapter use Symfony\Component\HttpClient\Psr18Client; $psr18Client = new Psr18Client(); $sparky = new SparkPost($psr18Client, $psr18Client, $psr18Client, ['key' => 'YOUR_API_KEY']);
-
Remove async code:
// Old async code $promise = $sparky->request('GET', 'templates'); $response = $promise->wait(); // New synchronous code $response = $sparky->request('GET', 'templates');
-
Remove promise callbacks:
// Old $promise->then( function($response) { /* ... */ }, function($exception) { /* ... */ } ); // New - use try/catch try { $response = $sparky->request('GET', 'templates'); // handle success } catch (\SparkPost\SparkPostException $e) { // handle error }