{"id":17476776,"url":"https://github.com/sparkpost/php-sparkpost","last_synced_at":"2025-05-15T17:01:21.347Z","repository":{"id":21981994,"uuid":"25306898","full_name":"SparkPost/php-sparkpost","owner":"SparkPost","description":"SparkPost client library for PHP","archived":false,"fork":false,"pushed_at":"2023-10-23T12:53:27.000Z","size":445,"stargazers_count":196,"open_issues_count":12,"forks_count":94,"subscribers_count":57,"default_branch":"master","last_synced_at":"2025-04-07T21:15:10.065Z","etag":null,"topics":["client-library","email","php","sparkpost"],"latest_commit_sha":null,"homepage":"https://www.sparkpost.com/","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/SparkPost.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":"AUTHORS.md","dei":null,"publiccode":null,"codemeta":null}},"created_at":"2014-10-16T14:47:44.000Z","updated_at":"2025-01-22T08:56:25.000Z","dependencies_parsed_at":"2024-06-18T10:59:15.438Z","dependency_job_id":"bf732a17-0f4e-4085-af93-8a1713ea72fc","html_url":"https://github.com/SparkPost/php-sparkpost","commit_stats":{"total_commits":249,"total_committers":35,"mean_commits":7.114285714285714,"dds":0.7389558232931727,"last_synced_commit":"2c7f60d27afbbbea05c72cb33ef9094f9cfceb88"},"previous_names":[],"tags_count":17,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SparkPost%2Fphp-sparkpost","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SparkPost%2Fphp-sparkpost/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SparkPost%2Fphp-sparkpost/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SparkPost%2Fphp-sparkpost/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/SparkPost","download_url":"https://codeload.github.com/SparkPost/php-sparkpost/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254384929,"owners_count":22062421,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["client-library","email","php","sparkpost"],"created_at":"2024-10-18T19:10:33.958Z","updated_at":"2025-05-15T17:01:21.271Z","avatar_url":"https://github.com/SparkPost.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003ca href=\"https://www.sparkpost.com\"\u003e\u003cimg src=\"https://www.sparkpost.com/sites/default/files/attachments/SparkPost_Logo_2-Color_Gray-Orange_RGB.svg\" width=\"200px\"/\u003e\u003c/a\u003e\n\n[Sign up](https://app.sparkpost.com/join?plan=free-0817?src=Social%20Media\u0026sfdcid=70160000000pqBb\u0026pc=GitHubSignUp\u0026utm_source=github\u0026utm_medium=social-media\u0026utm_campaign=github\u0026utm_content=sign-up) for a SparkPost account and visit our [Developer Hub](https://developers.sparkpost.com) for even more content.\n\n# SparkPost PHP Library\n\n[![Travis CI](https://travis-ci.org/SparkPost/php-sparkpost.svg?branch=master)](https://travis-ci.org/SparkPost/php-sparkpost)\n[![Coverage Status](https://coveralls.io/repos/SparkPost/php-sparkpost/badge.svg?branch=master\u0026service=github)](https://coveralls.io/github/SparkPost/php-sparkpost?branch=master)\n[![Downloads](https://img.shields.io/packagist/dt/sparkpost/sparkpost.svg?maxAge=3600)](https://packagist.org/packages/sparkpost/sparkpost)\n[![Packagist](https://img.shields.io/packagist/v/sparkpost/sparkpost.svg?maxAge=3600)](https://packagist.org/packages/sparkpost/sparkpost)\n\nThe official PHP library for using [the SparkPost REST API](https://developers.sparkpost.com/api/).\n\nBefore 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.\n\n## Installation\n**Please note: The composer package `sparkpost/php-sparkpost` has been changed to `sparkpost/sparkpost` starting with version 2.0.**\n\nThe recommended way to install the SparkPost PHP Library is through composer.\n\n```\n# Install Composer\ncurl -sS https://getcomposer.org/installer | php\n```\n\nSparkpost requires php-http client (see [Setting up a Request Adapter](#setting-up-a-request-adapter)). There are several [providers](https://packagist.org/providers/php-http/client-implementation) available. If you were using guzzle6 your install might look like this.\n\n```\ncomposer require php-http/guzzle6-adapter \"^1.1\"\ncomposer require guzzlehttp/guzzle \"^6.0\"\n```\n\nNext, run the Composer command to install the SparkPost PHP Library:\n\n```\ncomposer require sparkpost/sparkpost\n```\n\nAfter installing, you need to require Composer's autoloader:\n\n```php\nrequire 'vendor/autoload.php';\nuse SparkPost\\SparkPost;\n```\n\n**Note:** Without composer the costs outweigh the benefits of using the PHP client library. A simple function like the one in [issue #164](https://github.com/SparkPost/php-sparkpost/issues/164#issuecomment-289888237) wraps the SparkPost API and makes it easy to use the API without resolving the composer dependencies.\n\n## Running with IDEs\n\nWhen 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`:\n\n```\nException has occurred.\nHttp\\Discovery\\Exception\\PuliUnavailableException: Puli Factory is not available\n```\n\n[This is usual](http://docs.php-http.org/en/latest/discovery.html#puli-factory-is-not-available). Puli is not required to use the library. You can resume running after the exception.\n\nYou can prevent the exception, by setting the discovery strategies, prior to creating the adapter object:\n```php\n// Prevent annoying \"Puli exception\" during work with xdebug / IDE\n// See https://github.com/getsentry/sentry-php/issues/801\n\\Http\\Discovery\\ClassDiscovery::setStrategies([\n        // \\Http\\Discovery\\Strategy\\PuliBetaStrategy::class, // Deliberately disabled\n        \\Http\\Discovery\\Strategy\\CommonClassesStrategy::class,\n        \\Http\\Discovery\\Strategy\\CommonPsr17ClassesStrategy::class,\n]);\n```\n\n## Setting up a Request Adapter\n\nBecause of dependency collision, we have opted to use a request adapter rather than\nrequiring a request library.  This means that your application will need to pass in\na request adapter to the constructor of the SparkPost Library.  We use the [HTTPlug](https://github.com/php-http/httplug) in SparkPost. Please visit their repo for a list of supported [clients and adapters](http://docs.php-http.org/en/latest/clients.html).  If you don't currently use a request library, you will\nneed to require one and create a client from it and pass it along. The example below uses the GuzzleHttp Client Library.\n\nA Client can be setup like so:\n\n```php\n\u003c?php\nrequire 'vendor/autoload.php';\n\nuse SparkPost\\SparkPost;\nuse GuzzleHttp\\Client;\nuse Http\\Adapter\\Guzzle6\\Client as GuzzleAdapter;\n\n$httpClient = new GuzzleAdapter(new Client());\n$sparky = new SparkPost($httpClient, ['key'=\u003e'YOUR_API_KEY']);\n?\u003e\n```\n\n## Initialization\n#### new Sparkpost(httpClient, options)\n* `httpClient`\n    * Required: Yes\n    * HTTP client or adapter supported by HTTPlug\n* `options`\n    * Required: Yes\n    * Type: `String` or `Array`\n    * A valid Sparkpost API key or an array of options\n* `options.key`\n    * Required: Yes\n    * Type: `String`\n    * A valid Sparkpost API key\n* `options.host`\n    * Required: No\n    * Type: `String`\n    * Default: `api.sparkpost.com`\n* `options.protocol`\n    * Required: No\n    * Type: `String`\n    * Default: `https`\n* `options.port`\n    * Required: No\n    * Type: `Number`\n    * Default: 443\n* `options.version`\n    * Required: No\n    * Type: `String`\n    * Default: `v1`\n* `options.async`\n    * Required: No\n    * Type: `Boolean`\n    * Default: `true`\n    * `async` defines if the `request` function sends an asynchronous or synchronous request. If your client does not support async requests set this to `false`\n* `options.retries`\n    * Required: No\n    * Type: `Number`\n    * Default: `0`\n    * `retries` controls how many API call attempts the client makes after receiving a 5xx response\n* `options.debug`\n    * Required: No\n    * Type: `Boolean`\n    * Default: `false`\n    * If `debug` is true, then all `SparkPostResponse` and `SparkPostException` instances will return any array of the request values through the function `getRequest`\n\n## Methods\n### request(method, uri [, payload [, headers]])\n* `method`\n    * Required: Yes\n    * Type: `String`\n    * HTTP method for request\n* `uri`\n    * Required: Yes\n    * Type: `String`\n    * The URI to receive the request\n* `payload`\n    * Required: No\n    * Type: `Array`\n    * 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.\n* `headers`\n    * Required: No\n    * Type: `Array`\n    * Custom headers to be sent with the request.\n\n### syncRequest(method, uri [, payload [, headers]])\nSends a synchronous request to the SparkPost API and returns a `SparkPostResponse`\n\n### asyncRequest(method, uri [, payload [, headers]])\nSends an asynchronous request to the SparkPost API and returns a `SparkPostPromise`\n\n### setHttpClient(httpClient)\n* `httpClient`\n    *  Required: Yes\n    * HTTP client or adapter supported by HTTPlug\n\n### setOptions(options)\n* `options`\n    *  Required: Yes\n    *  Type: `Array`\n    * See constructor\n\n## Endpoints\n### transmissions\n* **post(payload)**\n    * `payload` - see request options\n    * `payload.cc`\n        * Required: No\n        * Type: `Array`\n        * Recipients to receive a carbon copy of the transmission\n    * `payload.bcc`\n        * Required: No\n        * Type: `Array`\n        * Recipients to discreetly receive a carbon copy of the transmission\n\n## Examples\n\n### Send An Email Using The Transmissions Endpoint\n```php\n\u003c?php\nrequire 'vendor/autoload.php';\n\nuse SparkPost\\SparkPost;\nuse GuzzleHttp\\Client;\nuse Http\\Adapter\\Guzzle6\\Client as GuzzleAdapter;\n\n$httpClient = new GuzzleAdapter(new Client());\n// Good practice to not have API key literals in code - set an environment variable instead\n// For simple example, use synchronous model\n$sparky = new SparkPost($httpClient, ['key' =\u003e getenv('SPARKPOST_API_KEY'), 'async' =\u003e false]);\n\ntry {\n    $response = $sparky-\u003etransmissions-\u003epost([\n        'content' =\u003e [\n            'from' =\u003e [\n                'name' =\u003e 'SparkPost Team',\n                'email' =\u003e 'from@sparkpostbox.com',\n            ],\n            'subject' =\u003e 'First Mailing From PHP',\n            'html' =\u003e '\u003chtml\u003e\u003cbody\u003e\u003ch1\u003eCongratulations, {{name}}!\u003c/h1\u003e\u003cp\u003eYou just sent your very first mailing!\u003c/p\u003e\u003c/body\u003e\u003c/html\u003e',\n            'text' =\u003e 'Congratulations, {{name}}!! You just sent your very first mailing!',\n        ],\n        'substitution_data' =\u003e ['name' =\u003e 'YOUR_FIRST_NAME'],\n        'recipients' =\u003e [\n            [\n                'address' =\u003e [\n                    'name' =\u003e 'YOUR_NAME',\n                    'email' =\u003e 'YOUR_EMAIL',\n                ],\n            ],\n        ],\n        'cc' =\u003e [\n            [\n                'address' =\u003e [\n                    'name' =\u003e 'ANOTHER_NAME',\n                    'email' =\u003e 'ANOTHER_EMAIL',\n                ],\n            ],\n        ],\n        'bcc' =\u003e [\n            [\n                'address' =\u003e [\n                    'name' =\u003e 'AND_ANOTHER_NAME',\n                    'email' =\u003e 'AND_ANOTHER_EMAIL',\n                ],\n            ],\n        ],\n    ]);\n    } catch (\\Exception $error) {\n        var_dump($error);\n    }\nprint($response-\u003egetStatusCode());\n$results = $response-\u003egetBody()['results'];\nvar_dump($results);\n?\u003e\n```\n\nMore examples [here](./examples/):\n### [Transmissions](./examples/transmissions/)\n- Create with attachment\n- Create with recipient list\n- Create with cc and bcc\n- Create with template\n- Create\n- Delete (scheduled transmission by campaign_id *only*)\n\n### [Templates](./examples/templates/)\n- Create\n- Get\n- Get (list) all\n- Update\n- Delete\n\n### [Message Events](./examples/message-events/)\n- get\n- get (with retry logic)\n\n### Send An API Call Using The Base Request Function\n\nWe provide a base request function to access any of our API resources.\n```php\n\u003c?php\nrequire 'vendor/autoload.php';\n\nuse SparkPost\\SparkPost;\nuse GuzzleHttp\\Client;\nuse Http\\Adapter\\Guzzle6\\Client as GuzzleAdapter;\n\n$httpClient = new GuzzleAdapter(new Client());\n$sparky = new SparkPost($httpClient, [\n    'key' =\u003e getenv('SPARKPOST_API_KEY'),\n    'async' =\u003e false]);\n\n$webhookId = 'afd20f50-865a-11eb-ac38-6d7965d56459';\n$response = $sparky-\u003erequest('DELETE', 'webhooks/' . $webhookId);\nprint($response-\u003egetStatusCode());\n?\u003e\n```\n\n\u003e Be sure to not have a leading `/` in your resource URI.\n\nFor complete list of resources, refer to [API documentation](https://developers.sparkpost.com/api/).\n\n## Handling Responses\nThe API calls either return a `SparkPostPromise` or `SparkPostResponse` depending on if `async` is `true` or `false`\n\n### Synchronous\n```php\n$sparky-\u003esetOptions(['async' =\u003e false]);\ntry {\n    $response = ... // YOUR API CALL GOES HERE\n\n    echo $response-\u003egetStatusCode().\"\\n\";\n    print_r($response-\u003egetBody()).\"\\n\";\n}\ncatch (\\Exception $e) {\n    echo $e-\u003egetCode().\"\\n\";\n    echo $e-\u003egetMessage().\"\\n\";\n}\n```\n\n### Asynchronous\nAsynchronous an be handled in two ways: by passing callbacks or waiting for the promise to be fulfilled. Waiting acts like synchronous request.\n##### Wait (Synchronous)\n```php\n\n$promise = ... // YOUR API CALL GOES HERE\n\ntry {\n    $response = $promise-\u003ewait();\n    echo $response-\u003egetStatusCode().\"\\n\";\n    print_r($response-\u003egetBody()).\"\\n\";\n} catch (\\Exception $e) {\n    echo $e-\u003egetCode().\"\\n\";\n    echo $e-\u003egetMessage().\"\\n\";\n}\n\necho \"I will print out after the promise is fulfilled\";\n```\n\n##### Then (Asynchronous)\n```php\n$promise = ... // YOUR API CALL GOES HERE\n\n$promise-\u003ethen(\n    // Success callback\n    function ($response) {\n        echo $response-\u003egetStatusCode().\"\\n\";\n        print_r($response-\u003egetBody()).\"\\n\";\n    },\n    // Failure callback\n    function (Exception $e) {\n        echo $e-\u003egetCode().\"\\n\";\n        echo $e-\u003egetMessage().\"\\n\";\n    }\n);\n\necho \"I will print out before the promise is fulfilled\";\n\n// You can combine multiple promises using \\GuzzleHttp\\Promise\\all() and other functions from the library.\n$promise-\u003ewait();\n```\n\n## Handling Exceptions\nAn 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.\n\n### SparkPostException\n* **getCode()**\n    * Returns the response status code of `400` or higher\n* **getMessage()**\n    * Returns the exception message\n* **getBody()**\n    * If there is a response body it returns it as an `Array`. Otherwise it returns `null`.\n* **getRequest()**\n    * Returns an array with the request values `method`, `url`, `headers`, `body` when `debug` is `true`\n\n\n### Contributing\nSee [contributing](https://github.com/SparkPost/php-sparkpost/blob/master/CONTRIBUTING.md).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsparkpost%2Fphp-sparkpost","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsparkpost%2Fphp-sparkpost","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsparkpost%2Fphp-sparkpost/lists"}