Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 7 additions & 12 deletions src/Common/Utils.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ public static function generateRandomString($length = 10)
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
$randomString .= $characters[random_int(0, $charactersLength - 1)];
}
return $randomString;
}
Expand All @@ -22,16 +22,11 @@ public static function generateRandomString($length = 10)
*/
public static function generateUuid(): string
{
return sprintf(
'%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0x0fff) | 0x4000,
mt_rand(0, 0x3fff) | 0x8000,
mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0xffff)
);
// RFC 4122 v4 from a CSPRNG: these values become payment idempotency and
// lookup keys, so they must be unguessable (rand()/mt_rand() are not).
$data = random_bytes(16);
$data[6] = chr(ord($data[6]) & 0x0f | 0x40);
$data[8] = chr(ord($data[8]) & 0x3f | 0x80);
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}
}
2 changes: 1 addition & 1 deletion src/Gateway/IvoryCost/Mono/MonoGateway.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public function payment(array $params)

$amount = $params['amount'];
$phone = $params['phone_number'];
$reference = $params['reference'] ?? uniqid('momo_');
$reference = $params['reference'] ?? 'momo_' . bin2hex(random_bytes(8));
$currency = $params['currency'] ?? 'XOF';

return $payment->requestToPay([
Expand Down
12 changes: 12 additions & 0 deletions src/Gateway/IvoryCost/Orange/OrangeTokenGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,12 @@ public function getToken()
*/
public function setUrl(string $url)
{
// Basic-auth credentials are POSTed to this URL, so never allow a
// cleartext endpoint.
if (stripos($url, 'https://') !== 0) {
throw new \InvalidArgumentException('The Orange token endpoint must use HTTPS.');
}

$this->get_token_url = $url;
}

Expand All @@ -87,6 +93,12 @@ public function setUrl(string $url)
*/
public function setTokenGeneratorEndpoint(string $url)
{
// Basic-auth credentials are POSTed to this URL, so never allow a
// cleartext endpoint.
if (stripos($url, 'https://') !== 0) {
throw new \InvalidArgumentException('The Orange token endpoint must use HTTPS.');
}

$this->get_token_url = $url;
}

Expand Down
6 changes: 3 additions & 3 deletions src/Shared/Wave/WaveClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ public function createCheckoutSession(array $data, ?string $idempotencyKey = nul
public function retrieveCheckoutSession(string $sessionId): WaveCheckoutSession
{
try {
$response = $this->http->get("/v1/checkout/sessions/{$sessionId}");
$response = $this->http->get("/v1/checkout/sessions/" . rawurlencode($sessionId));

$content = $response->getBody()->getContents();
$sessionData = json_decode($content, true);
Expand Down Expand Up @@ -217,7 +217,7 @@ public function searchCheckoutSessions(string $clientReference): array
public function refundCheckoutSession(string $sessionId): bool
{
try {
$response = $this->http->post("/v1/checkout/sessions/{$sessionId}/refund");
$response = $this->http->post("/v1/checkout/sessions/" . rawurlencode($sessionId) . "/refund");
return $response->getStatusCode() === 200;
} catch (\GuzzleHttp\Exception\ClientException $e) {
return $this->handleClientException($e);
Expand Down Expand Up @@ -246,7 +246,7 @@ public function refundCheckoutSession(string $sessionId): bool
public function expireCheckoutSession(string $sessionId): bool
{
try {
$response = $this->http->post("/v1/checkout/sessions/{$sessionId}/expire");
$response = $this->http->post("/v1/checkout/sessions/" . rawurlencode($sessionId) . "/expire");
return $response->getStatusCode() === 200;
} catch (\GuzzleHttp\Exception\ClientException $e) {
return $this->handleClientException($e);
Expand Down
26 changes: 24 additions & 2 deletions src/Support/TransactionLogger.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public function __construct(string $logPath = '', bool $enabled = true)
$this->enabled = $enabled;

if ($this->enabled && !file_exists($this->logPath)) {
mkdir($this->logPath, 0755, true);
mkdir($this->logPath, 0700, true);
}
}

Expand All @@ -53,6 +53,28 @@ public function __construct(string $logPath = '', bool $enabled = true)
* @param array $context
* @return void
*/
/**
* Recursively mask secret-bearing keys so credentials in gateway
* responses are never written to the log files.
*
* @param array $data
* @return array
*/
private function redact(array $data): array
{
$sensitive = '/(key|secret|passwo?r?d|token|authorization|signature|apikey|credential|private|cvv|pin)/i';

foreach ($data as $k => $v) {
if (is_string($k) && preg_match($sensitive, $k)) {
$data[$k] = '[REDACTED]';
} elseif (is_array($v)) {
$data[$k] = $this->redact($v);
}
}

return $data;
}

public function log(string $level, string $message, array $context = []): void
{
if (!$this->enabled) {
Expand All @@ -63,7 +85,7 @@ public function log(string $level, string $message, array $context = []): void
'timestamp' => date('Y-m-d H:i:s'),
'level' => $level,
'message' => $message,
'context' => $context,
'context' => $this->redact($context),
];

$filename = $this->logPath . '/payment_' . date('Y-m-d') . '.log';
Expand Down
27 changes: 21 additions & 6 deletions src/Webhook/WebhookHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,20 @@ public function __construct(string $provider, string $secret)
* @return WebhookEvent
* @throws PaymentException
*/
public function handle(array $payload, ?string $signature = null): WebhookEvent
public function handle(array $payload, ?string $signature = null, ?string $rawBody = null): WebhookEvent
{
// Validate signature if provided
if ($signature && !$this->validateSignature($payload, $signature)) {
// The signature is mandatory. An unsigned webhook must never be trusted,
// otherwise anyone can POST a forged "payment success" event (fraud).
if (!is_string($signature) || $signature === '') {
throw new PaymentException('Missing webhook signature', 401);
}

// Verify against the exact bytes the provider signed when the raw body
// is available; re-encoding the decoded array changes key order and
// escaping and would never match a real gateway signature.
$signed = $rawBody ?? $payload;

if (!$this->validateSignature($signed, $signature)) {
throw new PaymentException('Invalid webhook signature', 401);
}

Expand All @@ -60,10 +70,14 @@ public function handle(array $payload, ?string $signature = null): WebhookEvent
* @param string $signature
* @return bool
*/
public function validateSignature(array $payload, string $signature): bool
public function validateSignature(string|array $signed, string $signature): bool
{
$expectedSignature = hash_hmac('sha256', json_encode($payload), $this->secret);

// Prefer the raw request body (string); fall back to canonical JSON for
// callers that only have the decoded array.
$message = is_array($signed) ? json_encode($signed) : $signed;

$expectedSignature = hash_hmac('sha256', (string) $message, $this->secret);

return hash_equals($expectedSignature, $signature);
}

Expand All @@ -79,6 +93,7 @@ public static function parseRequest(): array

return [
'payload' => $data ?? [],
'raw' => $body,
'signature' => $_SERVER['HTTP_X_SIGNATURE'] ?? $_SERVER['HTTP_X_WEBHOOK_SIGNATURE'] ?? null,
'headers' => getallheaders(),
];
Expand Down
14 changes: 12 additions & 2 deletions tests/WebhookHandlerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,23 @@ public function testHandleValidWebhook()
'amount' => 1000,
];

$event = $this->handler->handle($payload);

$signature = hash_hmac('sha256', json_encode($payload), $this->secret);

$event = $this->handler->handle($payload, $signature);

$this->assertInstanceOf(WebhookEvent::class, $event);
$this->assertEquals('orange', $event->getProvider());
$this->assertEquals('TX-123', $event->getTransactionId());
}

public function testMissingSignatureIsRejected()
{
$this->expectException(PaymentException::class);

// An unsigned webhook must be refused, not trusted.
$this->handler->handle(['event' => 'payment.success', 'status' => 'paid', 'amount' => 100000]);
}

public function testValidateSignature()
{
$payload = ['test' => 'data'];
Expand Down
Loading