eaglebirth/eaglebirth-php 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

eaglebirth/eaglebirth-php

Composer 安装命令:

composer require eaglebirth/eaglebirth-php

包简介

Official PHP SDK for EagleBirth API - Email, SMS, WhatsApp, OTP, QR Codes, Vision AI, and User Management

README 文档

README

Official PHP SDK for the EagleBirth API.

Installation

Install via Composer:

composer require eaglebirth/eaglebirth-php

Requirements

  • PHP 7.4 or higher
  • cURL extension
  • JSON extension

Quick Start

<?php

require_once 'vendor/autoload.php';

use EagleBirth\EagleBirth;

// Initialize the client
$client = new EagleBirth('eb_test_your_api_key_here');

// Send an email
$response = $client->email->send(
    email: 'user@example.com',
    subject: 'Welcome!',
    message: 'Thank you for signing up.'
);

print_r($response);

Authentication

Get your API key from https://eaglebirth.com > Dashboard > Apps > API Keys

// Test environment - automatically routes to sandbox.eaglebirth.com
$client = new EagleBirth('eb_test_...');

// Production environment - automatically routes to eaglebirth.com
$client = new EagleBirth('eb_live_...');

Environments

The SDK automatically routes requests to the correct environment based on your API key prefix:

  • Sandbox/Test (eb_test_...) - Routes to sandbox.eaglebirth.com. For development and testing. No charges, uses test data.
  • Production (eb_live_...) - Routes to eaglebirth.com. For live applications. Real charges apply.

No additional configuration needed - just use the appropriate API key and the SDK will automatically connect to the right server. You can create separate API keys for each environment from your dashboard.

Usage Examples

Email

// Send a simple email
$client->email->send(
    email: 'user@example.com',
    subject: 'Welcome to our service',
    message: 'Thank you for joining us!'
);

// Send with custom reply-to and header
$client->email->send(
    email: 'user@example.com',
    subject: 'Account Verification',
    message: 'Please verify your email address.',
    replyTo: 'support@myapp.com',
    header: 'MyApp Verification'
);

SMS

// Send an SMS
$client->sms->send(
    phoneNumber: '+1234567890',
    message: 'Your verification code is 123456'
);

// Get SMS pricing
$prices = $client->sms->getPrices('+1234567890');
print_r($prices);

WhatsApp

// Send a WhatsApp message
$client->whatsapp->send(
    phoneNumber: '+1234567890',
    message: 'Hello from EagleBirth!',
    template: 'normal_message'
);

OTP (One-Time Passwords)

// Send OTP via email
$result = $client->otp->send(
    validationType: 'email',
    email: 'user@example.com',
    codeLength: 6,
    timeout: 180,
    trials: 3
);
$codeId = $result['code_id'];

// Validate the OTP
$validation = $client->otp->validate(
    codeId: $codeId,
    code: '123456'
);

// Check if code was validated
$status = $client->otp->checkValidated($codeId);

QR Code Generation

// Generate a simple QR code
$qr = $client->qr->generate(
    text: 'https://example.com'
);

// Generate with custom colors and logo
$qr = $client->qr->generate(
    text: 'https://example.com',
    image: '/path/to/logo.png',
    imageType: 'object',
    color: '#000000',
    backgroundColor: '#FFFFFF',
    qrType: 'rounded'
);

// Generate with logo from URL
$qr = $client->qr->generate(
    text: 'https://example.com',
    image: 'https://example.com/logo.png',
    imageType: 'link'
);

Vision AI

// Extract face details from an image file
$details = $client->vision->extractFaceDetails(
    image: '/path/to/photo.jpg',
    imageType: 'object'
);

// Extract face details from image URL
$details = $client->vision->extractFaceDetails(
    image: 'https://example.com/photo.jpg',
    imageType: 'link'
);

// Compare two faces
$comparison = $client->vision->compareFaces(
    image1: '/path/to/photo1.jpg',
    image2: '/path/to/photo2.jpg',
    image1Type: 'object',
    image2Type: 'object'
);

