Fix Paddle customer lookup for billing
This commit is contained in:
@@ -17,8 +17,10 @@ class PaddleCustomerService
|
||||
return $tenant->paddle_customer_id;
|
||||
}
|
||||
|
||||
$email = $tenant->contact_email ?: ($tenant->user?->email ?? null);
|
||||
|
||||
$payload = [
|
||||
'email' => $tenant->contact_email ?: ($tenant->user?->email ?? null),
|
||||
'email' => $email,
|
||||
'name' => $tenant->name,
|
||||
];
|
||||
|
||||
@@ -26,7 +28,19 @@ class PaddleCustomerService
|
||||
throw new PaddleException('Tenant email address required to create Paddle customer.');
|
||||
}
|
||||
|
||||
$response = $this->client->post('/customers', $payload);
|
||||
try {
|
||||
$response = $this->client->post('/customers', $payload);
|
||||
} catch (PaddleException $exception) {
|
||||
$existingCustomerId = $this->resolveExistingCustomerId($tenant, $email, $exception);
|
||||
if ($existingCustomerId) {
|
||||
$tenant->forceFill(['paddle_customer_id' => $existingCustomerId])->save();
|
||||
|
||||
return $existingCustomerId;
|
||||
}
|
||||
|
||||
throw $exception;
|
||||
}
|
||||
|
||||
$customerId = Arr::get($response, 'data.id') ?? Arr::get($response, 'id');
|
||||
|
||||
if (! $customerId) {
|
||||
@@ -38,4 +52,29 @@ class PaddleCustomerService
|
||||
|
||||
return $customerId;
|
||||
}
|
||||
|
||||
protected function resolveExistingCustomerId(Tenant $tenant, string $email, PaddleException $exception): ?string
|
||||
{
|
||||
if ($exception->status() !== 409 || Arr::get($exception->context(), 'error.code') !== 'customer_already_exists') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$response = $this->client->get('/customers', [
|
||||
'email' => $email,
|
||||
'per_page' => 1,
|
||||
]);
|
||||
|
||||
$customerId = Arr::get($response, 'data.0.id') ?? Arr::get($response, 'data.0.customer_id');
|
||||
|
||||
if (! $customerId) {
|
||||
Log::warning('Paddle customer lookup by email returned no id', [
|
||||
'tenant' => $tenant->id,
|
||||
'error_code' => Arr::get($exception->context(), 'error.code'),
|
||||
]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
return $customerId;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user