Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

Merge main and support Guzzle 8 transports

Yudhi Armyndharis5aeb29af32ab
diff --cc .github/workflows/sdk-ci.yml
index c80395980,cc97c8a1d..594e240fa
--- a/.github/workflows/sdk-ci.yml
+++ b/.github/workflows/sdk-ci.yml
@@@ -92,13 -92,13 +92,14 @@@ jobs
- run: pytest
php:
-- name: PHP SDK (${{ matrix.php }})
++ name: PHP SDK (${{ matrix.php }}, Guzzle ${{ matrix.guzzle }})
runs-on: ubuntu-latest
timeout-minutes: 15
strategy:
fail-fast: false
matrix:
php: ['8.1', '8.2']
++ guzzle: ['7', '8']
defaults:
run:
working-directory: sdk/php
@@@ -108,6 -108,6 +109,8 @@@
with:
php-version: ${{ matrix.php }}
- run: composer install --no-interaction --no-progress
++ - run: composer update 'guzzlehttp/guzzle:^7.9' --with-all-dependencies --no-interaction --no-progress
++ if: matrix.guzzle == '7'
- run: ./vendor/bin/phpunit
java:
diff --cc sdk/php/README.md
index 408665630,72b407ab9..37ced8b00
--- a/sdk/php/README.md
+++ b/sdk/php/README.md
@@@ -12,7 -12,7 +12,7 @@@ A synchronous client built on [Guzzle](
composer require rmyndharis/openwa
```
--Requires PHP 8.1+ and Guzzle 7. The namespace is `OpenWA\`.
++Requires PHP 8.1+ and Guzzle 7.9+ or 8.x. The namespace is `OpenWA\`.
## Usage
@@@ -51,6 -51,6 +51,8 @@@ $client = new Client(
]);
```
++The optional `defaultHeaders` map accepts strings, scalar values, null, and non-empty lists of those values. Numbers, booleans, and null are converted to text. An empty list is rejected by header name before any request is sent because Guzzle 8 cannot represent a header with zero values. Use `''` for an empty header value.
++
## Messaging
> Voice notes: pass `'ptt' => true` to `sendAudio` to send a real WhatsApp voice note (PTT). Supply `audio/ogg; codecs=opus` audio for reliable playback; the server defaults the mimetype to that when `ptt` is set without one.
diff --cc sdk/php/composer.lock
index f1d40ad5a,214f76a87..a042735b1
--- a/sdk/php/composer.lock
+++ b/sdk/php/composer.lock
@@@ -4,7 -4,7 +4,7 @@@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
- "content-hash": "a618b93aa3cb1ee43938b154933139e8",
- "content-hash": "175d3ef7e7a7d0c2b6d23422981fa6e0",
++ "content-hash": "60578ba023573ca5d010ecdf826eedd8",
"packages": [
{
"name": "guzzlehttp/guzzle",
diff --cc sdk/php/src/Client.php
index b9fa5cd92,b9fa5cd92..c26d562da
--- a/sdk/php/src/Client.php
+++ b/sdk/php/src/Client.php
@@@ -80,7 -80,7 +80,7 @@@ class Clien
* apiKey:string,
* timeout?:float,
* httpClient?:?\GuzzleHttp\ClientInterface|null,
-- * defaultHeaders?:array<string,string>,
++ * defaultHeaders?:array<string,scalar|null|non-empty-array<array-key,scalar|null>>,
* allowInsecureHttp?:bool
* } $config
*
diff --cc sdk/php/src/Http/HttpExecutor.php
index 87a5b37bd,87a5b37bd..a34f9d534
--- a/sdk/php/src/Http/HttpExecutor.php
+++ b/sdk/php/src/Http/HttpExecutor.php
@@@ -6,6 -6,6 +6,9 @@@ namespace OpenWA\Http
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\ConnectException;
++use GuzzleHttp\Exception\ConnectTimeoutException;
++use GuzzleHttp\Exception\NetworkTimeoutException;
++use GuzzleHttp\Exception\ResponseTimeoutException;
use OpenWA\Exceptions\OpenWAApiException;
use OpenWA\Exceptions\OpenWAException;
use OpenWA\Exceptions\OpenWATimeoutException;
@@@ -26,7 -26,7 +29,7 @@@ class HttpExecuto
* var_dump, var_export, an (array) cast and a framework's dumper all read properties, and both are
* bearer-equivalent (a header often carries the credential of a proxy in front of the gateway).
*
-- * @var \WeakMap<HttpExecutor,array{apiKey:string,headers:array<string,string>}>|null
++ * @var \WeakMap<HttpExecutor,array{apiKey:string,headers:array<string,string|list<string>>}>|null
*/
private static ?\WeakMap $secrets = null;
@@@ -37,7 -37,7 +40,7 @@@
private array $headerNames;
/**
-- * @param array<string,string> $defaultHeaders Applied UNDER the auth/JSON headers
++ * @param array<string,scalar|null|non-empty-array<array-key,scalar|null>> $defaultHeaders Applied UNDER the auth/JSON headers
* (which always win), on every request.
*/
public function __construct(
@@@ -48,6 -48,6 +51,10 @@@
#[\SensitiveParameter] array $defaultHeaders = []
) {
self::checkDefaultHeaders($defaultHeaders);
++ $defaultHeaders = array_map(
++ static fn ($value) => is_array($value) ? array_map('strval', array_values($value)) : (string) $value,
++ $defaultHeaders
++ );
$this->timeout = $timeout;
self::$secrets ??= new \WeakMap();
self::$secrets[$this] = ['apiKey' => $apiKey, 'headers' => $defaultHeaders];
@@@ -68,7 -68,7 +75,7 @@@
* Public so that the client can run it before it builds an executor, whose constructor frame holds the
* key and, before PHP 8.2, shows its first characters in a trace.
*
-- * A number, a boolean or null is sent as its text and a list as several values, as the stack does.
++ * A number, a boolean or null is sent as its text and a non-empty list as several values.
*
* @param array<mixed> $headers
*
@@@ -82,6 -82,6 +89,9 @@@
'OpenWA Client: defaultHeaders has a header name that is not a valid HTTP token'
);
}
++ if ($value === []) {
++ throw new OpenWAException(sprintf('OpenWA Client: defaultHeaders value for "%s" must be text or a non-empty list', $name));
++ }
foreach (is_array($value) ? $value : [$value] as $each) {
if (is_scalar($each) || $each === null) {
if (preg_match('/\A[\t\x20-\x7e]*\z/', (string) $each) === 1) {
@@@ -246,12 -246,12 +256,11 @@@
try {
$response = $this->http->request($method, $url, $options);
++ } catch (ConnectTimeoutException | NetworkTimeoutException | ResponseTimeoutException $e) {
++ throw new OpenWATimeoutException($this->timeout);
} catch (ConnectException $e) {
-- // cURL error 28 (CURLE_OPERATION_TIMEDOUT) is the canonical timeout
-- // signal, surfaced via the handler context. We check errno first
-- // (locale- and version-independent) and fall back to message matching
-- // for transports that don't populate the context (e.g. stream handler).
-- $errno = $e->getHandlerContext()['errno'] ?? null;
++ // Guzzle 7 exposes cURL errno 28 in the context; custom transports may only supply a message.
++ $errno = method_exists($e, 'getHandlerContext') ? ($e->getHandlerContext()['errno'] ?? null) : null;
$isTimeout = $errno === 28 || str_contains($e->getMessage(), 'timed out');
if ($isTimeout) {
throw new OpenWATimeoutException($this->timeout);
diff --cc sdk/php/tests/ClientTest.php
index 34c92d3a7,34c92d3a7..5b220d344
--- a/sdk/php/tests/ClientTest.php
+++ b/sdk/php/tests/ClientTest.php
@@@ -73,17 -73,17 +73,51 @@@ class ClientTest extends TestCas
public function testANumberABooleanOrNullDefaultHeaderValueIsSentAsItsText(): void
{
-- $backend = (new MockBackend())->on(200, []);
++ $mock = new \GuzzleHttp\Handler\MockHandler([new \GuzzleHttp\Psr7\Response(200)]);
++ $httpClient = new \GuzzleHttp\Client(['handler' => \GuzzleHttp\HandlerStack::create($mock)]);
(new \OpenWA\Client([
'baseUrl' => 'http://localhost:2785',
'apiKey' => 'k',
-- 'httpClient' => $backend->httpClient(),
-- 'defaultHeaders' => ['X-Tenant-Id' => 42, 'X-Ratio' => 1.5, 'X-Debug' => true, 'X-Empty' => null],
++ 'httpClient' => $httpClient,
++ 'defaultHeaders' => [
++ 'X-Tenant-Id' => 42,
++ 'X-Ratio' => 1.5,
++ 'X-Debug' => true,
++ 'X-False' => false,
++ 'X-Empty' => null,
++ 'X-List' => ['first', 42, 1.5, true, false, null],
++ ],
]))->request('GET', '/api/anything');
-- $headers = $backend->lastCall()['headers'];
-- $this->assertSame('42', $headers['x-tenant-id'] ?? null);
-- $this->assertSame('1.5', $headers['x-ratio'] ?? null);
-- $this->assertSame('1', $headers['x-debug'] ?? null);
++ $request = $mock->getLastRequest();
++ $this->assertNotNull($request);
++ $this->assertSame(['42'], $request->getHeader('X-Tenant-Id'));
++ $this->assertSame(['1.5'], $request->getHeader('X-Ratio'));
++ $this->assertSame(['1'], $request->getHeader('X-Debug'));
++ $this->assertSame([''], $request->getHeader('X-False'));
++ $this->assertSame([''], $request->getHeader('X-Empty'));
++ $this->assertSame(['first', '42', '1.5', '1', '', ''], $request->getHeader('X-List'));
++ }
++
++ public function testAnEmptyHeaderListIsRefusedBeforeAnInjectedCredentialCanBeSent(): void
++ {
++ $mock = new \GuzzleHttp\Handler\MockHandler([new \GuzzleHttp\Psr7\Response(200)]);
++ $httpClient = new \GuzzleHttp\Client([
++ 'handler' => \GuzzleHttp\HandlerStack::create($mock),
++ 'headers' => ['X-Proxy-Credential' => 'private-default'],
++ ]);
++ try {
++ (new \OpenWA\Client([
++ 'baseUrl' => 'http://localhost:2785',
++ 'apiKey' => 'k',
++ 'httpClient' => $httpClient,
++ 'defaultHeaders' => ['X-Proxy-Credential' => []],
++ ]))->request('GET', '/api/anything');
++ $this->fail('Expected an exception for an empty header list');
++ } catch (\OpenWA\Exceptions\OpenWAException $e) {
++ $this->assertStringContainsString('X-Proxy-Credential', $e->getMessage());
++ $this->assertStringNotContainsString('private-default', $e->getMessage());
++ }
++ $this->assertNull($mock->getLastRequest());
}
public function testADefaultHeaderThatIsNeitherTextNorAListOfItIsRefusedByName(): void
@@@ -449,27 -449,27 +483,45 @@@
}
}
-- public function testTimeoutWithErrno28MapsToTimeoutException(): void
++ /** @dataProvider transportTimeouts */
++ public function testTransportTimeoutMapsWithoutAnEnglishMessage(\Throwable $failure, bool $binary): void
{
-- // Regression guard: cURL error 28 (CURLE_OPERATION_TIMEDOUT) must map to
-- // OpenWATimeoutException, regardless of the message wording. The message
-- // deliberately avoids 'timed out' so only the errno check can match it.
-- $timeoutRequest = new \GuzzleHttp\Exception\ConnectException(
-- 'cURL error 28: Zeitlimit für Vorgang überschritten',
-- new \GuzzleHttp\Psr7\Request('GET', '/api/sessions'),
-- null,
-- ['errno' => 28],
-- );
-- $mock = new \GuzzleHttp\Handler\MockHandler([$timeoutRequest]);
++ $mock = new \GuzzleHttp\Handler\MockHandler([$failure]);
$httpClient = new \GuzzleHttp\Client(['handler' => \GuzzleHttp\HandlerStack::create($mock)]);
$client = new \OpenWA\Client([
'baseUrl' => 'http://localhost:2785',
'apiKey' => 'k',
++ 'timeout' => 1.25,
'httpClient' => $httpClient,
]);
-- $this->expectException(OpenWATimeoutException::class);
-- $client->sessions->list();
++ try {
++ $binary ? $client->status->media('s', 'status') : $client->sessions->list();
++ $this->fail('Expected a timeout exception');
++ } catch (OpenWATimeoutException $e) {
++ $this->assertSame(1.25, $e->getTimeout());
++ }
++ }
++
++ public static function transportTimeouts(): array
++ {
++ $request = new \GuzzleHttp\Psr7\Request('GET', '/api/sessions');
++ $message = 'cURL error 28: Zeitlimit für Vorgang überschritten';
++ if (method_exists(\GuzzleHttp\Exception\ConnectException::class, 'getHandlerContext')) {
++ $failures = ['curl errno 28' => new \GuzzleHttp\Exception\ConnectException($message, $request, null, ['errno' => 28])];
++ } else {
++ $failures = [
++ 'connect timeout' => new \GuzzleHttp\Exception\ConnectTimeoutException($message, $request),
++ 'network timeout' => new \GuzzleHttp\Exception\NetworkTimeoutException($message, $request),
++ 'response timeout' => new \GuzzleHttp\Exception\ResponseTimeoutException($message, $request, new \GuzzleHttp\Psr7\Response(200)),
++ ];
++ }
++ $cases = [];
++ foreach ($failures as $name => $failure) {
++ $cases[$name . ' JSON'] = [$failure, false];
++ $cases[$name . ' binary'] = [$failure, true];
++ }
++ return $cases;
}
public function testTimedOutMessageWithoutErrnoMapsToTimeoutException(): void
@@@ -494,13 -494,13 +546,10 @@@
public function testConnectionRefusedDoesNotMapToTimeoutException(): void
{
-- // Regression guard: a non-timeout ConnectException (errno 7) must NOT be
-- // misclassified as a timeout — it must propagate as ConnectException.
++ // A connection refusal must propagate unchanged instead of becoming a timeout.
$refused = new \GuzzleHttp\Exception\ConnectException(
'cURL error 7: connection refused',
new \GuzzleHttp\Psr7\Request('GET', '/api/sessions'),
-- null,
-- ['errno' => 7],
);
$mock = new \GuzzleHttp\Handler\MockHandler([$refused]);
$httpClient = new \GuzzleHttp\Client(['handler' => \GuzzleHttp\HandlerStack::create($mock)]);
@@@ -510,7 -510,7 +559,11 @@@
'httpClient' => $httpClient,
]);
-- $this->expectException(\GuzzleHttp\Exception\ConnectException::class);
-- $client->sessions->list();
++ try {
++ $client->sessions->list();
++ $this->fail('Expected a connection exception');
++ } catch (\GuzzleHttp\Exception\ConnectException $e) {
++ $this->assertSame($refused, $e);
++ }
}
}