// Extract text from image (OCR)
$text = $client->vision->extractText(
    image: '/path/to/document.jpg',
    imageType: 'object'
);

Cloud Storage

// Create a directory
$client->storage->directory->create(
    path: '/photos/vacation/',
    private: 'yes',  // 'yes' or 'no'
    directoryPassword: 'secret123'  // Optional password protection
);

// Upload a file
$client->storage->file->upload(
    file: '/path/to/document.pdf',
    path: '/documents/report.pdf',
    private: 'no',
    filePassword: 'filepass123'  // Optional file password
);

// List directory contents
$contents = $client->storage->directory->listContent(
    path: '/photos/vacation/',
    directoryPassword: 'secret123'  // If directory is password protected
);

foreach ($contents['data']['directories'] as $dir) {
    echo "Directory: {$dir['path']}\n";
}

foreach ($contents['data']['files'] as $file) {
    echo "File: {$file['filename']} - {$file['size']} bytes\n";
}

// Retrieve a file
$fileData = $client->storage->file->retrieve(
    path: '/documents/report.pdf',
    password: 'filepass123'  // If file is password protected
);

// Update file privacy
$client->storage->file->updatePrivacy(
    path: '/documents/report.pdf',
    private: 'yes',
    refreshToken: 'yes'  // Generate new access token
);

// Update directory password
$client->storage->directory->updatePassword(
    path: '/photos/vacation/',
    directoryPassword: 'newsecret456'
);

// Delete a file
$client->storage->file->delete(path: '/documents/old_report.pdf');

// Delete a directory
$client->storage->directory->delete(path: '/photos/old_vacation/');

User Management

Manage your application's end users. All operations use your API key (no additional authentication needed).

// Note: The client is already authenticated with your API key.
// User Management operates on your app's users.

