PHP code example of gigerit / laravel-swiss-post-postcard-api-client

1. Go to this page and download the library: Download gigerit/laravel-swiss-post-postcard-api-client 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/ */

    

gigerit / laravel-swiss-post-postcard-api-client example snippets


use Gigerit\PostcardApi\PostcardApi;
use Gigerit\PostcardApi\DTOs\Address\RecipientAddress;

class PostcardController extends Controller
{
    public function __construct(private PostcardApi $postcardApi) {}

    public function sendPostcard()
    {
        // Create recipient address
        $recipient = new RecipientAddress(
            street: 'Musterstrasse',
            zip: '8000',
            city: 'Zürich',
            country: 'CH',
            firstname: 'John',
            lastname: 'Doe',
            houseNr: '123'
        );

        // Send postcard
        $result = $this->postcardApi->postcards()->createComplete(
            recipientAddress: $recipient,
            imagePath: storage_path('postcards/my-image.jpg'),
            senderText: 'Hello from Laravel!'
        );

        return response()->json(['cardKey' => $result->cardKey]);
    }
}

use Gigerit\PostcardApi\Facades\PostcardApi;
use Gigerit\PostcardApi\DTOs\Address\RecipientAddress;

// Check campaign quota
$stats = PostcardApi::campaigns()->getDefaultCampaignStatistics();
if ($stats->freeToSendPostcards === 0) {
    throw new Exception('No postcards remaining in campaign');
}

// Create and send postcard
$recipient = new RecipientAddress(/* ... */);
$result = PostcardApi::postcards()->createComplete(
    recipientAddress: $recipient,
    imagePath: 'path/to/image.jpg'
);

use Gigerit\PostcardApi\PostcardApi;
use Gigerit\PostcardApi\Connectors\SwissPostConnector;

// Auto-authenticate using configured OAuth2 credentials
$api = new PostcardApi();

// Or provide specific access token
$api = new PostcardApi('your_access_token_here');

// Using Saloon's OAuth2 directly
$connector = new SwissPostConnector();
$authenticator = $connector->getAccessToken(); // Uses client credentials grant
$connector->authenticate($authenticator);

$postcards = $api->postcards();

// Create postcards
$result = $postcards->create($campaignKey, $postcard);
$result = $postcards->createComplete($recipient, $imagePath, $sender, $text);

// Upload content
$postcards->uploadImage($cardKey, $imagePath);
$postcards->uploadSenderText($cardKey, $text);
$postcards->uploadSenderAddress($cardKey, $senderAddress);
$postcards->uploadRecipientAddress($cardKey, $recipientAddress);

// Manage postcards
$postcards->approve($cardKey);
$state = $postcards->getState($cardKey);
$frontPreview = $postcards->getPreviewFront($cardKey);
$backPreview = $postcards->getPreviewBack($cardKey);

$branding = $api->branding();

// Text branding
$branding->addSimpleText($cardKey, 'Your Company', '#FF0000', '#FFFFFF');

// QR code branding
$branding->addSimpleQRCode($cardKey, 'https://yoursite.com', 'Visit us!');

// Image branding
$branding->uploadImage($cardKey, 'path/to/logo.jpg');
$branding->uploadStamp($cardKey, 'path/to/stamp.jpg');

$campaigns = $api->campaigns();

// Get statistics
$stats = $campaigns->getDefaultCampaignStatistics();
$stats = $campaigns->getStatistics($campaignKey);

// Check quota
$hasQuota = $campaigns->hasRemainingQuota($campaignKey);
$remaining = $campaigns->getRemainingQuota($campaignKey);

use Gigerit\PostcardApi\Exceptions\SwissPostApiException;
use Gigerit\PostcardApi\Enums\ErrorCode;

try {
    $result = $api->postcards()->create();

    // Check for warnings
    if ($result->hasWarnings()) {
        foreach ($result->getWarningMessages() as $warning) {
            Log::warning("Postcard warning: {$warning}");
        }
    }

} catch (SwissPostApiException $e) {
    // API errors (quota exceeded, invalid data, etc.)
    Log::error("Swiss Post API error: {$e->getMessage()}");

} catch (\InvalidArgumentException $e) {
    // Validation errors (invalid image dimensions, text too long, etc.)
    Log::error("Validation error: {$e->getMessage()}");
}

// Error codes are available as enums
$errorCode = ErrorCode::CAMPAIGN_QUOTA_EXCEEDED;
echo $errorCode->getDescription(); // "Campaign quota exceeded"

use Gigerit\PostcardApi\Validation\PostcardValidator;
use Gigerit\PostcardApi\Enums\ImageDimensions;

// Validate addresses
$errors = PostcardValidator::validateRecipientAddress($recipient);

// Validate text
$errors = PostcardValidator::validateSenderText($text);

// Validate images
$errors = PostcardValidator::validateImageDimensions(
    '/path/to/image.jpg',
    ImageDimensions::FRONT_IMAGE
);

// Disable validation if needed
$api->postcards()->uploadImage($cardKey, $path, null, false); // Skip validation
bash
php artisan vendor:publish --tag="swiss-post-postcard-api-client-config"