payfrit-api/api/workers/createAccount.php
John Mizerek 1f81d98c52 Initial PHP API migration from CFML
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.
2026-03-14 14:26:59 -07:00

84 lines
2.1 KiB
PHP

<?php
require_once __DIR__ . '/../helpers.php';
runAuth();
/**
* Create or reuse Stripe Connect Express account for worker
* POST: { UserID: int }
*/
$data = readJsonBody();
$userID = (int) ($data['UserID'] ?? 0);
global $userId;
if ($userID <= 0) $userID = $userId;
if ($userID <= 0) {
apiAbort(['OK' => false, 'ERROR' => 'missing_params', 'MESSAGE' => 'UserID is required.']);
}
try {
$qUser = queryOne("
SELECT StripeConnectedAccountID, EmailAddress, FirstName, LastName
FROM Users WHERE ID = ?
", [$userID]);
if (!$qUser) {
apiAbort(['OK' => false, 'ERROR' => 'user_not_found']);
}
$existingAccountID = trim($qUser['StripeConnectedAccountID'] ?? '');
if (!empty($existingAccountID)) {
jsonResponse([
'OK' => true,
'ACCOUNT_ID' => $existingAccountID,
'CREATED' => false,
]);
}
// Create new Stripe Connect Express account
$stripeSecretKey = getenv('STRIPE_SECRET_KEY') ?: '';
$postFields = [
'type' => 'express',
'country' => 'US',
'capabilities[transfers][requested]' => 'true',
'metadata[user_id]' => $userID,
];
$userEmail = trim($qUser['EmailAddress'] ?? '');
if (!empty($userEmail)) {
$postFields['email'] = $userEmail;
}
$ch = curl_init('https://api.stripe.com/v1/accounts');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query($postFields),
CURLOPT_USERPWD => $stripeSecretKey . ':',
CURLOPT_RETURNTRANSFER => true,
]);
$result = curl_exec($ch);
curl_close($ch);
$acctData = json_decode($result, true);
if (isset($acctData['error'])) {
apiAbort(['OK' => false, 'ERROR' => $acctData['error']['message']]);
}
$newAccountID = $acctData['id'];
// Save to Users table
queryTimed("UPDATE Users SET StripeConnectedAccountID = ? WHERE ID = ?", [$newAccountID, $userID]);
jsonResponse([
'OK' => true,
'ACCOUNT_ID' => $newAccountID,
'CREATED' => true,
]);
} catch (Exception $e) {
jsonResponse(['OK' => false, 'ERROR' => $e->getMessage()]);
}