定制 echo-five/sparky-api-client-php 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

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

echo-five/sparky-api-client-php

Composer 安装命令:

composer require echo-five/sparky-api-client-php

包简介

Sparky API Client PHP

README 文档

README

PHP Version Size License

A PHP client library for the Sparky API.

Menu

Requirements

PHP 8.3 or higher with cURL, JSON, Sodium and Ctype extensions

Installation

How to install?

This package can be installed via Composer:

composer require echo-five/sparky-api-client-php

How to update?

Use the following command to update this package only:

composer update echo-five/sparky-api-client-php

How to remove?

This package can be uninstalled via Composer:

composer remove echo-five/sparky-api-client-php

Get started

Prerequisites

  • The library has been installed via Composer.
  • You have a valid API Key.
  • You have a valid API Signature Key (to "sign" the request, see here).

Create a new blank PHP file and copy the code below:

<?php

// Load Composer autoloader.
require 'vendor/autoload.php';

// Use declaration.
use SparkyApiClient\SparkyApiClient;

// Try to execute the API request.
try {
    // Initialize.
    $sparkyApi = new SparkyApiClient('SPARKY_API_HOST', 'SPARKY_API_KEY');
    
    // Do a request.
    $sparkyApi->request('post', '/endpoint', [
        'foo' => 'Bar',
        'biz' => 'Buz',
    ]);

    // Get the request response.
    $requestResponse = $sparkyApi->getResponse();

    // Dump.
    var_dump($requestResponse);
}
catch (Exception $e) {
    // Show error message.
    echo 'Error: ' . $e->getMessage();
}

This example is stored in the project and can be downloaded here: GetStartedSimpleRequest.php

Features

Simple request vs Signed request

The library allows two types of requests:

  • Simple requests (unsigned)
    The request is validated only using your API key.
  • Signed requests
    Your request is signed using asymmetric cryptography.
    This allows to verify both the authenticity and integrity of the data.

Signed requests, although a bit slower, are therefore more secure than simple requests.

How it works

  • When you create an API key on the platform, a cryptographic key pair is generated as well.
    • The public key is stored on the API side and linked to your account.
    • The private key (the API Signature Key) is shown to you once.
      • The system does not store it and cannot regenerate it.
        You must keep it secure.
  • You use the API Signature Key to sign your requests before they are sent.
  • The system verifies each signature using your registered public key.
  • If the signature is invalid, the request is not processed.

Signing requests is very straightforward!
The only thing to do is to provide your API Signature Key when you instantiate the library.
Then all requests will be automatically signed!

// Initialize with signature key (private key) for signed requests.
$sparkyApi = new SparkyApiClient('SPARKY_API_HOST', 'SPARKY_API_KEY', 'SPARKY_API_SIGNATURE_KEY');

This example is stored in the project and can be downloaded here: GetStartedSignedRequest.php

IMPORTANT

  • Store your API Key and API Signature Key securely (environment variables, secrets manager, etc.).
  • Never share your API Key or API Signature Key, and never commit them to version control.

Debugging

Troubleshooting an API can sometimes be challenging.
The library includes a debugging mode to help you better understand how requests are built and sent.

The debugging mode allows to:

  • See the time consumption of each request.
  • See how many requests were executed.
  • See the execution order of the requests.

Using the debugging mode is very easy!
Just start it at a specific breakpoint and stop it at another.

<?php

// Load Composer autoloader.
require 'vendor/autoload.php';

// Use declaration.
use SparkyApiClient\SparkyApiClient;

// Try to execute the API request.
try {
    // Initialize.
    $sparkyApi = new SparkyApiClient('SPARKY_API_HOST', 'SPARKY_API_KEY');
    
    // Start the debugging mode.
    $sparkyApi->debugStart();
    
    // Do a request.
    $sparkyApi->request('post', '/endpoint', [
        'foo' => 'Bar',
        'biz' => 'Buz',
    ]);
    
    // Stop the debugging mode.
    $sparkyApi->debugStop();

    // Get the request response.
    $requestResponse = $sparkyApi->getResponse();

    // Dumps.
    var_dump($requestResponse);
    var_dump($sparkyApi->debugGet());
}
catch (Exception $e) {
    // Show error message.
    echo 'Error: ' . $e->getMessage();
}

See Available methods section for more debugging options.
This example is stored in the project and can be downloaded here: GetStartedDebugging.php

Here is an example of the debugging information:

// Result:
Array
(
    [requests] => Array
        (
            [time] => 0.218735
            [count] => 1
            [trace] => Array
                (
                    [2025-01-01T12:57:09.603425Z] => Start debug.
                    [2025-01-01T12:57:09.822565Z] => Request | https://example.com/endpoint
                    [2025-01-01T12:57:09.822592Z] => Stop debug.
                )
        )
)

