1. Go to this page and download the library: Download davidvarney/phannp library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
davidvarney / phannp example snippets
hannp\Client;
$client = new Client('your-api-key-here');
// Create a postcard
// Note: the SDK's Postcards resource expects an array of parameters and
// tcard
$postcard = $client->postcards->get(789);
// Cancel a postcard
$result = $client->postcards->cancel(789);
// If you have a template id and recipient id available, the create call
// will eventually accept a combined payload. For now pass parameters as an
// associative array and
// Create a letter
// The Letters resource supports both creating a merged letter (pass a
// recipient id or array) or posting a pre-merged PDF using post().
// Example: create with a recipient array (mail-merge)
$letter = $client->letters->create([
'firstname' => 'Jane',
'lastname' => 'Doe',
'address1' => '1 Example St',
'city' => 'London',
'postcode' => 'EC1A 1BB',
'country' => 'GB',
]);
// Or: post a pre-merged PDF (country
// Create with an existing recipient and a template id
$letter = $client->letters->create(123, false, 456);
// Pass a URL
$letter = $client->letters->post('GB', false, 'https://example.com/file.pdf');
// Or pass a local resource
$fp = fopen('/path/to/letter.pdf', 'r');
$letter = $client->letters->post('GB', false, $fp);
fclose($fp);
// Create a recipient (positional parameters)
// create(firstname, lastname, address1, address2, address3, city, postcode, country,
// email, phone_number, ref_id, group_id, on_duplicate, test_level)
$recipient = $client->recipients->create(
'Alice', 'Smith', '23 Baker Street', 'Flat 4', '', 'London', 'NW1 6XE', 'GB',
'[email protected]', '+447911123456', 'alice-001', 0, 'update', 'standard'
);
// Get a recipient
$recipient = $client->recipients->get(123);
// List recipients
// list(groupId, offset = 0, limit = 0) — pass groupId to filter, use 0 for all groups
$recipients = $client->recipients->list(0, 0, 10);
// Delete a recipient
$result = $client->recipients->delete(123);
// Import recipients in bulk
// import(file, group_id, duplicates, no_headings, mappings)
// - file: path to CSV/XLS, a base64 CSV string, or a URL to the file
// - group_id: integer group to import into (0 = all / none)
// - duplicates: 'update' | 'ignore' | 'duplicate'
// - no_headings: true if the file has no header row
// - mappings: comma-separated mapping string when headings differ or no_headings=true
$result = $client->recipients->import(
'/tmp/recipients.csv',
0,
'update',
false,
'firstname,lastname,company,address1,address2,city,postcode,country,email,phone'
);
// Create a group
$group = $client->groups->create(['name' => 'VIP Customers']);
// Get a group
$group = $client->groups->get(123);
// List groups
$groups = $client->groups->list();
// Delete a group
$result = $client->groups->delete(123);
// Add recipient to group
$result = $client->groups->addRecipient(123, 456);
// Remove recipient from group
$result = $client->groups->removeRecipient(123, 456);
// Create an event
$event = $client->events->create(
'recipient-123', // recipient id or external reference
'PURCHASE', // event name
'49.99', // value
true, // conversion
json_encode(['sku' => 'X']), // data
'ref-1' // ref
);
// Optionally: list or get events if supported by your account
$events = $client->events->list(['limit' => 10]);
$event = $client->events->get(123);
// Upload a file
$file = $client->files->upload(['file' => 'path/to/file.pdf']);
// Get a file
$file = $client->files->get(123);
// List files
$files = $client->files->list(['limit' => 10]);
// Delete a file
$result = $client->files->delete(123);
// Upload via file path (SDK will detect and send multipart)
$file = $client->files->upload(['file' => '/path/to/file.pdf']);
// Upload via resource
$fp = fopen('/path/to/file.pdf', 'r');
$file = $client->files->upload(['file' => $fp]);
fclose($fp);
// Upload via URL (the SDK will forward the URL string)
$file = $client->files->upload(['file' => 'https://example.com/file.pdf']);
// Upload a file as part of creating a campaign (file can be a path, resource, or URL)
$campaign = $client->campaigns->create([
'name' => 'Spring Promo',
'file' => '/tmp/flyer.pdf', // local path
]);
// Upload using a resource (useful when streaming files)
$fp = fopen('/tmp/flyer.pdf', 'r');
$campaign = $client->campaigns->create([
'name' => 'Spring Promo',
'file' => $fp,
]);
fclose($fp);
// Or pass a URL if the file is hosted remotely
$campaign = $client->campaigns->create([
'name' => 'Spring Promo',
'file' => 'https://cdn.example.com/flyer.pdf',
]);
[$client, $getHistory] = $this->makeClientWithHistoryPair([
new \GuzzleHttp\Psr7\Response(200, [], json_encode(['ok' => true])),
]);
$client->files->upload(['file' => fopen('/tmp/a.pdf', 'r')]);
$history = $getHistory();
$req = $history[0]['request'];
$this->assertStringContainsString('multipart/form-data', $req->getHeaderLine('Content-Type'));
$parts = $this->parseMultipartBody($req);
$this->assertNotEmpty($parts);
// Find the file part by name and assert filename/content
$filePart = null;
foreach ($parts as $p) {
if ($p['name'] === 'file') {
$filePart = $p;
break;
}
}
$this->assertNotNull($filePart);
$this->assertStringContainsString('%PDF', $filePart['body']);
public function testFileUploadSendsMultipart()
{
[$client, $getHistory] = $this->makeClientWithHistoryPair([
new \GuzzleHttp\Psr7\Response(200, [], json_encode(['ok' => true])),
]);
// The SDK accepts resources, paths or URLs
$fp = fopen(__DIR__ . '/tests/fixtures/sample.pdf', 'r');
$client->files->upload(['file' => $fp]);
fclose($fp);
$history = $getHistory();
$this->assertCount(1, $history);
$req = $history[0]['request'];
// Header should indicate multipart
$this->assertStringContainsString('multipart/form-data', $req->getHeaderLine('Content-Type'));
// Parse parts and assert
$parts = $this->parseMultipartBody($req);
$this->assertNotEmpty($parts);
$filePart = null;
foreach ($parts as $p) {
if ($p['name'] === 'file') {
$filePart = $p;
break;
}
}
$this->assertNotNull($filePart, 'File part missing in multipart body');
$this->assertNotEmpty($filePart['filename']);
$this->assertStringContainsString('%PDF', $filePart['body']);
}
// Get stats
$stats = $client->reporting->getStats(['from' => '2023-01-01', 'to' => '2023-12-31']);
// Get campaign stats
$campaignStats = $client->reporting->getCampaignStats(123);
// Create a campaign
$campaign = $client->campaigns->create(['name' => 'Summer Sale']);
// Get a campaign
$campaign = $client->campaigns->get(123);
// List campaigns
$campaigns = $client->campaigns->list(['limit' => 10]);
// Delete a campaign
$result = $client->campaigns->delete(123);
// Create a selection
$selection = $client->selections->create(['name' => 'Active Customers']);
// Get a selection
$selection = $client->selections->get(123);
// List selections
$selections = $client->selections->list(['limit' => 10]);
// Get account information
$account = $client->account->get();
// Get account balance
$balance = $client->account->getBalance();
// Top up account
$result = $client->account->topUp(['amount' => 100]);
[$client, $getHistory] = $this->makeClientWithHistoryPair([
new \GuzzleHttp\Psr7\Response(200, [], json_encode(['ok' => true])),
]);
$client->campaigns->approve(123);
// Get a fresh copy of the recorded history
$history = $getHistory();
$this->assertCount(1, $history);
$entry = $history[0];
$request = $entry['request'];
// Assert request method and URI
$this->assertSame('POST', $request->getMethod());
$this->assertStringContainsString('campaigns/approve', (string) $request->getUri());
// Assert headers
$this->assertStringContainsString('application/x-www-form-urlencoded', $request->getHeaderLine('Content-Type'));
// Note: the SDK appends the API key to the request as a query parameter.
// For POST/PUT/DELETE requests the api_key will be present in the request URI
// query (Guzzle's 'query' option) rather than embedded in the form body.
// Inspect the URI query for the api_key and the body for other params.
$this->assertStringContainsString('api_key=test_api_key', $request->getUri()->getQuery());
// Inspect form body for other parameters
$body = (string) $request->getBody();
parse_str($body, $params);
$this->assertSame('123', $params['id']);
$history = [];
$client = $this->makeClientWithHistory([
new \GuzzleHttp\Psr7\Response(200, [], json_encode(['ok' => true])),
], [], $history);
$client->recipients->create([
'firstname' => 'Jane',
'lastname' => 'Doe',
'address1' => '1 Example St',
'city' => 'London',
'postcode' => 'EC1A 1BB',
'country' => 'GB',
]);
$this->assertNotEmpty($history);
$req = $history[0]['request'];
$this->assertSame('POST', $req->getMethod());
// For multipart requests (file uploads) inspect the Content-Type and parsed parts
$this->assertStringContainsString('multipart/form-data', $req->getHeaderLine('Content-Type'));
// Use the test helpers to parse multipart parts and assert filename
$parts = $this->parseMultipartBody($req);
$filePart = null;
foreach ($parts as $p) {
if ($p['name'] === 'file') {
$filePart = $p;
break;
}
}
$this->assertNotNull($filePart);
$this->assertSame('a.pdf', $filePart['filename']);
$this->assertStringContainsString('%PDF', $filePart['body']);
// Get list of countries
$countries = $client->tools->getCountries();
// Get regions for a country
$regions = $client->tools->getRegions('US');
// Get pricing
$pricing = $client->tools->getPricing();
use Phannp\Utilities\Countries;
$allowed = Countries::allowedCodes(); // ['US', 'GB']
if (!Countries::isValid('US')) {
// handle invalid
}
// Send an SMS
$sms = $client->sms->send([
'to' => '+1234567890',
'message' => 'Hello from Phannp!',
]);
// Get an SMS
$sms = $client->sms->get(123);
// List SMS messages
$messages = $client->sms->list(['limit' => 10]);
use Phannp\Client;
use Phannp\Exceptions\ApiException;
try {
$client = new Client('your-api-key');
$postcard = $client->postcards->get(123);
} catch (ApiException $e) {
echo 'API Error: ' . $e->getMessage();
}
use Phannp\Client;
use Phannp\Exceptions\ApiException;
use Phannp\Exceptions\PhannpException;
try {
$client = new Client('your-api-key');
// This may throw PhannpException for client-side validation
$client->addresses->validate(['address1' => '1', 'country' => 'XX']);
} catch (PhannpException $e) {
// Validation or SDK usage error (e.g. wrong parameter type)
echo 'Client error: ' . $e->getMessage();
} catch (ApiException $e) {
// HTTP/API error. ApiException wraps the underlying Guzzle exception.
// You can inspect the HTTP status code and upstream message.
echo 'API Error: ' . $e->getMessage();
$code = $e->getCode();
// For detailed debugging you can inspect the previous exception
$previous = $e->getPrevious();
if ($previous) {
echo '\nUpstream: ' . $previous->getMessage();
}
}
Inspecting API response JSON
ApiException exposes helpers to inspect the HTTP details returned by the API. Use `getResponseJson()` to attempt decoding a JSON body (returns an associative array or `null` if decoding fails):