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
11 changes: 11 additions & 0 deletions app/Http/Controllers/PaymentGatewayWebHookController.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
use models\exceptions\ValidationException;
use Exception;
use OpenApi\Attributes as OA;
use Stripe\Exception\SignatureVerificationException;

/**
* Class PaymentGatewayWebHookController
Expand Down Expand Up @@ -179,6 +180,11 @@ public function genericConfirm($application_type, LaravelRequest $request){
Log::warning($ex);
return $this->error412(["error" => 'payload error']);
}
catch (SignatureVerificationException $ex){
// message only: the trace carries the webhook signing secret (verifyHeader() argument)
Log::warning(sprintf("PaymentGatewayWebHookController::genericConfirm application_type %s invalid signature: %s", $application_type, $ex->getMessage()));
return $this->error400(["error" => 'payload error']);
}
catch (Exception $ex){
Log::error($ex);
return $this->error400(["error" => 'payload error']);
Expand Down Expand Up @@ -289,6 +295,11 @@ public function confirm($summit_id, $application_type, LaravelRequest $request){
Log::warning($ex);
return $this->error412(["error" => 'payload error']);
}
catch (SignatureVerificationException $ex){
// message only: the trace carries the webhook signing secret (verifyHeader() argument)
Log::warning(sprintf("PaymentGatewayWebHookController::confirm summit %s application_type %s invalid signature: %s", $summit_id, $application_type, $ex->getMessage()));
return $this->error400(["error" => 'payload error']);
}
catch (Exception $ex){
Log::error($ex);
return $this->error400(["error" => 'payload error']);
Expand Down
5 changes: 3 additions & 2 deletions app/Jobs/Payments/CreatePaymentProfileMQJob.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
use Illuminate\Support\Facades\Log;
use models\summit\IPaymentConstants;
use models\summit\ISummitRepository;
use models\summit\PaymentGatewayProfile;
use models\summit\Summit;

class CreatePaymentProfileMQJob implements ShouldQueue
Expand Down Expand Up @@ -67,13 +68,13 @@ public function handle(PaymentsMQJob $job): void{
return;
}
$response = $this->payments_api->getPaymentProfile($summit_id, $id);
Log::debug("CreatePaymentProfileMQJob::handle", ['response' => $response]);
Log::debug("CreatePaymentProfileMQJob::handle", ['response' => PaymentGatewayProfile::toLogContext($response)]);
$summit = $this->summit_repository->getById($summit_id);
if($summit instanceof Summit) {
// mappings
$response['external_id'] = $id;
$response['active'] = $response['is_active'] ?? false;
Log::debug("CreatePaymentProfileMQJob::handle creating payment profile", ['response' => $response ]);
Log::debug("CreatePaymentProfileMQJob::handle creating payment profile", ['response' => PaymentGatewayProfile::toLogContext($response)]);
$this->service->addPaymentProfile($summit, $response);
}
$job->delete();
Expand Down
6 changes: 3 additions & 3 deletions app/Jobs/Payments/UpdatePaymentProfileMQJob.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ public function handle(PaymentsMQJob $job): void{
return;
}
$response = $this->payments_api->getPaymentProfile($summit_id, $id);
Log::debug("UpdatePaymentProfileMQJob::handle", ['response' => $response]);
Log::debug("UpdatePaymentProfileMQJob::handle", ['response' => PaymentGatewayProfile::toLogContext($response)]);
$summit = $this->summit_repository->getById($summit_id);
$local_payment_profile =$this->payment_gateway_profile_repository->getByExternalId($id);
if($summit instanceof Summit) {
Expand All @@ -90,11 +90,11 @@ public function handle(PaymentsMQJob $job): void{
else{
Log::warning("UpdatePaymentProfileMQJob::handle local profile does not exists ...");
$response = $this->payments_api->getPaymentProfile($summit_id, $id);
Log::debug("UpdatePaymentProfileMQJob::handle get from payment api", ['response' => $response]);
Log::debug("UpdatePaymentProfileMQJob::handle get from payment api", ['response' => PaymentGatewayProfile::toLogContext($response)]);
// mappings
$response['external_id'] = $id;
$response['active'] = $response['is_active'] ?? false;
Log::debug("UpdatePaymentProfileMQJob::handle creating payment profile", ['response' => $response ]);
Log::debug("UpdatePaymentProfileMQJob::handle creating payment profile", ['response' => PaymentGatewayProfile::toLogContext($response)]);
$this->service->addPaymentProfile($summit, $response);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ final class PaymentGatewayProfileFactory
*/
public static function build(string $provider, array $params): ?PaymentGatewayProfile
{
Log::debug("PaymentGatewayProfileFactory::build()", ['provider' => $provider, 'params' => $params]);
Log::debug("PaymentGatewayProfileFactory::build()", ['provider' => $provider, 'params' => PaymentGatewayProfile::toLogContext($params)]);
return static::populate(static::create($provider), $params);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,36 @@ public function setTestMode(): void

abstract public function buildWebHook(): void;

/**
* Fields of a payment profile payload that can be logged. API keys and webhook secrets
* are never among them.
*/
const LoggableFields = [
'id',
'external_id',
'provider',
'application_type',
'active',
'is_active',
'test_mode_enabled',
'send_email_receipt',
'set_webhooks',
];

/**
* Returns only the loggable fields of a payment profile payload (as sent by the admin API or
* returned by purchases-api), so the payload can be logged without its keys. Anything that
* is not an array, such as the null PaymentsApi::getPaymentProfile() returns on a 404, gives
* an empty context: logging must never be what makes a caller fail.
* @param mixed $payload
* @return array
*/
public static function toLogContext(mixed $payload): array
{
if (!is_array($payload)) return [];
return array_intersect_key($payload, array_flip(self::LoggableFields));
}

/**
* Deletes at the payment gateway every webhook that this in-memory instance created itself.
* Called when the transaction meant to persist the profile fails: the DB rollback cannot
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ public function getTestWebhookSecretKey(): ?string
*/
public function setLiveWebHookData(array $webhook_data): void
{
Log::debug(sprintf("StripePaymentProfile::setLiveWebHookData payload %s", json_encode($webhook_data)));
Log::debug(sprintf("StripePaymentProfile::setLiveWebHookData id %s", $webhook_data['id'] ?? ''));

$this->live_webhook_id = $webhook_data['id'];
$this->live_webhook_secret_key = $webhook_data['secret_key'];
Expand All @@ -127,7 +127,7 @@ public function setLiveWebHookData(array $webhook_data): void
*/
public function setTestWebHookData(array $webhook_data): void
{
Log::debug(sprintf("StripePaymentProfile::setTestWebHookData payload %s", json_encode($webhook_data)));
Log::debug(sprintf("StripePaymentProfile::setTestWebHookData id %s", $webhook_data['id'] ?? ''));
$this->test_webhook_id = $webhook_data['id'];
$this->test_webhook_secret_key = $webhook_data['secret_key'];
}
Expand Down
4 changes: 2 additions & 2 deletions app/Services/Apis/AbstractOAuth2Api.php
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ protected function getAccessToken():?string{
$accessToken = $client->getAccessToken('client_credentials', ['scope' => $scopes]);
$token = $accessToken->getToken();
$expires_in = $accessToken->getExpires() - time();
Log::debug(sprintf("AbstractOAuth2Api::getAccessToken - setting new access token %s expires in %s", $token, $expires_in));
Log::debug(sprintf("AbstractOAuth2Api::getAccessToken - setting new access token expires in %s", $expires_in));
$ttl = $expires_in - self::SkewTime;
if($ttl < 0)
$ttl = $expires_in;
Expand All @@ -156,7 +156,7 @@ protected function getAccessToken():?string{
throw $ex;
}
}
Log::debug(sprintf("AbstractOAuth2Api::getAccessToken - returning access token %s", $token));
Log::debug(sprintf("AbstractOAuth2Api::getAccessToken - returning access token (%s)", empty($token) ? 'empty' : 'set'));
return $token;
}

Expand Down
13 changes: 9 additions & 4 deletions app/Services/Apis/PaymentGateways/LawPayApi.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,11 @@ public function __construct(array $config)
(
sprintf
(
"LawPayApi::__construct config %s",
json_encode($config)
"LawPayApi::__construct account_id %s test_mode_enabled %s secret_key %s public_key %s",
$this->account_id,
json_encode($this->test_mode_enabled),
empty($this->secret_key) ? 'not set' : 'set',
empty($this->public_key) ? 'not set' : 'set'
)
);
}
Expand All @@ -93,7 +96,8 @@ public function preProcessOrder(SummitOrder $order): SummitOrder
*/
public function postProcessOrder(SummitOrder $order, array $payload = []):SummitOrder
{
Log::debug(sprintf("LawPayApi::postProcessOrder order %s payload %s", $order->getId(), json_encode($payload)));
// the payload carries the one-time payment token (payment_method_id): log its keys only
Log::debug(sprintf("LawPayApi::postProcessOrder order %s payload keys %s", $order->getId(), implode(',', array_keys($payload))));

$summit_id = $order->getSummitId();
$token_id = $payload['payment_method_id'] ?? null;
Expand Down Expand Up @@ -164,7 +168,8 @@ public function generatePayment(array $payload): array
if (empty($this->public_key))
throw new \InvalidArgumentException();

Log::debug(sprintf("LawPayApi::generatePayment payload %s ",json_encode($payload)));
// the payload carries the one-time payment token (token_id): leave it out
Log::debug(sprintf("LawPayApi::generatePayment amount %s metadata %s", $payload['amount'] ?? '', json_encode($payload['metadata'] ?? [])));
try {
ChargeIO::setCredentials(new ChargeIO_Credentials(
$this->public_key,
Expand Down
53 changes: 34 additions & 19 deletions app/Services/Apis/PaymentGateways/StripeApi.php
Original file line number Diff line number Diff line change
Expand Up @@ -72,13 +72,28 @@ public function __construct(array $config)
(
sprintf
(
"StripeApi::__construct secret_key %s webhook_secret_key %s",
$this->secret_key,
$this->webhook_secret_key
"StripeApi::__construct secret_key %s (%s) webhook_secret_key %s",
empty($this->secret_key) ? 'not set' : 'set',
self::keyMode($this->secret_key),
empty($this->webhook_secret_key) ? 'not set' : 'set'
)
);
}

/**
* Mode of a Stripe API key, read from its prefix, so logs can tell live from test calls
* without ever printing the key.
* @param string|null $key
* @return string
*/
private static function keyMode(?string $key): string
{
if (empty($key)) return 'none';
if (str_contains($key, '_live_')) return 'live';
if (str_contains($key, '_test_')) return 'test';
return 'unknown';
}

/**
* @param string $webhook_secret_key
*/
Expand All @@ -92,7 +107,7 @@ public function setWebHookSecretKey(string $webhook_secret_key):void{
*/
private function extractPaymentMethodInfo(array $stripeObject): array
{
Log::debug(sprintf("StripeApi::extractPaymentMethodInfo %s", json_encode($stripeObject)));
Log::debug(sprintf("StripeApi::extractPaymentMethodInfo %s %s", $stripeObject['object'] ?? '', $stripeObject['id'] ?? ''));

$isIntent = $stripeObject['object'] === 'payment_intent';
$charge = null;
Expand Down Expand Up @@ -248,10 +263,10 @@ public function processCallback(LaravelRequest $request): array
(
sprintf
(
"StripeApi::processCallback Stripe-Signature %s requestContent %s webHook Secret %s",
$signature,
$requestContent,
$this->webhook_secret_key
"StripeApi::processCallback body %s bytes Stripe-Signature %s webhook_secret_key %s",
strlen($requestContent),
empty($signature) ? 'missing' : 'present',
empty($this->webhook_secret_key) ? 'not set' : 'set'
)
);

Expand All @@ -262,6 +277,7 @@ public function processCallback(LaravelRequest $request): array
);

$event = Event::constructFrom(json_decode($requestContent, true));
Log::debug(sprintf("StripeApi::processCallback event %s type %s", $event->id, $event->type));
if (!in_array($event->type, ["payment_intent.succeeded", "payment_intent.payment_failed"]))
throw new \InvalidArgumentException();

Expand Down Expand Up @@ -291,13 +307,11 @@ public function processCallback(LaravelRequest $request): array
}

throw new ValidationException(sprintf("event type %s not handled!", $event->type));
} catch (\UnexpectedValueException $e) {
Log::warning($e);
// Invalid payload
throw $e;
} catch (SignatureVerificationException $e) {
Log::warning($e);
// Invalid signature
} catch (\UnexpectedValueException|SignatureVerificationException $e) {
// Invalid payload or signature. Log the message only: the trace of an exception
// thrown by WebhookSignature::verifyHeader() carries its arguments, the webhook
// signing secret among them.
Log::warning(sprintf("StripeApi::processCallback %s: %s", get_class($e), $e->getMessage()));
throw $e;
} catch (\Exception $e) {
Log::warning($e);
Expand Down Expand Up @@ -475,7 +489,7 @@ public function getCartStatus(string $cart_id): ?string
if (is_null($intent))
throw new \InvalidArgumentException();

Log::debug(sprintf("StripeApi::getCartStatus calling cart_id %s intent %s", $cart_id, json_encode($intent)));
Log::debug(sprintf("StripeApi::getCartStatus cart_id %s intent %s status %s", $cart_id, $intent->id, $intent->status));
return $intent->status;
}
catch(Exception $ex){
Expand Down Expand Up @@ -506,7 +520,8 @@ public function createWebHook(string $webhook_endpoint_url): array
],
]);