Available methods

Request

This method allows to make an API request.

request(string $requestType, string $requestEndpoint, array <$requestParams>, string <$requestMode>)

  • The requestType argument defines the HTTP method to use.
    Allowed values are GET, POST, PUT, PATCH, and DELETE.
    This argument is mandatory.

  • The requestEndpoint argument defines the endpoint to call.
    This is a URI, e.g.: /endpoint or /api/v1/mirror
    This argument is mandatory.

  • The requestParams argument defines the data to send to the endpoint.
    This is a key/value array, by default no data is sent.
    For GET and DELETE: sent as query string parameters.
    For POST, PUT, PATCH: sent as request body.
    This argument is optional.

  • The requestMode argument defines the body encoding format.
    Allowed values are JSON (default), FORM, and HTTP.
    Only applicable for POST, PUT, and PATCH requests.
    This argument is optional.

This method returns the class instance itself, not the result of the request.
The request result must be retrieved using another method (getResponse).
For convenience, this method is chainable.

Example:

// Do a request and get the request response.
$requestResponse = $sparkyApi->request('post', '/endpoint')->getResponse();

Get Response

This method allows to get the response of the request.

getResponse(bool <$object>)

  • The object argument defines if the request response must be returned as object or not.
    The API replies in JSON format, so the response is a raw JSON string.
    The object argument allows to get a PHP object instead of a raw JSON string.
    The object argument is set to true by default.

Usage examples:

$requestResponse = $sparkyApi->getResponse();      // Return a PHP object.
$requestResponse = $sparkyApi->getResponse(true);  // Return a PHP object.
$requestResponse = $sparkyApi->getResponse(false); // Return a raw JSON string.

This method returns a raw JSON string or a PHP object, depending on the passed argument.
The request response is always a full API response.
Here is an example:

// Request:
$sparkyApi->request('post', '/endpoint', [
    'foo' => 'Bar',
    'biz' => 'Buz',
]);

// Response:
stdClass Object
(
    [status] => 200
    [data] => stdClass Object
        (
            [foo] => Bar
            [biz] => Buz
        )
    [messages] => Array
        (
            [0] => stdClass Object
                (
                    [type] => info
                    [text] => The request has input data.
                )
            [1] => stdClass Object
                (
                    [type] => info
                    [text] => The request has 2 data keys.
                    [data] => stdClass Object
                        (
                            [keys] => 2
                        )
                )
        )
)

Get Response Status

This method allows to directly get the [status] property of the request response.
The status is the HTTP status code associated with the response.

getResponseStatus()

This method always returns an int.

Usage example:

// Get the request response status.
$requestResponseStatus = $sparkyApi->getResponseStatus();

Get Response Headers

This method allows to get the response headers.

getResponseHeaders(bool <$array>)

  • The array argument defines if the headers must be returned as array or not.
    The array argument allows to get a parsed associative array instead of a raw headers string.
    The array argument is set to true by default.

This method returns a parsed associative array or a raw headers string, depending on the passed argument.

Usage examples:

$requestResponseHeaders = $sparkyApi->getResponseHeaders();      // Return a parsed array.
$requestResponseHeaders = $sparkyApi->getResponseHeaders(true);  // Return a parsed array.
$requestResponseHeaders = $sparkyApi->getResponseHeaders(false); // Return a raw headers string.

Get Response Data

This method allows to directly get the [data] property of the request response.

getResponseData()

This method always returns a PHP object.

Usage example:

// Get the request response data.
$requestResponseData = $sparkyApi->getResponseData();

Get Response Messages

This method allows to directly get the [messages] property of the request response.

getResponseMessages()

This method always returns a PHP array.

Usage example:

// Get the request response messages.
$requestResponseMessages = $sparkyApi->getResponseMessages();

Get Sent

This method allows to get the complete sent request.

getSent(bool <$object>)

  • The object argument defines if the sent request must be returned as object or not.
    The object argument allows to get a PHP object instead of a raw string.
    The object argument is set to true by default.

This method returns a raw string or a PHP object, depending on the passed argument.
The sent request includes the method, endpoint, headers, and payload.

Usage examples:

$requestSent = $sparkyApi->getSent();      // Return a PHP object.
$requestSent = $sparkyApi->getSent(true);  // Return a PHP object.
$requestSent = $sparkyApi->getSent(false); // Return a raw string.

Get Sent Headers

This method allows to get the sent headers.

getSentHeaders(bool <$array>)

  • The array argument defines if the headers must be returned as array or not.
    The array argument allows to get a parsed associative array instead of a raw headers string.
    The array argument is set to true by default.

