Sendery
Sendery

言語別 SDK

PHP

PHP から Sendery の公開済みテンプレートを送信します。

インストール
composer require sendery/php:^0.1
ソースコード

動作環境

PHP 8.3 以上と cURL 拡張が必要です。

設定

name と action_url を使う welcome テンプレートを公開し、プロジェクトの API キーを作成します。サーバーの環境変数 SENDERY_API_KEY に保存してください。

Shell
export SENDERY_API_KEY="your_project_api_key"

メールを送信

受付済みメールの id と status が返ります。 変数がない場合は data: [] を渡します。SDK が空の JSON オブジェクトに変換します。

PHP
require 'vendor/autoload.php';

use Sendery\Client;

$sendery = new Client(getenv('SENDERY_API_KEY'));
$receipt = $sendery->send(
    to: '[email protected]',
    template: 'welcome',
    data: ['name' => 'Alex', 'action_url' => 'https://example.com/start'],
);

echo $receipt['id'];

メールの状態を取得

返された ID で配信状態を確認します。

PHP
$message = $sendery->get($receipt['id']);
echo $message['status'];

送信を再試行

welcome-123 などのキーを 1 通に割り当て、再試行時は元の内容を使います。retry(3) は一時的なエラーに対して最大 3 回の追加試行を行い、send() だけでは 1 回のみ試行します。

PHP
$email = $sendery->prepare(
    to: '[email protected]',
    template: 'welcome',
    data: ['name' => 'Alex', 'action_url' => 'https://example.com/start'],
    idempotencyKey: 'welcome-123',
);
$receipt = $email->retry(3)->send();

エラー処理

SDK の例外を捕捉してステータスとコードを確認します。再試行の待機時間は秒単位です。以下では再試行の例で作成した email を使用します。

PHP
try {
    $receipt = $email->retry(3)->send();
} catch (\Sendery\ApiException $error) {
    error_log($error->status.': '.$error->errorCode);
    // $error->errors contains field-level validation errors.
    // $error->retryAfter is a delay in seconds, when provided.
    throw $error;
}