Log::debug(sprintf("StripeApi::createWebHook webhook_endpoint_url %s res %s", $webhook_endpoint_url, $res->toJSON()));
// the response carries the endpoint signing secret: log only what identifies the endpoint
Log::debug(sprintf("StripeApi::createWebHook webhook_endpoint_url %s id %s livemode %s", $webhook_endpoint_url, $res->id, json_encode($res->livemode)));

return [
'id' => $res->id,
Expand All @@ -532,7 +547,7 @@ public function getWebHookById(string $id){

$res = WebhookEndpoint::retrieve($id);
if(!is_null($res))
Log::debug(sprintf("StripeApi::getWebHookById id %s res %s", $id, $res->toJSON()));
Log::debug(sprintf("StripeApi::getWebHookById id %s url %s status %s", $id, $res->url, $res->status));

return $res;
}
Expand Down Expand Up @@ -629,7 +644,7 @@ public function getPaymentDetailsInfo(string $cart_id): ?array
if (is_null($intent))
throw new \InvalidArgumentException();

Log::debug(sprintf("StripeApi::getPaymentDetailsInfo pi %s ", json_encode($intent)));
Log::debug(sprintf("StripeApi::getPaymentDetailsInfo pi %s status %s", $intent->id, $intent->status));

return $this->extractPaymentMethodInfo($intent->toArray());
}
Expand Down
2 changes: 1 addition & 1 deletion app/Services/Auth/OAuth2ClientFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public static function build(array $idpConfig, array $appConfig, string $redirec
sprintf(
"OAuth2ClientFactory::build client_id %s client_secret %s scopes %s",
$client_id,
$client_secret,
empty($client_secret) ? 'not set' : 'set',
$scopes
)
);
Expand Down
4 changes: 2 additions & 2 deletions app/Services/Model/Imp/PaymentGatewayProfileService.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public function addPaymentProfile(Summit $summit, array $payload): ?PaymentGatew
$built_profiles = [];
try {
$profile = $this->tx_service->transaction(function () use ($summit, $payload, &$built_profiles) {
Log::debug("PaymentGatewayProfileService::addPaymentProfilee", ["summit" => $summit->getId(), 'payload' => $payload]);
Log::debug("PaymentGatewayProfileService::addPaymentProfilee", ["summit" => $summit->getId(), 'payload' => PaymentGatewayProfile::toLogContext($payload)]);
$is_active = isset($payload['active']) && boolval($payload['active']) == true;
// check before building the profile, so that a rejected one never reaches the gateway
if ($is_active) {
Expand Down Expand Up @@ -128,7 +128,7 @@ public function deletePaymentProfile(Summit $summit, int $child_id): void
public function updatePaymentProfile(Summit $summit, int $child_id, array $payload): ?PaymentGatewayProfile
{
return $this->tx_service->transaction(function () use ($summit, $child_id, $payload) {
Log::debug("PaymentGatewayProfileService::updatePaymentProfile", ["summit" => $summit->getId(), "profile_id" => $child_id, "payload" => $payload]);
Log::debug("PaymentGatewayProfileService::updatePaymentProfile", ["summit" => $summit->getId(), "profile_id" => $child_id, "payload" => PaymentGatewayProfile::toLogContext($payload)]);
$profile = $summit->getPaymentProfileById($child_id);
if (is_null($profile))
throw new EntityNotFoundException();
Expand Down
Loading
Loading