daniel-jorg-schuppelius/php-api-toolkit 问题修复 & 功能扩展

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

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

daniel-jorg-schuppelius/php-api-toolkit

Composer 安装命令:

composer require daniel-jorg-schuppelius/php-api-toolkit

包简介

Reused codes for my api php sdks

README 文档

README

A reusable PHP library for building API client SDKs, targeting PHP 8.2+ with modern patterns and PSR compliance.

Features

  • HTTP Client Abstraction - Built on GuzzleHttp with automatic rate limiting and retry logic
  • Authentication Strategies - Built-in support for Bearer, Basic, API Key and OAuth2 (Authorization Code incl. PKCE/revocation, Client Credentials incl. private_key_jwt)
  • Exception Mapping - HTTP status codes automatically mapped to specific exceptions
  • Entity System - Type-safe data objects with automatic hydration and validation
  • PSR-3 Logging - Comprehensive logging integration
  • Timeouts - Configurable request and connection timeouts
  • Proxy Support - Enterprise-ready proxy configuration
  • Default Headers & Query Params - Global request configuration
  • SSL Control - Optional SSL verification bypass for development

Installation

composer require dschuppelius/php-api-toolkit

Quick Start

use APIToolkit\Contracts\Abstracts\API\Authentication\BearerAuthentication;

// Create your API client extending ClientAbstract
// Simply pass the base URL - HttpClient is created internally
$apiClient = new MyApiClient('https://api.example.com', $logger);

// Set authentication
$auth = new BearerAuthentication('your-token');
$apiClient->setAuthentication($auth);

// Make requests - auth headers are added automatically
$response = $apiClient->get('/endpoint');

Advanced: Custom HttpClient

For advanced use cases (custom middleware, handler stacks, etc.), you can still provide your own HttpClient:

use GuzzleHttp\Client as HttpClient;
use GuzzleHttp\HandlerStack;

$stack = HandlerStack::create();
// Add custom middleware...

$httpClient = new HttpClient([
    'base_uri' => 'https://api.example.com',
    'handler' => $stack,
]);

$apiClient = new MyApiClient('https://api.example.com', $logger, false, $httpClient);

Authentication

The toolkit provides three authentication strategies out of the box:

Bearer Token (OAuth2, JWT)

use APIToolkit\Contracts\Abstracts\API\Authentication\BearerAuthentication;

$auth = new BearerAuthentication('your-jwt-token');
$client->setAuthentication($auth);

// Update token later (e.g., after refresh)
$auth->setToken('new-refreshed-token');

Basic Authentication

use APIToolkit\Contracts\Abstracts\API\Authentication\BasicAuthentication;

$auth = new BasicAuthentication('username', 'password');
$client->setAuthentication($auth);

API Key

use APIToolkit\Contracts\Abstracts\API\Authentication\ApiKeyAuthentication;

// Default header: X-API-Key
$auth = new ApiKeyAuthentication('your-api-key');

// Custom header name
$auth = new ApiKeyAuthentication('your-api-key', 'X-Custom-Auth');
$client->setAuthentication($auth);

OAuth2 Client Credentials (Machine-to-Machine)

For APIs without user interaction (e.g. UPS, FedEx, Microsoft Graph app-only). Tokens are fetched, cached and re-fetched on expiry automatically; after a 401 the token is discarded and the request retried exactly once.

use APIToolkit\API\Authentication\OAuth2\{OAuth2ClientCredentialsAuthentication, OAuth2ClientCredentialsGrant};

$grant = new OAuth2ClientCredentialsGrant(
    'client-id',
    'client-secret',
    'https://provider.example.com/oauth/token'
);

// Client authentication at the token endpoint:
// default: credentials in the form body (e.g. FedEx)
$grant->setTokenAuthMethod(OAuth2ClientCredentialsGrant::AUTH_METHOD_BASIC); // HTTP Basic header (e.g. UPS)

// Token persistence is pluggable via OAuth2TokenStoreInterface
// (default: in-memory). Inject e.g. an encrypted per-tenant store:
$auth = new OAuth2ClientCredentialsAuthentication($grant, $myTokenStore, ['read', 'write']);
$client->setAuthentication($auth);

Certificate-based clients (private_key_jwt, RFC 7523 — e.g. Microsoft Entra ID certificate credentials) sign a JWT client assertion instead of sending a secret (requires the openssl extension):

$grant = new OAuth2ClientCredentialsGrant('client-id', '', 'https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token');
$grant->setPrivateKeyJwt($privateKeyPem, $certificatePem); // certificate adds the x5t/x5t#S256 header

$auth = new OAuth2ClientCredentialsAuthentication($grant, null, ['https://graph.microsoft.com/.default']);
$client->setAuthentication($auth);

