Download the PHP package davidvarney/phannp without Composer
On this page you can find all versions of the php package davidvarney/phannp. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download davidvarney/phannp
More information about davidvarney/phannp
Files in davidvarney/phannp
Package phannp
Short Description PHP SDK for the Stannp Direct Mail API
License MIT
Informations about the package phannp
Phannp
A modern PHP SDK for the Stannp Direct Mail API.
Installation
Install via Composer:
Developer & testing guide (short)
If you're contributing or running tests locally, here's a short guide.
-
Run the full test-suite:
-
Run a single test file for faster feedback:
-
Use
tests/TestCase.phphelpers:makeClient()— returns aPhannp\\Clientconfigured with a Guzzle MockHandler preloaded with responses.makeClientWithHistoryPair()— returns[$client, $getHistory]where$getHistory()returns recorded request history (useful to assert outgoing request shapes).parseMultipartBody()/getMultipartParts()— test helpers to assert multipart uploads.
- Error assertion helpers:
callAndCatchApiException()— run a callable that should raiseApiExceptionand return the caught exception for assertions.assertApiErrorJsonHasPath()— assert nested JSON error paths inApiException::getResponseJson().
Local commit note
Most recent local commit message on this branch:
Discussion: this commit tightens the Tools resource API and test coverage:
Tools::pdfMerge()now validates input client-side (requires a non-empty array of strings).- Tests in
tests/Resources/ToolsTest.phpwere updated to assert query param encoding, edge cases and history-based request assertions.
If you pushed this branch, include the commit hash in the changelog entry and consider mentioning the validation behavior in the public README examples.
Requirements
- PHP 7.4 or higher
- Guzzle HTTP client 7.0 or higher
Usage
Initialize the Client
Postcards
Postcards::create parameters
- size (string) — postcard size, e.g. '4x6', '6x9', '6x11'. Must be provided in the parameters array:
['size' => '4x6']. - (future) recipient/template/file — the SDK may accept additional params; currently pass required parameters as an associative array to
create().
Example using a template (future-proof):
Letters
Letters::create parameters
- recipient (mixed) — mandatory. Either an existing recipient ID (int/string) or an associative array defining a new recipient (keys like firstname, lastname, address1, city, postcode, country).
- test (bool) — optional. Generate a sample PDF without dispatch when true.
- template (mixed) — optional. Template ID to use for mail-merge.
- file (mixed) — optional. Instead of template/pages, you can pass a local file path, resource (fopen), or a URL to a PDF/DOC file.
- duplex (bool) — optional. Defaults to true; set false to print only on the front.
- clearzone (bool) — optional. Defaults to false; overlay clear zones with white when true.
- post_unverified (bool) — optional. Defaults to true; set to false to prevent posting unverified addresses.
- tags (string) — optional. Comma-separated tags.
- addons (string) — optional. Comma-separated addon codes, e.g. 'FIRST_CLASS'.
Example — create using a template id and recipient id:
Example — post a pre-merged file (resource or URL):
Recipients
Groups
Events
Files
Multipart uploads (files)
The SDK supports uploading files either by file path, by resource (e.g. fopen), or by URL. In tests we use Guzzle's history middleware to inspect outgoing requests and assert multipart bodies.
Upload examples:
Additional upload examples
Asserting multipart in tests
Use the test helper makeClientWithHistoryPair() to capture outgoing requests and
parseMultipartBody() / getMultipartParts() to inspect multipart parts.
Concrete test assertion example (full snippet)
Reporting
Campaigns
Selections
Account
Account top-up caveats
- Top-ups are forwarded directly to the Stannp API. Confirm the account
currencyand available balance withgetBalance()before callingtopUp()to avoid unexpected charges. - The SDK forwards whatever
amountyou send as-is. If you need idempotency for retries, implement an external idempotency key on your side and avoid callingtopUp()multiple times for the same logical operation. - Rate limits and limits on top-up amounts are enforced by Stannp; the SDK will surface API errors as
Phannp\Exceptions\ApiExceptionwith the upstream message and HTTP status code.
Addresses
Notes on Addresses validation
- The
Addresses::validate()helper accepts only the following keys:company,address1,address2,city,state,zipcode, andcountry. - All provided values must be strings.
countrymust be an ISO 3166-1 alpha-2 code. For compatibility with Stannp the SDK currently accepts onlyUSandGBand will suggest the allowed codes on error (for example: use "US" or "GB").stateandcountryvalues are normalized to uppercase before being sent to the API (e.g.gb->GB,ny->NY).
If you need to assert what the SDK sends, the test helpers add a Guzzle history middleware so any outgoing requests can be inspected in tests.
Asserting outgoing requests (examples)
Example — ergonomic pair helper (recommended):
Example — manual history (pass-by-reference):
Notes:
- Prefer
makeClientWithHistoryPair()in most tests — it returns a closure that always reads the up-to-date recorded history. - For multipart bodies there isn't a convenient parser in tests; assert the
Content-Typeincludesmultipart/form-dataand inspect the raw body for expected filenames or boundaries.
Quick helper: name => body map
If you only care about the parts' bodies (not filenames or disposition details) use getMultipartParts() which returns a simple name=>body map:
Tools
Utilities and Countries helper
This SDK includes a small utilities module under src/Utilities/.
Phannp\Utilities\Countriesexposes helpers for country validation. UseCountries::allowedCodes()to get the canonical list of allowed country codes used by the SDK (currently['US', 'GB']) andCountries::isValid($code)to check validity.
Example:
SMS
Error Handling
The SDK throws exceptions when API requests fail:
Changelog (recent)
For a full changelog see CHANGELOG.md in the project root.
-
2025-10-09: Refactor of Resources API
Letters::create()now accepts arecipientparameter (id or array) and supportstemplate,file(path/resource/URL),duplex,clearzone, and other flags.Letters::post()added for posting pre-merged PDF/DOC files (accepts country and file resource/URL).Postcards::create()now requires an associative array of parameters and must include asizekey (e.g.['size' => '4x6']). Other postcard parameters may be added in future SDK releases.- Tests and README updated to reflect these API changes.
-
2025-10-20: API key handling change
- The SDK now appends the client's
api_keyas a query parameter (api_key) on all requests. - For POST, PUT and DELETE requests the
api_keyis sent via Guzzle'squeryoption and any trailing/on provided endpoints is trimmed before sending. - Migration note: If your code previously relied on the SDK placing the API key inside request bodies or using an
autharray, update any tests or integrations to look forapi_keyin the request query string. This change avoids surprises when endpoints include existing query strings and keeps parameter handling consistent across request methods.
- The SDK now appends the client's
- 2025-10-20: Postcards resource update
Postcards::create()now requires an associative array of parameters (no longer accepts a plain size string). Thesizekey is required (e.g.['size' => '4x6']).- Migration note: Update any code or tests that previously called
create('4x6')to passcreate(['size' => '4x6'])instead. This validation helps prevent ambiguous calls and makes future postcard options extensible.
More detailed error handling
The SDK also defines Phannp\Exceptions\PhannpException for client-side errors (validation, argument issues) and Phannp\Exceptions\ApiException for server/API errors. Example showing both:
php try { $client->campaigns->approve(123); } catch (ApiException $e) { $status = $e->getStatusCode(); $raw = $e->getResponseBody(); $json = $e->getResponseJson();
echo "Status: {$status}\n";
if ($json) {
// Inspect structured error fields
echo 'API message: ' . ($json['message'] ?? $json['error'] ?? json_encode($json));
} else {
// Fallback to raw body
echo 'Raw response: ' . $raw;
}
}
License
MIT
Testing
This repository includes a PHPUnit test suite that exercises the Phannp\Client and every resource under src/Resources.
What the tests cover
- Each resource class has a corresponding test in
tests/Resources/that verifies the public methods delegate to the client and return the parsed API response. tests/ClientTest.phpensures theClientcan send GET/POST/PUT/DELETE requests and that the resource properties (e.g.$client->postcards) are correctly instantiated.- Tests are isolated from the network by using Guzzle's
MockHandler, so no real API calls or API keys are required.
How the tests work
tests/TestCase.phpprovides amakeClient(array $responses = [], array $options = [])helper. It builds aPhannp\Clientconfigured with a GuzzleMockHandlerpreloaded with the responses you provide.- Each test queues one or more
GuzzleHttp\Psr7\Responseobjects. When the SDK makes an HTTP request, the MockHandler returns the next queued response.
Run tests locally
-
Install dependencies (from the project root):
- Run the test suite with the vendor PHPUnit binary:
Run an individual test file:
Continuous Integration
The tests are self-contained and suitable for CI. A simple GitHub Actions workflow should install composer dependencies and run ./vendor/bin/phpunit --configuration phpunit.xml.dist.
Extending the tests
- To assert the exact request URI/method or headers, add a middleware to the Guzzle handler stack in
tests/TestCase.phpand capture the request objects for assertions. - Add negative/error cases by queuing responses with non-2xx status codes and asserting
Phannp\Exceptions\ApiExceptionis thrown.