Complete port of all 163 API endpoints from Lucee/CFML to PHP 8.3. Shared helpers in api/helpers.php (DB, auth, request/response, security). PDO prepared statements throughout. Same JSON response shapes as CFML.
57 lines
2.2 KiB
PHP
57 lines
2.2 KiB
PHP
<?php
|
|
require_once __DIR__ . '/../helpers.php';
|
|
require_once __DIR__ . '/../config/stripe.php';
|
|
runAuth();
|
|
|
|
try {
|
|
$data = readJsonBody();
|
|
$userID = (int) ($data['UserID'] ?? 0);
|
|
|
|
if ($userID === 0) apiAbort(['OK' => false, 'ERROR' => 'UserID is required']);
|
|
|
|
$config = getStripeConfig();
|
|
|
|
$qUser = queryOne("SELECT StripeCustomerId, EmailAddress, FirstName, LastName FROM Users WHERE ID = ?", [$userID]);
|
|
if (!$qUser) apiAbort(['OK' => false, 'ERROR' => 'User not found']);
|
|
|
|
$stripeCustomerId = $qUser['StripeCustomerId'] ?? '';
|
|
|
|
// Create Stripe Customer if user doesn't have one
|
|
if (empty(trim($stripeCustomerId))) {
|
|
$customerParams = ['metadata[user_id]' => $userID];
|
|
$customerName = trim(($qUser['FirstName'] ?? '') . ' ' . ($qUser['LastName'] ?? ''));
|
|
if (!empty($customerName)) $customerParams['name'] = $customerName;
|
|
if (!empty(trim($qUser['EmailAddress'] ?? ''))) $customerParams['email'] = $qUser['EmailAddress'];
|
|
|
|
$customerData = stripeRequest('POST', 'https://api.stripe.com/v1/customers', $customerParams);
|
|
|
|
if (isset($customerData['error'])) {
|
|
apiAbort(['OK' => false, 'ERROR' => 'Failed to create customer: ' . $customerData['error']['message']]);
|
|
}
|
|
|
|
$stripeCustomerId = $customerData['id'];
|
|
queryTimed("UPDATE Users SET StripeCustomerId = ? WHERE ID = ?", [$stripeCustomerId, $userID]);
|
|
}
|
|
|
|
// Create Ephemeral Key (need raw response for SDK)
|
|
$ephemeralRaw = stripeRequestRaw(
|
|
'https://api.stripe.com/v1/ephemeral_keys',
|
|
['customer' => $stripeCustomerId],
|
|
['Stripe-Version' => '2023-10-16']
|
|
);
|
|
|
|
$ephemeralData = json_decode($ephemeralRaw, true);
|
|
if (isset($ephemeralData['error'])) {
|
|
apiAbort(['OK' => false, 'ERROR' => 'Failed to create ephemeral key: ' . $ephemeralData['error']['message']]);
|
|
}
|
|
|
|
jsonResponse([
|
|
'OK' => true,
|
|
'CUSTOMER' => $stripeCustomerId,
|
|
'EPHEMERAL_KEY' => $ephemeralRaw, // Raw JSON for SDK
|
|
'PUBLISHABLE_KEY' => $config['publishableKey'],
|
|
]);
|
|
|
|
} catch (Exception $e) {
|
|
jsonResponse(['OK' => false, 'ERROR' => $e->getMessage(), 'DETAIL' => '']);
|
|
}
|