Custom Authentication

Implement AuthenticationInterface for custom auth strategies:

use APIToolkit\Contracts\Interfaces\API\AuthenticationInterface;

class OAuth1Authentication implements AuthenticationInterface {
    public function getAuthHeaders(): array {
        return ['Authorization' => 'OAuth ' . $this->buildOAuthHeader()];
    }
    
    public function getType(): string {
        return 'OAuth1';
    }
    
    public function isValid(): bool {
        return !empty($this->consumerKey);
    }
}

Rate Limiting

// Set minimum interval between requests (default: 0.25s, minimum: 0.2s)
$client->setRequestInterval(0.5); // 500ms between requests

Retry Logic

// Configure retry behavior for 429, 503, 504 errors
$client->setMaxRetries(5);
$client->setBaseRetryDelay(2); // seconds
$client->setExponentialBackoff(true); // delays: 2s, 4s, 8s, 16s...

Timeouts

// Request timeout (default: 30s)
$client->setTimeout(60.0);

// Connection timeout (default: 10s)
$client->setConnectTimeout(5.0);

Default Headers

// Set headers included in every request
$client->setDefaultHeaders([
    'Content-Type' => 'application/json;charset=utf-8',
    'Accept' => 'application/json;charset=utf-8',
]);

// Add/remove individual headers
$client->addDefaultHeader('X-Custom-Header', 'value');
$client->removeDefaultHeader('X-Custom-Header');

Default Query Parameters

// Set query parameters included in every request
$client->setDefaultQueryParams([
    'api_version' => '2.0',
    'format' => 'json',
]);

// Add/remove individual parameters
$client->addDefaultQueryParam('locale', 'de_DE');
$client->removeDefaultQueryParam('format');

User-Agent

$client->setUserAgent('MyApp/1.0.0 (PHP 8.2)');

Proxy Support

// Set proxy for enterprise environments
$client->setProxy('http://proxy.company.com:8080');

// With authentication
$client->setProxy('http://user:pass@proxy.company.com:8080');

// Disable proxy
$client->setProxy(null);

SSL Verification

// Disable SSL verification (development only!)
$client->setVerifySSL(false);

// Check status
$client->isSSLVerificationEnabled();

⚠️ Warning: Disabling SSL verification is insecure. Only use for development or self-signed certificates.

Complete Configuration Example

use APIToolkit\Contracts\Abstracts\API\Authentication\BearerAuthentication;

// Simple constructor - just base URL
$client = new MyApiClient('https://api.example.com', $logger);

// Timeouts
$client->setTimeout(30.0);
$client->setConnectTimeout(10.0);

// Default headers
$client->setDefaultHeaders([
    'Content-Type' => 'application/json;charset=utf-8',
    'Accept' => 'application/json;charset=utf-8',
]);

// User-Agent
$client->setUserAgent('MyApp/1.0.0');

// Default query parameters
$client->setDefaultQueryParams(['api_version' => '2']);

// Authentication with additional headers
$auth = new BearerAuthentication($token, [
    'X-Client-ID' => $clientId,
]);
$client->setAuthentication($auth);

// Rate limiting
$client->setRequestInterval(0.5);
$client->setMaxRetries(3);

// Enterprise environment (optional)
$client->setProxy('http://proxy:8080');
$client->setVerifySSL(false); // Development only!

Exception Handling

HTTP errors are automatically converted to typed exceptions:

use APIToolkit\Exceptions\TooManyRequestsException;
use APIToolkit\Exceptions\UnauthorizedException;
use APIToolkit\Exceptions\NotFoundException;

try {
    $response = $client->get('/resource');
} catch (UnauthorizedException $e) {
    // 401 - Invalid or expired token
} catch (NotFoundException $e) {
    // 404 - Resource not found
} catch (TooManyRequestsException $e) {
    // 429 - Rate limited
}
Status Code Exception
400 BadRequestException
401 UnauthorizedException
402 PaymentRequiredException
403 ForbiddenException
404 NotFoundException
405 NotAllowedException
406 NotAcceptableException
408 RequestTimeoutException
409 ConflictException
415 UnsupportedMediaTypeException
422 UnprocessableEntityException
429 TooManyRequestsException
500 InternalServerErrorException
502 BadGatewayException
503 ServiceUnavailableException
504 GatewayTimeoutException

Testing

composer test
# or
vendor/bin/phpunit

License

MIT License - see LICENSE for details.

daniel-jorg-schuppelius/php-api-toolkit 适用场景与选型建议

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

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

围绕 daniel-jorg-schuppelius/php-api-toolkit 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-12-29