Stars: 195
Forks: 81
Pull Requests: 87
Issues: 125
Watchers: 62
Last Updated: 2023-06-28 11:43:44
Sign up for a SparkPost account and visit our Developer Hub for even more content.
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.
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.
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,
]);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']);
?>httpClient
options
String or Arrayoptions.key
Stringoptions.host
Stringapi.sparkpost.comoptions.protocol
Stringhttpsoptions.port
Numberoptions.version
Stringv1options.async
Booleantrueasync defines if the request function sends an asynchronous or synchronous request. If your client does not support async requests set this to falseoptions.retries
Number0retries controls how many API call attempts the client makes after receiving a 5xx responseoptions.debug
Booleanfalsedebug is true, then all SparkPostResponse and SparkPostException instances will return any array of the request values through the function getRequestmethod
Stringuri
Stringpayload
ArrayGET 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
ArraySends a synchronous request to the SparkPost API and returns a SparkPostResponse
Sends an asynchronous request to the SparkPost API and returns a SparkPostPromise
httpClient
options
Arraypayload - see request optionspayload.cc
Arraypayload.bcc
Array<?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:
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";
}Asynchronous an be handled in two ways: by passing callbacks or waiting for the promise to be fulfilled. Waiting acts like synchronous request.
$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";$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();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.
400 or higherArray. Otherwise it returns null.method, url, headers, body when debug is trueSee contributing.