```php
// Create a new user
$user = $client->users->create(
    email: 'newuser@example.com',
    username: 'johndoe',
    firstName: 'John',
    lastName: 'Doe',
    password: 'securepassword123',
    phone: '+1234567890'
);
echo "User created with ID: {$user['data']['user_id']}\n";

// Check if a user exists
$exists = $client->users->exists(username: 'johndoe');
if ($exists['data']['exists']) {
    echo "User exists!\n";
}

// Get user details
$userDetails = $client->users->get(username: 'johndoe');
echo "User email: {$userDetails['data']['email']}\n";

// List all users (paginated)
$users = $client->users->listAll(page: 1, limit: 10);
foreach ($users['data']['users'] as $user) {
    echo "{$user['username']} - {$user['email']}\n";
}

// Update user details
$client->users->update(
    username: 'johndoe',
    email: 'newemail@example.com',
    firstName: 'Jonathan'
);

// Sign in a user (classic username/password)
$signinResult = $client->users->signIn(
    username: 'johndoe',
    password: 'securepassword123'
);
$accessToken = $signinResult['data']['access'];
$refreshToken = $signinResult['data']['refresh'];

// Sign in with third-party auth (e.g., Google, Facebook)
$signinResult = $client->users->signIn(
    authenticationType: 'google',
    authenticationTypeId: 'google_user_id_12345'
);

// OAuth PKCE Flow with EagleBirth Auth UI
// After user authenticates via EagleBirth Auth UI, you'll receive a 'code'
// Exchange the code for user session and data
$userSession = $client->users->exchangeCodeForUser(
    code: 'authorization_code_from_redirect',
    codeVerifier: 'your_code_verifier'
);
echo "User email: {$userSession['data']['email']}\n";
echo "Access token: {$userSession['data']['access']}\n";
echo "User ID: {$userSession['data']['user_id']}\n";

// Verify if a session token is valid
$isValid = $client->users->verifyToken(token: $accessToken);

// Refresh user session token
$newTokens = $client->users->refreshToken(refresh: $refreshToken);

// Update user password (admin action)
$client->users->updatePassword(
    username: 'johndoe',
    password: 'newpassword456'
);

// Send verification code for password reset
$codeResponse = $client->users->sendVerificationCode(username: 'johndoe');
$codeId = $codeResponse['data']['code_id'];

// Validate the verification code
$client->users->validateVerificationCode(
    code: '123456',
    codeId: $codeId
);

// Reset password using verification code (self-service)
$client->users->resetPassword(
    code: '123456',
    codeId: $codeId,
    password: 'brandnewpassword789'
);

// Update user status
$client->users->updateStatus(
    username: 'johndoe',
    status: 'suspended'  // Options: 'active', 'suspended', 'pending', 'deleted'
);

// Update user type/role
$client->users->updateType(
    username: 'johndoe',
    type: 'premium'
);

// Reactivate a suspended user
$client->users->reactivate(username: 'johndoe');

// Sign out a user (invalidate refresh token)
$client->users->signOut(refreshToken: $refreshToken);

// Delete a user
$client->users->delete(username: 'johndoe');

OAuth PKCE Flow (EagleBirth Auth UI)

When users authenticate through EagleBirth's hosted Auth UI, you'll receive an authorization code that needs to be exchanged for user data and session tokens.

// Step 1: Redirect users to EagleBirth Auth UI with PKCE parameters
// (You generate code_verifier and code_challenge in your app)

// Step 2: After successful authentication, EagleBirth redirects back to your app
// with a 'code' parameter in the URL

// Step 3: Exchange the code for user session data
$userSession = $client->users->exchangeCodeForUser(
    code: 'code_from_url_redirect',
    codeVerifier: 'your_original_code_verifier'
);

// Access user information
$userData = $userSession['data'];
echo "Email: {$userData['email']}\n";
echo "Username: {$userData['username']}\n";
echo "Name: {$userData['first_name']} {$userData['last_name']}\n";
echo "Phone: {$userData['phone']}\n";
echo "User ID: {$userData['user_id']}\n";

// Access session tokens
$accessToken = $userData['access'];
$refreshToken = $userData['refresh'];

// Use the access token for authenticated requests
// Store the refresh token for renewing the session

Messaging Webhooks

Register HTTPS endpoints to receive real-time notifications whenever a recipient replies to a message you sent through EagleBirth (SMS, WhatsApp, or email).

Supported events:

  • message.reply — any channel (catch-all)
  • message.reply.whatsapp — WhatsApp replies only
  • message.reply.sms — SMS replies only
  • message.reply.email — email replies only
// Register a new webhook
$result = $client->webhooks->create(
    url: 'https://yourapp.com/webhooks/eaglebirth',
    event: 'message.reply'
);
// ⚠ Save the secret — it is shown only once
$webhookId = $result['data']['id'];
$secret     = $result['data']['secret'];
echo "Webhook created: {$webhookId}\n";
echo "Save your secret: {$secret}\n";

// List all registered webhooks
$hooks = $client->webhooks->list();
foreach ($hooks['data'] as $hook) {
    $active = $hook['is_active'] ? 'yes' : 'no';
    echo "{$hook['id']}{$hook['event']}{$hook['url']} (active={$active})\n";
}

// Send a test delivery to confirm your endpoint is reachable
$testResult = $client->webhooks->test($webhookId);
echo "Your server responded with HTTP {$testResult['data']['http_status']}\n";

// Pause deliveries temporarily
$client->webhooks->update($webhookId, null, false);

// Change the endpoint URL
$client->webhooks->update($webhookId, 'https://yourapp.com/new-path');

// Resume deliveries
$client->webhooks->update($webhookId, null, true);

// Permanently delete a webhook
$client->webhooks->delete($webhookId);

Verifying Webhook Signatures

Every delivery includes an X-EagleBirth-Signature header containing an HMAC-SHA256 signature. Always verify it before processing the payload.

<?php

use EagleBirth\Resources\Webhooks;

// Plain PHP — works with any framework
$body      = file_get_contents('php://input');  // raw bytes — do not decode JSON first
$secret    = getenv('EAGLEBIRTH_WEBHOOK_SECRET');
$signature = $_SERVER['HTTP_X_EAGLEBIRTH_SIGNATURE'] ?? '';

if (!Webhooks::verifySignature($body, $secret, $signature)) {
    http_response_code(400);
    exit('Invalid signature');
}

$payload = json_decode($body, true);
$event   = $payload['event'];
$data    = $payload['data'];
// e.g. 'message.reply.sms', 'message.reply.whatsapp', 'message.reply.email'

switch ($event) {
    case 'message.reply.sms':
        echo "SMS reply from {$data['from']}: {$data['body']}\n";
        break;
    case 'message.reply.whatsapp':
        echo "WhatsApp reply from {$data['from']}: {$data['body']}\n";
        break;
    case 'message.reply.email':
        echo "Email reply from {$data['from']}: {$data['subject']}\n";
        break;
}

http_response_code(200);

Webhook payload shape:

{
  "event": "message.reply.sms",
  "test": false,
  "data": {
    "from": "+1234567890",
    "to": "+0987654321",
    "body": "Thanks!",
    "channel": "sms",
    "sub_channel": "direct",
    "message_id": "SM_abc123",
    "original_message_id": "eb_msg_xyz",
    "timestamp": "2024-01-15T10:30:00Z"
  }
}

Error Handling

use EagleBirth\Exceptions\EagleBirthException;
use EagleBirth\Exceptions\AuthenticationException;
use EagleBirth\Exceptions\APIException;

try {
    $response = $client->email->send(
        email: 'user@example.com',
        subject: 'Test',
        message: 'Hello!'
    );
} catch (AuthenticationException $e) {
    // Invalid API key or authentication failed
    echo "Authentication error: " . $e->getMessage();
} catch (APIException $e) {
    // API returned an error
    echo "API error: " . $e->getMessage();
    echo "Status code: " . $e->getCode();
} catch (EagleBirthException $e) {
    // General SDK error
    echo "Error: " . $e->getMessage();
}

Configuration

// Custom base URL (for testing or self-hosted)
$client = new EagleBirth(
    apiKey: 'eb_test_...',
    baseUrl: 'https://custom-api.example.com/api'
);

// Custom timeout (default: 30 seconds)
$client = new EagleBirth(
    apiKey: 'eb_test_...',
    baseUrl: null,
    timeout: 60
);

Cloud Storage

// Upload a file
$client->storage->file->upload(
    file: '/path/to/document.pdf',
    path: '/docs/report.pdf',
    private: 'no'
);

// Create a directory
$client->storage->directory->create(
    path: '/photos/vacation/',
    private: 'yes'
);

// List directory contents
$contents = $client->storage->directory->listContent(path: '/photos/');

// Retrieve a file
$fileData = $client->storage->file->retrieve(path: '/docs/report.pdf');

Authentication

// Sign in with app credentials
$authResponse = $client->auth->signIn(
    clientId: 'your_client_id',
    secretId: 'your_secret_id'
);

// Get user tokens
$tokens = $client->auth->getToken(
    username: 'user@example.com',
    password: 'password123'
);

// Refresh access token
$newToken = $client->auth->refreshToken(refresh: 'your_refresh_token');

Available Resources

  • $client->email - Email notifications
  • $client->sms - SMS messaging
  • $client->whatsapp - WhatsApp messaging
  • $client->otp - OTP/verification codes
  • $client->qr - QR code generation
  • $client->vision - Vision AI (face detection, OCR, face comparison)
  • $client->storage - Cloud storage (files and directories)
    • $client->storage->file - File operations
    • $client->storage->directory - Directory operations
  • $client->users - User management for your app's end users
  • $client->webhooks - Messaging webhook management (register, list, test, pause, delete)

Support

License

MIT License

eaglebirth/eaglebirth-php 适用场景与选型建议

eaglebirth/eaglebirth-php 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 0 次下载、GitHub Stars 达 0, 最近一次更新时间为 2026 年 01 月 26 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「api」 「email」 「sms」 「sdk」 「OCR」 「otp」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 eaglebirth/eaglebirth-php 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 eaglebirth/eaglebirth-php 我们能提供哪些服务?
定制开发 / 二次开发

基于 eaglebirth/eaglebirth-php 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 0
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 29
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-01-26