This method returns a parsed associative array or a raw headers string, depending on the passed argument.

Usage examples:

$requestSentHeaders = $sparkyApi->getSentHeaders();      // Return a parsed array.
$requestSentHeaders = $sparkyApi->getSentHeaders(true);  // Return a parsed array.
$requestSentHeaders = $sparkyApi->getSentHeaders(false); // Return a raw headers string.

Get Sent Payload

This method allows to get the sent payload.

getSentPayload(bool <$object>)

  • The object argument defines if the payload must be returned as object or not.
    The object argument allows to get a PHP object instead of a raw string.
    The object argument is set to true by default.

This method returns a raw string or a PHP object, depending on the passed argument.

Usage examples:

$requestSentPayload = $sparkyApi->getSentPayload();      // Return a PHP object.
$requestSentPayload = $sparkyApi->getSentPayload(true);  // Return a PHP object.
$requestSentPayload = $sparkyApi->getSentPayload(false); // Return a raw string.

Get cURL Info

This method allows to get the cURL request information.
Each request is made using the PHP cURL extension, and this method returns the result of curl_getinfo().
See the official PHP.net documentation for details.

getCurlInfo()

This method always returns a PHP array.

Usage example:

// Get the request info.
$requestInfo = $sparkyApi->getCurlInfo();

Debug Start

This method allows to start the debugging mode.
Every request executed after this method call will be taken into account for the debugging.

debugStart()

This method returns the class instance itself.
For convenience, this method is chainable.

Example:

// Start the debugging mode.
$sparkyApi->debugStart();

Debug Stop

This method allows to stop the debugging mode.
Every request executed after this method call will not be taken into account for the debugging.

debugStop()

This method returns the class instance itself.
For convenience, this method is chainable.

Example:

// Stop the debugging mode.
$sparkyApi->debugStop();

Debug Get

This method allows to get the result of the debugging data.
This method call doesn't stop the debugging mode, so it can be called every time needed.
This is just a debugging output at the time "t".

debugGet()

This method returns a PHP array.

Example:

// Start the debugging mode.
$sparkyApi->debugStart();

// Do a request #1.
$sparkyApi->request('post', '/endpoint');

// Do a request #2.
$sparkyApi->request('post', '/endpoint');

// Dump the debugging data (which contains requests #1 and #2).
var_dump($sparkyApi->debugGet());

// Do a request #3.
$sparkyApi->request('post', '/endpoint');

// Do a request #4.
$sparkyApi->request('post', '/endpoint');

// Stop the debugging mode.
$sparkyApi->debugStop();

// Dump the debugging data (which contains requests #1, #2, #3, #4).
var_dump($sparkyApi->debugGet());

Debug Reset

This method allows to reset the debugging data.
This method call doesn't stop the debugging mode, but it erases all collected data.

debugReset()

This method returns the class instance itself.
For convenience, this method is chainable.

Example #1:

// Do a request and reset the debugging data.
$sparkyApi->request('post', '/endpoint')->debugReset();

Example #2:

// Start the debugging mode.
$sparkyApi->debugStart();

// Do a request #1.
$sparkyApi->request('post', '/endpoint');

// Do a request #2.
$sparkyApi->request('post', '/endpoint');

// Dump the debugging data (which contains requests #1 and #2).
var_dump($sparkyApi->debugGet());

// Reset the debugging data.
$sparkyApi->debugReset();

// Do a request #3.
$sparkyApi->request('post', '/endpoint');

// Do a request #4.
$sparkyApi->request('post', '/endpoint');

// Stop the debugging mode.
$sparkyApi->debugStop();

// Dump the debugging data (which contains requests #3 and #4).
var_dump($sparkyApi->debugGet());

Accept Unsafe Certificates

This method allows to disable the cURL SSL verify peer.
For example: accepting self-signed SSL certificates in development.

acceptUnsafeCertificatesByDisablingCurlSslVerifyPeer()

WARNING:
This method is intended for API development and testing purposes only.
It should NEVER be used when consuming production APIs, as it disables SSL verification.
Only use this when testing against local API instances with self-signed certificates.

This method returns the class instance itself.
For convenience, this method is chainable.

Example:

// Accept self-signed certificates when testing against local API instance.
$sparkyApi = new SparkyApiClient('https://local-api.dev', 'SPARKY_API_KEY');
$sparkyApi->acceptUnsafeCertificatesByDisablingCurlSslVerifyPeer();
$sparkyApi->request('post', '/endpoint', ['data' => 'value']);

License

MIT

echo-five/sparky-api-client-php 适用场景与选型建议

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

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

围绕 echo-five/sparky-api-client-php 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-11-22