diff --git a/CRM/Core/Payment/Square.php b/CRM/Core/Payment/Square.php index 8c775ba1..035bfd2e 100644 --- a/CRM/Core/Payment/Square.php +++ b/CRM/Core/Payment/Square.php @@ -2,6 +2,7 @@ use CRM_Square_ExtensionUtil as E; use Civi\Api4\ContributionRecur; +use Civi\Api4\Payment; use Civi\Api4\PaymentToken; use Civi\Payment\Exception\PaymentProcessorException; use Civi\Payment\PropertyBag; @@ -10,7 +11,9 @@ use Square\Types\SubscriptionSource; use Square\Payments\Requests\CreatePaymentRequest; use Square\Subscriptions\Requests\CreateSubscriptionRequest; +use Square\Refunds\Requests\GetRefundsRequest; use Square\Refunds\Requests\RefundPaymentRequest; +use Square\Types\PaymentRefund; require_once E::path() . '/vendor/autoload.php'; /** @@ -33,6 +36,16 @@ */ class CRM_Core_Payment_Square extends CRM_Core_Payment { + /** + * How many times doRefund() checks on a refund Square has not completed yet. + */ + protected const REFUND_STATUS_CHECKS = 5; + + /** + * Microseconds between those checks. + */ + protected const REFUND_STATUS_CHECK_INTERVAL = 1000000; + /** * Payment-processor instance configuration. * @@ -101,8 +114,14 @@ public function buildForm(&$form) { $jsVars = [ 'id' => (int) ($this->_paymentProcessor['id'] ?? 0), 'applicationId' => $this->_paymentProcessor['user_name'] ?? '', - 'locationId' => $this->_paymentProcessor['signature'] ?? ($this->_paymentProcessor['password'] ?? ''), + // Never fall back to any other credential: everything here is + // published to the browser. + 'locationId' => trim((string) ($this->_paymentProcessor['signature'] ?? '')), 'isSandbox' => (bool) $isSandbox, + // For the buyer verification details js/square.js passes to Square + // when tokenizing the card. + 'currency' => (method_exists($form, 'getCurrency') ? $form->getCurrency() : NULL) ?: 'USD', + 'countryIsoCodes' => (object) CRM_Core_PseudoConstant::countryIsoCode(), ]; // Add hidden field for the payment token. @@ -236,9 +255,10 @@ protected function processorId(): int { } /** - * Validate Square configuration by making a real SDK call. + * Check every Square credential this processor needs is configured. * * @return string|null + * An error message naming the missing ones, or NULL. */ public function checkConfig() { $missing = []; @@ -313,7 +333,7 @@ public function handleInvoicePaymentCreated(array $payload) { } /** - * Sync a Square invoice.payment_failed webhook event. + * Sync a Square invoice.scheduled_charge_failed webhook event. * * @param array $invoice * @@ -323,29 +343,6 @@ public function syncInvoicePaymentFailedFromSquare(array $invoice): void { $this->reconciler()->syncInvoicePaymentFailedFromSquare($invoice); } - /** - * Handle a subscription.canceled webhook event. - * - * @param array $payload - * Full decoded JSON body from Square webhook. - * - * @see CRM_Square_Reconciler::handleSubscriptionCancelled() - */ - public function handleSubscriptionCancelled(array $payload) { - $this->reconciler()->handleSubscriptionCancelled($payload); - } - - /** - * Sync a Square subscription cancellation into CiviCRM. - * - * @param string $squareSubscriptionId - * - * @see CRM_Square_Reconciler::syncSubscriptionCancellationFromSquare() - */ - public function syncSubscriptionCancellationFromSquare($squareSubscriptionId) { - $this->reconciler()->syncSubscriptionCancellationFromSquare($squareSubscriptionId); - } - /** * Ensure a Square customer exists for this contact, saving any submitted card. * @@ -409,11 +406,68 @@ public function doDirectPayment(&$params) { */ public function doPayment(&$params, $component = 'contribute') { $this->_component = $component; - // Determine if this is a recurring payment. - if (!empty($params['is_recur']) || !empty($params['contributionRecurID'])) { - return $this->doRecurPayment($params); + try { + // Determine if this is a recurring payment. + if (!empty($params['is_recur']) || !empty($params['contributionRecurID'])) { + return $this->doRecurPayment($params); + } + return $this->doOneTimePayment($params); } - return $this->doOneTimePayment($params); + catch (PaymentProcessorException $e) { + // Square declined the card: CiviCRM's checkout cleans up. + throw $e; + } + catch (CRM_Core_Payment_SquareOutcomeUnknownException $e) { + // Already logged. A contribution page keeps its Pending contribution + // for the webhook to complete; event registration only handles + // PaymentProcessorException, and has no contribution yet. + if ($component === 'event') { + throw new PaymentProcessorException($e->getMessage(), 0, [], $e); + } + throw $e; + } + catch (\Throwable $e) { + // Anything else happened before Square could charge the card (or + // Square rejected the request), so nothing was taken: report it as a + // failed payment, which CiviCRM's checkout knows how to clean up. + \Civi::log('square')->error('Square checkout failed: ' . $e->getMessage(), ['exception' => $e]); + throw new PaymentProcessorException(E::ts('Your payment could not be processed. Please try again, or contact us if the problem continues.'), 0, [], $e); + } + } + + /** + * The Square Web Payments SDK card token submitted with the billing form. + * + * Webform CiviCRM's confirm-form path does not always merge $_POST values + * into payment params, so the request is the fallback. + * + * @param array $params + * + * @return string|null + */ + protected function getPaymentToken(array $params): ?string { + $token = CRM_Square_Customers::cardNonce($params) + ?? $_POST['square_payment_token'] + ?? $_REQUEST['square_payment_token'] + ?? NULL; + return empty($token) ? NULL : (string) $token; + } + + /** + * Log, and describe to the payer, a charge Square may have made without confirming it. + * + * @param \Throwable $e + * @param string $reference + * What was being paid, for the log. + * + * @return \CRM_Core_Payment_SquareOutcomeUnknownException + */ + protected function paymentOutcomeUnknown(\Throwable $e, string $reference): CRM_Core_Payment_SquareOutcomeUnknownException { + \Civi::log('square')->error("Square: could not confirm the outcome of {$reference} on payment processor {$this->processorId()}; check the Square Dashboard before the payer tries again. " . $e->getMessage(), ['exception' => $e]); + return new CRM_Core_Payment_SquareOutcomeUnknownException( + E::ts('We could not confirm whether your payment went through. Please do not pay again yet: contact us so we can check.'), + 0, [], $e + ); } /** @@ -445,15 +499,7 @@ protected function doOneTimePayment(&$params) { } // 2. Extract Web Payments SDK token. - // Webform CiviCRM's confirm-form path does not always merge $_POST - // values into payment params, so we fall back to the request globals. - $token = $params['square_payment_token'] - ?? $params['payment_token'] - ?? $params['token'] - ?? $_POST['square_payment_token'] - ?? $_REQUEST['square_payment_token'] - ?? NULL; - + $token = $this->getPaymentToken($params); if (!$token) { throw new \CRM_Core_Exception('Missing Square payment token.'); } @@ -461,8 +507,8 @@ protected function doOneTimePayment(&$params) { // Persist it back into $params so downstream code can see it. $params['square_payment_token'] = $token; - $amountCents = (int) round(((float) $amount) * 100); $currency = $params['currency'] ?? $params['currencyID'] ?? 'USD'; + $amountMinorUnits = CRM_Square_Currency::toMinorUnits($amount, $currency); // 3. Idempotency key, derived from the checkout's own reference so that a // retried request for the same checkout can never charge twice. Every @@ -478,7 +524,7 @@ protected function doOneTimePayment(&$params) { $requestValues = [ 'idempotencyKey' => $idempotencyKey, 'sourceId' => $token, - 'amountMoney' => new Money(['amount' => $amountCents, 'currency' => $currency]), + 'amountMoney' => new Money(['amount' => $amountMinorUnits, 'currency' => $currency]), 'locationId' => $this->getLocationId(), ]; @@ -496,24 +542,35 @@ protected function doOneTimePayment(&$params) { $requestValues['referenceId'] = (string) $params['invoiceID']; } - // 5. Send request. - $response = $this->callSquare(fn (SquareClient $client) => $client->payments->create(new CreatePaymentRequest($requestValues))); - $payment = $response->getPayment(); - if (empty($payment) || empty($payment->getId())) { - throw new \CRM_Core_Exception('Square payment failed: Missing payment ID.'); + // 5. Send request. A decline or rejected request means nothing was + // charged; a server error, timeout or unreadable response does not. + try { + $response = $this->callSquare(fn (SquareClient $client) => $client->payments->create(new CreatePaymentRequest($requestValues))); + } + catch (CRM_Core_Payment_SquareRetryableException $e) { + throw $this->paymentOutcomeUnknown($e, "payment {$paymentReference}"); } - - $trxnId = $payment->getId(); // 6. Report the outcome; CiviCRM's checkout records the payment against // the returned trxn_id. A payment Square has authorized but not yet // settled is reported Pending — payment.updated completes it later. - $isCompleted = CRM_Square_Status::mapPaymentStatus($payment->getStatus() ?? 'UNKNOWN') === CRM_Square_Status::contributionStatusId('Completed'); - $statusName = $isCompleted ? 'Completed' : 'Pending'; - $params['trxn_id'] = $trxnId; - $params['payment_status_id'] = CRM_Square_Status::contributionStatusId($statusName); - $params['payment_status'] = $statusName; - $params['contribution_status_id'] = $params['payment_status_id']; + // Square has accepted the charge by now, so no failure from here on + // may be reported as a failed payment. + try { + $payment = $response->getPayment(); + if (empty($payment) || empty($payment->getId())) { + throw new \CRM_Core_Exception('Square payment response has no payment ID.'); + } + $isCompleted = CRM_Square_Status::mapPaymentStatus($payment->getStatus() ?? 'UNKNOWN') === CRM_Square_Status::contributionStatusId('Completed'); + $statusName = $isCompleted ? 'Completed' : 'Pending'; + $params['trxn_id'] = $payment->getId(); + $params['payment_status_id'] = CRM_Square_Status::contributionStatusId($statusName); + $params['payment_status'] = $statusName; + $params['contribution_status_id'] = $params['payment_status_id']; + } + catch (\Throwable $e) { + throw $this->paymentOutcomeUnknown($e, "payment {$paymentReference}"); + } return $params; } @@ -541,15 +598,7 @@ protected function doOneTimePayment(&$params) { */ public function doRecurPayment(&$params) { // 1. Extract token from Web Payments SDK. - // Webform CiviCRM's confirm-form path does not always merge $_POST - // values into payment params, so we fall back to the request globals. - $token = $params['square_payment_token'] - ?? $params['payment_token'] - ?? $params['token'] - ?? $_POST['square_payment_token'] - ?? $_REQUEST['square_payment_token'] - ?? NULL; - + $token = $this->getPaymentToken($params); if (!$token) { throw new CRM_Core_Exception('Missing Square card token for recurring payments.'); } @@ -566,18 +615,17 @@ public function doRecurPayment(&$params) { throw new CRM_Core_Exception('Missing contributionRecurID for Square recurring payments.'); } - // 3. Ensure customer exists / or create one + // 3. Determine the plan variation first: an amount or cadence Square + // cannot bill is refused before any customer or card is saved. + $planVariationId = $this->subscriptions()->getPlanVariationIdForParams($params); + CRM_Core_Payment_SquareDebugLogger::log("Square doRecurPayment: Using plan variation ID {$planVariationId} for CiviCRM recur ID {$recurId}"); + + // 4. Ensure the customer exists (saving the card), with current details. $customers = $this->customers(); $customerId = $customers->ensureSquareCustomer($params); - if ($customers->findSquareCustomerById($customerId)) { - CRM_Core_Payment_SquareDebugLogger::log("Square doRecurPayment: Found existing Square customer ID {$customerId} for CiviCRM recur ID {$recurId}"); - $customers->updateSquareCustomerDetails($customerId, $params); - } - else { - throw new CRM_Core_Exception("Failed to find or create Square customer for CiviCRM recur ID {$recurId}"); - } + $customers->updateSquareCustomerDetails($customerId, $params); - // 4. Fetch the Square card ID via the PaymentToken that + // 5. Fetch the Square card ID via the PaymentToken that // ensureSquareCustomer() -> createCardOnFile() just attached to this // recurring contribution. Card nonces are single-use, so we must not // redeem $token a second time here — ensureSquareCustomer() already @@ -589,18 +637,12 @@ public function doRecurPayment(&$params) { } CRM_Core_Payment_SquareDebugLogger::log("Square doRecurPayment: Using card ID {$cardId} for customer ID {$customerId} and CiviCRM recur ID {$recurId}"); - // 5. Determine plan ID - $planVariationId = $this->subscriptions()->getPlanVariationIdForParams($params); - CRM_Core_Payment_SquareDebugLogger::log("Square doRecurPayment: Using plan variation ID {$planVariationId} for CiviCRM recur ID {$recurId}"); - // 6. Generate idempotency key tied to the recurring record so re-posts don't duplicate. $idempotencyKey = $this->idempotencyKey('subscription', (string) $recurId); $source = [ 'contact_id' => (string) ($params['contactID'] ?? $params['contact_id'] ?? ''), 'recur_id' => (string) $recurId, ]; - // Implode key and value of source - // convert array to string with maintain key value. $note = json_encode($source, JSON_UNESCAPED_SLASHES); // 7. Build subscription payload. startDate is deliberately omitted: @@ -619,22 +661,34 @@ public function doRecurPayment(&$params) { 'source' => new SubscriptionSource(['name' => $note]), ]); - // 8. Send subscription create request - $response = $this->callSquare(fn (SquareClient $client) => $client->subscriptions->create($createSubscriptionRequest)); - $subscription = $response->getSubscription(); - - if (empty($subscription) || empty($subscription->getId())) { - throw new CRM_Core_Exception('Failed to create Square subscription.'); + // 8. Send subscription create request. Square bills the first + // installment as soon as the subscription exists, so once this may have + // succeeded, no failure may be reported as a failed payment. + try { + $response = $this->callSquare(fn (SquareClient $client) => $client->subscriptions->create($createSubscriptionRequest)); + } + catch (CRM_Core_Payment_SquareRetryableException $e) { + throw $this->paymentOutcomeUnknown($e, "subscription for recurring contribution {$recurId}"); + } + try { + $subscription = $response->getSubscription(); + if (empty($subscription) || empty($subscription->getId())) { + throw new CRM_Core_Exception('Square subscription response has no subscription ID.'); + } + $subscriptionId = $subscription->getId(); + CRM_Core_Payment_SquareDebugLogger::log('Square subscription created: ' . json_encode([ + 'subscription_id' => $subscriptionId, + 'recur_id' => $recurId, + ])); + + // 9. Link the subscription to the recurring contribution, which stays + // Pending until its first payment is recorded. + $this->saveRecurSubscription((int) $recurId, $subscriptionId); + } + catch (\Throwable $e) { + $reference = "subscription " . ($subscriptionId ?? '(unknown ID)') . " for recurring contribution {$recurId}"; + throw $this->paymentOutcomeUnknown($e, $reference); } - $subscriptionId = $subscription->getId(); - CRM_Core_Payment_SquareDebugLogger::log('Square subscription created: ' . json_encode([ - 'subscription_id' => $subscriptionId, - 'recur_id' => $recurId, - ])); - - // 9. Link the subscription to the recurring contribution, which stays - // Pending until its first payment is recorded. - $this->saveRecurSubscription((int) $recurId, $subscriptionId); // 10. The checkout's contribution stays Pending until Square confirms // the first charge. No trxn_id is returned: the subscription ID @@ -686,7 +740,7 @@ protected function saveRecurSubscription(int $recurId, string $subscriptionId): ->addWhere('id', '=', $recurId) ->addValue('processor_id', $subscriptionId) ->addValue('trxn_id', $subscriptionId) - ->addValue('contribution_status_id', CRM_Square_Status::contributionStatusId('Pending')) + ->addValue('contribution_status_id', CRM_Square_Status::recurStatusId('Pending')) ->execute(); } @@ -711,57 +765,170 @@ public function supportsRefund() { /** * Perform a refund via Square Refunds API. * + * Only a refund Square has completed is reported: refund_status + * 'Completed' is what CiviCRM and mjwshared's refund form record, and the + * only status that form accepts. Square accepts a card refund as PENDING + * until it has the funds, which can take far longer than this request and + * can end in FAILED, so a refund still PENDING after a short wait is + * reported as an error and left for the refund.updated webhook to record + * once Square completes it (see CRM_Square_Reconciler::syncRefundFromSquare()). + * * @param array $params + * trxn_id (the Square payment ID) and amount; currency is optional, and + * ignored in favour of the payment's own. * * @return array + * refund_trxn_id (the Square refund ID), refund_status ('Completed'), + * trxn_date and fee_amount. * - * @throws \CRM_Core_Exception + * @throws \Civi\Payment\Exception\PaymentProcessorException */ public function doRefund(&$params) { $trxnId = $params['trxn_id'] ?? $params['transaction_id'] ?? NULL; if (empty($trxnId)) { - throw new CRM_Core_Exception('Missing transaction ID for refund.'); + throw new PaymentProcessorException('Missing transaction ID for refund.'); } if (empty($params['amount'])) { - throw new CRM_Core_Exception('Missing refund amount.'); + throw new PaymentProcessorException('Missing refund amount.'); } $rawAmount = (float) $params['amount']; - $amountInCents = (int) round($rawAmount * 100); - if ($amountInCents <= 0) { - throw new CRM_Core_Exception('Refund amount must be greater than zero.'); + if ($rawAmount <= 0) { + throw new PaymentProcessorException('Refund amount must be greater than zero.'); } - $currency = $params['currencyID'] ?? $params['currency'] ?? 'USD'; - - $refundRequest = new RefundPaymentRequest([ - 'idempotencyKey' => $this->idempotencyKey('refund', (string) $trxnId . ':' . $amountInCents), - 'paymentId' => $trxnId, - 'amountMoney' => new Money(['amount' => $amountInCents, 'currency' => $currency]), - ]); + try { + // The refund must be in the payment's currency, which mjwshared's + // refund form does not always pass on. + [$paymentCurrency, $refundCount] = $this->getRefundContext((string) $trxnId); + $currency = $paymentCurrency ?? $params['currencyID'] ?? $params['currency'] ?? 'USD'; + $amountMinorUnits = CRM_Square_Currency::toMinorUnits($rawAmount, $currency); + if ($amountMinorUnits <= 0) { + throw new PaymentProcessorException('Refund amount must be greater than zero.'); + } - $response = $this->createRefund($refundRequest); - $refund = $response->getRefund(); + // The key changes once CiviCRM has recorded a refund, so a further + // refund of the same amount is a new refund — not mistaken by Square + // for a retry of the first, which would return the first again. Until + // then it does not change, so a retry of a refund whose outcome was + // lost gets Square's original refund back instead of a second one. + $refundRequest = new RefundPaymentRequest([ + 'idempotencyKey' => $this->idempotencyKey('refund', "{$trxnId}:{$amountMinorUnits}:{$refundCount}"), + 'paymentId' => $trxnId, + 'amountMoney' => new Money(['amount' => $amountMinorUnits, 'currency' => $currency]), + ]); + + $refund = $this->createRefund($refundRequest)->getRefund(); + if (!empty($refund) && !empty($refund->getId())) { + $refund = $this->awaitRefundOutcome($refund); + } + } + catch (PaymentProcessorException $e) { + throw $e; + } + catch (\Throwable $e) { + throw new PaymentProcessorException(E::ts('Square refund failed: %1', [1 => $e->getMessage()]), 0, [], $e); + } if (empty($refund) || empty($refund->getId())) { - $msg = 'Square refund failed: unexpected response.'; - throw new CRM_Core_Exception($msg); + throw new PaymentProcessorException('Square refund failed: unexpected response.'); } - $status = $refund->getStatus() ?? 'UNKNOWN'; - - if (!in_array($status, ['PENDING', 'COMPLETED', 'APPROVED'], TRUE)) { - $msg = "Square refund not completed. Status: {$status}"; - throw new CRM_Core_Exception($msg); + $status = strtoupper($refund->getStatus() ?? 'UNKNOWN'); + if ($status === 'PENDING') { + throw new PaymentProcessorException(E::ts('Square accepted refund %1 but has not completed it yet, so it is not recorded in CiviCRM now. It will be recorded automatically once Square completes it. Do not refund this payment again.', [1 => $refund->getId()])); + } + if (!in_array($status, ['COMPLETED', 'APPROVED'], TRUE)) { + throw new PaymentProcessorException("Square refund not completed. Status: {$status}"); } + $createdAt = $refund->getCreatedAt(); return [ - 'refund_status' => $status, 'refund_trxn_id' => $refund->getId(), + 'refund_status' => 'Completed', + 'trxn_date' => date('Y-m-d H:i:s', $createdAt && strtotime($createdAt) ? strtotime($createdAt) : time()), + // Square reports the refunded processing fee later, if at all. + 'fee_amount' => 0, ]; } + /** + * The currency of a payment recorded in CiviCRM, and how many refunds its contribution has. + * + * @param string $paymentTrxnId + * The Square payment ID. + * + * @return array + * [currency or NULL if the payment is not recorded, number of refunds]. + */ + protected function getRefundContext(string $paymentTrxnId): array { + $payment = Payment::get(FALSE) + ->addSelect('contribution_id', 'currency') + ->addWhere('trxn_id', '=', $paymentTrxnId) + ->addWhere('total_amount', '>', 0) + ->execute() + ->first(); + if (empty($payment['contribution_id'])) { + return [NULL, 0]; + } + $refundCount = Payment::get(FALSE) + ->addSelect('id') + ->addWhere('contribution_id', '=', $payment['contribution_id']) + ->addWhere('total_amount', '<', 0) + ->execute() + ->count(); + return [$payment['currency'] ?? NULL, $refundCount]; + } + + /** + * Wait briefly for Square to complete a refund it accepted as PENDING. + * + * Most card refunds complete within seconds. One Square has to fund from + * the seller's bank account can stay PENDING much longer, and may fail. + * + * @param \Square\Types\PaymentRefund $refund + * + * @return \Square\Types\PaymentRefund + * The refund as Square last reported it. + */ + protected function awaitRefundOutcome(PaymentRefund $refund): PaymentRefund { + for ($check = 0; $check < self::REFUND_STATUS_CHECKS && strtoupper((string) $refund->getStatus()) === 'PENDING'; $check++) { + $this->pause(self::REFUND_STATUS_CHECK_INTERVAL); + try { + $refund = $this->getRefund((string) $refund->getId()) ?? $refund; + } + catch (\Throwable $e) { + // The refund exists at Square either way; report what is known. + \Civi::log('square')->warning("Square: could not check on refund {$refund->getId()}: " . $e->getMessage()); + break; + } + } + return $refund; + } + + /** + * A refund as Square currently reports it. + * + * @param string $refundId + * + * @return \Square\Types\PaymentRefund|null + * + * @throws \CRM_Core_Exception + */ + protected function getRefund(string $refundId): ?PaymentRefund { + return $this->callSquare(fn (SquareClient $client) => $client->refunds->get(new GetRefundsRequest(['refundId' => $refundId])))->getRefund(); + } + + /** + * Wait, between checks on a refund. + * + * @param int $microseconds + */ + protected function pause(int $microseconds): void { + usleep($microseconds); + } + /** * Call the Square Refunds API through a testable seam. * @@ -842,7 +1009,8 @@ public function doCancelRecurring(PropertyBag $propertyBag): array { public function changeSubscriptionAmount(&$message = '', $params = []) { $subscriptionId = $params['subscriptionId'] ?? NULL; $recurId = (int) ($params['contributionRecurID'] ?? $params['id'] ?? 0); - $amount = $params['amount'] ?? NULL; + // The form passes the amount as submitted, e.g. "1,000.00". + $amount = isset($params['amount']) ? CRM_Utils_Rule::cleanMoney((string) $params['amount']) : NULL; if (empty($subscriptionId) || !$recurId || !is_numeric($amount) || (float) $amount <= 0) { throw new PaymentProcessorException(E::ts('A Square subscription and a positive amount are required to change the amount.')); } @@ -901,8 +1069,8 @@ protected function getRecurForAmountChange(int $recurId): ?array { /** * Cancel a Square subscription by its processor ID. * - * Low-level helper used by doCancelRecurring() and by the civicrm_post hook. - * Makes the Square API call directly without PropertyBag logic. + * Low-level helper used by doCancelRecurring(). Makes the Square API call + * directly without PropertyBag logic. * * @param string $subscriptionId * Square subscription ID (e.g. "SUB_xxx"). @@ -966,16 +1134,6 @@ public function getWebhookSignatureKey() { return $this->_paymentProcessor['subject'] ?? NULL; } - /** - * Handle subscription cancellation from Square webhook. - * - * @param array $payload - * Full webhook payload from Square. - */ - public function handleSubscriptionCanceled(array $payload) { - $this->handleSubscriptionCancelled($payload); - } - /** * Handle invoice paid from Square webhook. * @@ -1036,17 +1194,19 @@ public function handlePaymentNotification() { http_response_code(200); $rawData = file_get_contents('php://input'); + // Returning ends the request: CRM_Core_Payment::handleIPN() calls + // CRM_Utils_System::civiExit() next. if (!$this->validateWebhookSignature($rawData, getallheaders())) { - Civi::log()->error('Square IPN: webhook signature validation failed.'); + // Already logged. http_response_code(401); - exit(); + return; } $payload = json_decode($rawData, TRUE); if (empty($payload)) { Civi::log()->error('Square IPN: invalid JSON body received.'); http_response_code(400); - exit(); + return; } CRM_Core_Payment_SquareDebugLogger::log('Square IPN: handlePaymentNotification() received webhook. event_id=' . ($payload['event_id'] ?? 'unknown') . ', type=' . ($payload['type'] ?? 'unknown') . ', processor_id=' . $this->getID()); diff --git a/CRM/Core/Payment/SquareIPN.php b/CRM/Core/Payment/SquareIPN.php index d65179d2..666add3f 100644 --- a/CRM/Core/Payment/SquareIPN.php +++ b/CRM/Core/Payment/SquareIPN.php @@ -10,10 +10,14 @@ * Entry point: onReceiveWebhook() — called from CRM_Core_Payment_Square::handlePaymentNotification(). * * Handles: - * subscription.created, subscription.updated, subscription.canceled - * invoice.created, invoice.payment_made, invoice.payment_failed + * subscription.created, subscription.updated + * invoice.created, invoice.payment_made, invoice.scheduled_charge_failed * payment.updated, refund.created, refund.updated * + * Square has no subscription.canceled event: a cancellation arrives as a + * subscription.updated with a canceled_date, while its status is still + * ACTIVE. + * * Webhook lifecycle: * 1. onReceiveWebhook() validates the event type, deduplicates via * civicrm_paymentprocessor_webhook (a table owned by the mjwshared @@ -111,10 +115,9 @@ public static function getSupportedEventTypes(): array { return [ 'subscription.created', 'subscription.updated', - 'subscription.canceled', 'invoice.created', 'invoice.payment_made', - 'invoice.payment_failed', + 'invoice.scheduled_charge_failed', 'payment.updated', 'refund.created', 'refund.updated', @@ -409,19 +412,13 @@ public function processWebhookEvent(array $payload, string $eventType): bool { break; case 'subscription.updated': + // Also how a cancellation arrives: Square sets a canceled_date. if (!empty($this->subscription_id)) { $this->_paymentProcessor->syncSubscriptionFromSquare($this->subscription_id); CRM_Core_Payment_SquareDebugLogger::log("Square IPN: subscription.updated synced for {$this->subscription_id}"); } break; - case 'subscription.canceled': - if (!empty($this->subscription_id)) { - $this->_paymentProcessor->syncSubscriptionCancellationFromSquare($this->subscription_id); - CRM_Core_Payment_SquareDebugLogger::log("Square IPN: subscription.canceled synced for {$this->subscription_id}"); - } - break; - case 'invoice.created': // Nothing to record. Square publishes invoice.created while the // invoice is still a DRAFT it has not tried to charge, so it is never @@ -430,7 +427,7 @@ public function processWebhookEvent(array $payload, string $eventType): bool { // contribution CiviCRM created at checkout. The installment is // recorded once Square confirms the charge, via invoice.payment_made // or payment.updated (see - // CRM_Core_Payment_Square::recordSubscriptionInstallment()). + // CRM_Square_Reconciler::recordSubscriptionInstallment()). CRM_Core_Payment_SquareDebugLogger::log("Square IPN: invoice.created noted for invoice {$this->invoice_id} (subscription " . ($this->subscription_id ?? 'null') . '); nothing is recorded until Square confirms payment.'); break; @@ -439,7 +436,7 @@ public function processWebhookEvent(array $payload, string $eventType): bool { CRM_Core_Payment_SquareDebugLogger::log("Square IPN: invoice.payment_made processed for invoice {$this->invoice_id}"); break; - case 'invoice.payment_failed': + case 'invoice.scheduled_charge_failed': $invoice = $obj['invoice'] ?? []; if (!empty($invoice)) { $this->_paymentProcessor->syncInvoicePaymentFailedFromSquare($invoice); diff --git a/CRM/Core/Payment/SquareOutcomeUnknownException.php b/CRM/Core/Payment/SquareOutcomeUnknownException.php new file mode 100644 index 00000000..f17164cf --- /dev/null +++ b/CRM/Core/Payment/SquareOutcomeUnknownException.php @@ -0,0 +1,19 @@ + 0, + 'CLP' => 0, + 'DJF' => 0, + 'GNF' => 0, + 'ISK' => 0, + 'JPY' => 0, + 'KMF' => 0, + 'KRW' => 0, + 'PYG' => 0, + 'RWF' => 0, + 'UGX' => 0, + 'UYI' => 0, + 'VND' => 0, + 'VUV' => 0, + 'XAF' => 0, + 'XOF' => 0, + 'XPF' => 0, + // Three decimal places. + 'BHD' => 3, + 'IQD' => 3, + 'JOD' => 3, + 'KWD' => 3, + 'LYD' => 3, + 'OMR' => 3, + 'TND' => 3, + ]; + + /** + * The number of decimal places in a currency's amounts. + * + * @param string|null $currency + * ISO 4217 code. + * + * @return int + */ + public static function decimals(?string $currency): int { + return self::DECIMALS[strtoupper(trim((string) $currency))] ?? 2; + } + + /** + * An amount in Square's smallest unit of the currency (e.g. cents). + * + * @param float|int|string $amount + * @param string|null $currency + * + * @return int + */ + public static function toMinorUnits($amount, ?string $currency): int { + return (int) round((float) $amount * (10 ** self::decimals($currency))); + } + + /** + * An amount from Square's smallest unit of the currency. + * + * @param int|string $minorUnits + * @param string|null $currency + * + * @return float + */ + public static function fromMinorUnits($minorUnits, ?string $currency): float { + return (float) $minorUnits / (10 ** self::decimals($currency)); + } + +} diff --git a/CRM/Square/Customers.php b/CRM/Square/Customers.php index 50360139..cc44a316 100644 --- a/CRM/Square/Customers.php +++ b/CRM/Square/Customers.php @@ -13,7 +13,6 @@ use Square\Types\CustomerTextFilter; use Square\Customers\Requests\CreateCustomerRequest; use Square\Customers\Requests\UpdateCustomerRequest; -use Square\Customers\Requests\GetCustomersRequest; use Square\Customers\Requests\SearchCustomersRequest; use Square\Cards\Requests\CreateCardRequest; @@ -42,59 +41,6 @@ public function __construct(CRM_Square_Gateway $gateway) { $this->gateway = $gateway; } - /** - * Look up an existing Square customer by email. - * - * @param string $email - * Customer email address. - * - * @return string|null - */ - protected function findSquareCustomerByEmail($email) { - if (empty($email)) { - return NULL; - } - - $response = $this->gateway->call(fn (SquareClient $client) => $client->customers->search(new SearchCustomersRequest([ - 'query' => new CustomerQuery([ - 'filter' => new CustomerFilter([ - 'emailAddress' => new CustomerTextFilter(['exact' => $email]), - ]), - ]), - ]))); - - $customers = $response->getCustomers(); - if (!empty($customers[0])) { - return $customers[0]->getId(); - } - - return NULL; - } - - /** - * Look up an existing Square customer by ID. - * - * @param string $customerID - * Square customer ID. - * - * @return string|null - */ - public function findSquareCustomerById($customerID) { - if (empty($customerID)) { - return NULL; - } - - $response = $this->gateway->call(fn (SquareClient $client) => $client->customers->get( - new GetCustomersRequest(['customerId' => $customerID]) - )); - $customer = $response->getCustomer(); - if (!empty($customer) && !empty($customer->getId())) { - return $customer->getId(); - } - - return NULL; - } - /** * Update a Square customer's details from CiviCRM payment parameters. * @@ -131,16 +77,15 @@ public function updateSquareCustomerDetails($customerID, $params) { } /** - * Ensure a Square customer exists for this contact. Also handles storing card_id if available. + * Ensure a Square customer exists for this contact, saving any submitted card. * - * 1. Check for a stored Square Customer ID in a custom field. - * 2. If none exists, check for existing Square customer by email. - * 3. If still none, create a new customer in Square. - * 4. Persist the new customer ID back to the contact. - * 5. If card token/nonce is present in $params, create and store the card_id as well. + * The customer is, in order: the one already mapped to the contact for + * this payment processor; an existing Square customer adopted for it (see + * adoptSquareCustomer()); or a new one. * * @param array $params - * Contribution params (includes contactID/contact_id). + * Contribution params (includes contactID/contact_id, and the card + * token as square_payment_token). * * @return string * Square customer ID. @@ -148,164 +93,158 @@ public function updateSquareCustomerDetails($customerID, $params) { * @throws CRM_Core_Exception */ public function ensureSquareCustomer(array $params) { - $contactID = $params['contactID'] ?? $params['contact_id'] ?? NULL; + $contactID = (int) ($params['contactID'] ?? $params['contact_id'] ?? 0); if (!$contactID) { throw new CRM_Core_Exception('Missing contactID in params for Square recurring payment.'); } - $contactID = (int) $contactID; - - // 1. Check if we already have a stored Square Customer ID. - if ($customerId = $this->getSquareCustomerId($contactID)) { - CRM_Core_Payment_SquareDebugLogger::log('Square customer already exists for contact ' . $contactID . ': ' . $customerId); - // If a fresh card token/nonce was submitted (e.g. a returning donor - // entering a new card), attach and store it. Card nonces are - // single-use, so this must be the only place that redeems it. - $cardNonce = $params['square_payment_token'] - ?? $params['payment_token'] - ?? $params['token'] - ?? NULL; - if (!empty($cardNonce)) { - $this->createCardOnFile($customerId, $cardNonce, $params, $contactID); - } - return $customerId; - } - // Migration logic: check whether this contact already exists in Square based on reference_id. - // If Square already has a customer with reference_id == Civi contact ID, we adopt that one. - try { - $lookupResponse = $this->gateway->call(fn (SquareClient $client) => $client->customers->search(new SearchCustomersRequest([ - 'query' => new CustomerQuery([ - 'filter' => new CustomerFilter([ - 'referenceId' => new CustomerTextFilter(['exact' => (string) $contactID]), - ]), - ]), - ]))); - $migratedCustomers = $lookupResponse->getCustomers(); - if (!empty($migratedCustomers[0])) { - $migratedCustomerId = $migratedCustomers[0]->getId(); - // Check if another Civi contact already mapped to this customerId - // (for this payment processor). - $existingContactId = CRM_Core_DAO::singleValueQuery( - 'SELECT contact_id FROM square_customer_map WHERE square_customer_id = %1 AND payment_processor_id = %2', - [1 => [$migratedCustomerId, 'String'], 2 => [$this->gateway->processorId(), 'Integer']] - ); - - if (!empty($existingContactId) && (int) $existingContactId !== $contactID) { - throw new CRM_Core_Exception( - "Square customer {$migratedCustomerId} already mapped to a different CiviCRM contact ({$existingContactId})." - ); - } - - // Store mapping if safe. - $this->saveSquareCustomerId($contactID, $migratedCustomerId); + $customerId = $this->getSquareCustomerId($contactID) + ?? $this->adoptSquareCustomer($contactID) + ?? $this->createSquareCustomer($contactID); + CRM_Core_Payment_SquareDebugLogger::log("Square customer for contact {$contactID}: {$customerId}"); - // If a card token is present, attach card to this existing Square customer. - $cardNonce = $params['square_payment_token'] - ?? $params['payment_token'] - ?? $params['token'] - ?? NULL; - - if (!empty($cardNonce)) { - $this->createCardOnFile($migratedCustomerId, $cardNonce, $params, $contactID); - } - - return $migratedCustomerId; - } - } - catch (\Throwable $e) { - CRM_Core_Payment_SquareDebugLogger::log('Square migration lookup error: ' . $e->getMessage()); - } - $existingCustomerId = $this->getSquareCustomerId($contactID); - if (!empty($existingCustomerId)) { - // If card token/nonce is present, create and store card_id. - $cardNonce = $params['square_payment_token'] - ?? $params['payment_token'] - ?? $params['token'] - ?? NULL; - if (!empty($cardNonce)) { - $this->createCardOnFile($existingCustomerId, $cardNonce, $params, $contactID); - } - return $existingCustomerId; + // Card nonces are single-use, so this must be the only place that + // redeems it (e.g. a returning donor entering a new card). + $cardNonce = self::cardNonce($params); + if ($cardNonce) { + $this->createCardOnFile($customerId, $cardNonce, $params, $contactID); } + return $customerId; + } - // Load contact email. - $contact = Contact::get(FALSE) - ->addWhere('id', '=', $contactID) - ->addSelect('email') - ->execute() - ->first(); - - $email = $contact['email'] ?? NULL; - - // Check for existing Square customer by email. - $squareCustomerByEmail = $this->findSquareCustomerByEmail($email); + /** + * The card token submitted with the payment, if any. + * + * @param array $params + * + * @return string|null + */ + public static function cardNonce(array $params): ?string { + $nonce = $params['square_payment_token'] ?? $params['payment_token'] ?? $params['token'] ?? NULL; + return empty($nonce) ? NULL : (string) $nonce; + } - if (!empty($squareCustomerByEmail)) { - // Check if mapped to another contact (for this payment processor). - $existingContactId = CRM_Core_DAO::singleValueQuery( - 'SELECT contact_id FROM square_customer_map WHERE square_customer_id = %1 AND payment_processor_id = %2', - [1 => [$squareCustomerByEmail, 'String'], 2 => [$this->gateway->processorId(), 'Integer']] - ); + /** + * Map an existing Square customer to a contact that has none for this processor. + * + * Candidates are Square customers whose reference_id is the contact's ID + * (as this extension sets it), then those with the contact's email. A + * candidate already mapped to another contact on this processor is never + * shared: family members often share one email address, and each gets a + * Square customer of their own. + * + * @param int $contactID + * + * @return string|null + * The Square customer ID now mapped to the contact, or NULL if there + * was none to adopt. + * + * @throws CRM_Core_Exception + */ + protected function adoptSquareCustomer(int $contactID): ?string { + $candidates = $this->searchSquareCustomers(new CustomerFilter([ + 'referenceId' => new CustomerTextFilter(['exact' => (string) $contactID]), + ])); + $email = $this->getContactDetails($contactID)['email'] ?? NULL; + if ($email) { + $candidates = array_merge($candidates, $this->searchSquareCustomers(new CustomerFilter([ + 'emailAddress' => new CustomerTextFilter(['exact' => $email]), + ]))); + } - if (!empty($existingContactId) && (int) $existingContactId !== $contactID) { - throw new CRM_Core_Exception('This email address is already associated with a different Square customer in our system.'); + foreach (array_unique($candidates) as $candidateId) { + $mappedContactId = $this->getMappedContactId($candidateId); + if ($mappedContactId !== NULL && $mappedContactId !== $contactID) { + continue; } - - // Save mapping if none existed previously. - $this->saveSquareCustomerId($contactID, $squareCustomerByEmail); - // If card token/nonce is present, create and store card_id. - $cardNonce = $params['square_payment_token'] - ?? $params['payment_token'] - ?? $params['token'] - ?? NULL; - if (!empty($cardNonce)) { - $this->createCardOnFile($squareCustomerByEmail, $cardNonce, $params, $contactID); + $mapped = $this->saveSquareCustomerId($contactID, $candidateId); + if ($mapped !== NULL) { + CRM_Core_Payment_SquareDebugLogger::log("Square: adopted existing Square customer {$mapped} for contact {$contactID}."); + return $mapped; } - return $squareCustomerByEmail; } + return NULL; + } - // 2. Load contact info from CiviCRM using API4 for customer creation. - $contactInfo = Contact::get(FALSE) - ->addWhere('id', '=', $contactID) - ->addSelect('first_name', 'last_name', 'email') - ->execute() - ->first(); - - if (empty($contactInfo)) { + /** + * Create a Square customer for a contact, and map it to the contact. + * + * @param int $contactID + * + * @return string + * The Square customer ID mapped to the contact. + * + * @throws CRM_Core_Exception + */ + protected function createSquareCustomer(int $contactID): string { + $contact = $this->getContactDetails($contactID); + if (empty($contact)) { throw new CRM_Core_Exception("Unable to load contact {$contactID} for Square customer creation."); } - $firstName = $contactInfo['first_name'] ?? NULL; - $lastName = $contactInfo['last_name'] ?? NULL; - $email = $contactInfo['email'] ?? NULL; - $createResponse = $this->gateway->call(fn (SquareClient $client) => $client->customers->create(new CreateCustomerRequest([ - 'givenName' => $firstName, - 'familyName' => $lastName, - 'emailAddress' => $email, + 'givenName' => $contact['first_name'] ?: NULL, + 'familyName' => $contact['last_name'] ?: NULL, + 'emailAddress' => $contact['email'] ?: NULL, 'referenceId' => (string) $contactID, ]))); - $newCustomer = $createResponse->getCustomer(); if (empty($newCustomer) || empty($newCustomer->getId())) { throw new CRM_Core_Exception('Failed to create Square customer.'); } - $customerId = $newCustomer->getId(); - - // 3. Persist the customer ID mapping for this contact + processor. - $this->saveSquareCustomerId($contactID, $customerId); + // A concurrent checkout for the same contact may have mapped one first. + $mapped = $this->saveSquareCustomerId($contactID, $newCustomer->getId()); + if ($mapped === NULL) { + throw new CRM_Core_Exception("Square customer {$newCustomer->getId()} could not be mapped to contact {$contactID}."); + } + return $mapped; + } - // If card token/nonce is present, create and store card_id. - $cardNonce = $params['square_payment_token'] - ?? $params['payment_token'] - ?? $params['token'] - ?? NULL; - if (!empty($cardNonce)) { - $this->createCardOnFile($customerId, $cardNonce, $params, $contactID); + /** + * IDs of the Square customers matching a filter. + * + * @param \Square\Types\CustomerFilter $filter + * + * @return string[] + * + * @throws CRM_Core_Exception + */ + protected function searchSquareCustomers(CustomerFilter $filter): array { + $response = $this->gateway->call(fn (SquareClient $client) => $client->customers->search(new SearchCustomersRequest([ + 'query' => new CustomerQuery(['filter' => $filter]), + ]))); + $ids = []; + foreach ($response->getCustomers() ?? [] as $customer) { + if ($customer->getId()) { + $ids[] = $customer->getId(); + } } + return $ids; + } - return $customerId; + /** + * A contact's name and primary email. + * + * @param int $contactID + * + * @return array|null + * first_name, last_name and email; NULL if there is no such contact. + */ + protected function getContactDetails(int $contactID): ?array { + $contact = Contact::get(FALSE) + ->addWhere('id', '=', $contactID) + ->addSelect('first_name', 'last_name', 'email_primary.email') + ->execute() + ->first(); + if (!$contact) { + return NULL; + } + return [ + 'first_name' => $contact['first_name'] ?? NULL, + 'last_name' => $contact['last_name'] ?? NULL, + 'email' => $contact['email_primary.email'] ?? NULL, + ]; } /** @@ -316,7 +255,8 @@ public function ensureSquareCustomer(array $params) { * @param string $cardNonce * Token from Web Payments SDK. * @param array $params - * Additional parameters, possibly including verification_token. + * Payment params: billing address fields, names, email, and + * contributionRecurID. * @param int|null $contactId * CiviCRM contact ID (optional, but required to record a PaymentToken). * @@ -331,17 +271,9 @@ public function createCardOnFile($customerId, $cardNonce, array $params = [], $c } $cardValues = ['customerId' => $customerId]; - - // Add billing address if available. - if (!empty($params['billing_address'])) { - $cardValues['billingAddress'] = new Address([ - 'addressLine1' => $params['billing_address']['street_address'] ?? NULL, - 'addressLine2' => $params['billing_address']['street_address_2'] ?? NULL, - 'locality' => $params['billing_address']['city'] ?? NULL, - 'administrativeDistrictLevel1' => $params['billing_address']['state'] ?? NULL, - 'postalCode' => $params['billing_address']['postal_code'] ?? NULL, - 'country' => $this->mapCountryCode($params['billing_address']['country'] ?? 'US'), - ]); + $billingAddress = $this->billingAddress($params); + if ($billingAddress) { + $cardValues['billingAddress'] = $billingAddress; } $requestValues = [ @@ -353,11 +285,10 @@ public function createCardOnFile($customerId, $cardNonce, array $params = [], $c 'sourceId' => $cardNonce, 'card' => new Card($cardValues), ]; - // Square requires verification_token for AVS/SCA under certain conditions. - if (!empty($params['verification_token'])) { - $requestValues['verificationToken'] = $params['verification_token']; - } + // No verificationToken: buyer verification (Strong Customer + // Authentication) happens when js/square.js tokenizes the card, so the + // token itself carries it. try { $response = $this->gateway->client()->cards->create(new CreateCardRequest($requestValues)); } @@ -418,27 +349,58 @@ public function createCardOnFile($customerId, $cardNonce, array $params = [], $c } /** - * Map country to standardized 2-letter country code. + * The card's billing address, from the checkout's billing fields. + * + * CiviCRM submits them as billing_street_address-{location type ID} etc.; + * its checkout also maps them to street_address, city, state_province (an + * abbreviation), postal_code and country (an ISO code). + * + * @param array $params + * + * @return \Square\Types\Address|null + * NULL if no address was submitted. */ - protected function mapCountryCode($country) { - // Standardize country codes/names. - $countryMap = [ - 'US' => 'US', - 'USA' => 'US', - 'UNITED STATES' => 'US', - 'UNITED STATES OF AMERICA' => 'US', - 'CA' => 'CA', - 'CANADA' => 'CA', - 'GB' => 'GB', - 'UK' => 'GB', - 'UNITED KINGDOM' => 'GB', - ]; + protected function billingAddress(array $params): ?Address { + $value = static function (string $field) use ($params): ?string { + if (isset($params[$field]) && is_scalar($params[$field]) && trim((string) $params[$field]) !== '') { + return trim((string) $params[$field]); + } + foreach ($params as $key => $fieldValue) { + if (is_scalar($fieldValue) && trim((string) $fieldValue) !== '' && preg_match('/^billing_' . preg_quote($field, '/') . '-\d+$/', (string) $key)) { + return trim((string) $fieldValue); + } + } + return NULL; + }; - // Normalize input. - $normalizedCountry = strtoupper(trim($country)); + $street = $value('street_address'); + $city = $value('city'); + $postalCode = $value('postal_code'); + if ($street === NULL && $city === NULL && $postalCode === NULL) { + return NULL; + } - // Return mapped country or default to US. - return $countryMap[$normalizedCountry] ?? 'US'; + $state = $value('state_province'); + $stateId = $value('state_province_id'); + if ($stateId && ctype_digit($stateId)) { + $state = CRM_Core_PseudoConstant::stateProvinceAbbreviation((int) $stateId) ?: $state; + } + $country = $value('country'); + $countryId = $value('country_id'); + if ($countryId && ctype_digit($countryId)) { + $country = CRM_Core_PseudoConstant::countryIsoCode()[(int) $countryId] ?? $country; + } + // Square wants an ISO 3166 alpha-2 code; send none rather than a guess. + $country = ($country !== NULL && preg_match('/^[A-Za-z]{2}$/', $country)) ? strtoupper($country) : NULL; + + return new Address(array_filter([ + 'addressLine1' => $street, + 'addressLine2' => $value('supplemental_address_1'), + 'locality' => $city, + 'administrativeDistrictLevel1' => $state, + 'postalCode' => $postalCode, + 'country' => $country, + ], fn ($fieldValue) => $fieldValue !== NULL)); } /** @@ -517,6 +479,21 @@ public function getSquareCustomerId($contactId) { return $customerId !== NULL ? (string) $customerId : NULL; } + /** + * The contact a Square customer is mapped to on this processor, if any. + * + * @param string $customerId + * + * @return int|null + */ + protected function getMappedContactId(string $customerId): ?int { + $contactId = CRM_Core_DAO::singleValueQuery( + 'SELECT contact_id FROM square_customer_map WHERE square_customer_id = %1 AND payment_processor_id = %2', + [1 => [$customerId, 'String'], 2 => [$this->gateway->processorId(), 'Integer']] + ); + return $contactId === NULL ? NULL : (int) $contactId; + } + /** * Save the Square customer ID for a contact and processor. * @@ -524,12 +501,17 @@ public function getSquareCustomerId($contactId) { * * @param int $contactId * @param string $customerId + * + * @return string|null + * The customer the contact is mapped to afterwards — another one if the + * contact already had one — or NULL if $customerId belongs to another + * contact, so the contact still has none. */ - protected function saveSquareCustomerId($contactId, $customerId) { + protected function saveSquareCustomerId($contactId, $customerId): ?string { $contactId = (int) $contactId; $processorId = $this->gateway->processorId(); if ($contactId <= 0 || $processorId <= 0 || empty($customerId)) { - return; + return NULL; } // An existing mapping is never re-pointed (e.g. by two concurrent @@ -544,11 +526,12 @@ protected function saveSquareCustomerId($contactId, $customerId) { ); $mappedCustomerId = $this->getSquareCustomerId($contactId); if ($mappedCustomerId === NULL) { - Civi::log()->warning("Square: Square customer {$customerId} is already mapped to another contact on payment processor {$processorId}; not mapping it to contact {$contactId}."); + Civi::log('square')->warning("Square: Square customer {$customerId} is already mapped to another contact on payment processor {$processorId}; not mapping it to contact {$contactId}."); } elseif ($mappedCustomerId !== (string) $customerId) { - Civi::log()->warning("Square: contact {$contactId} is already mapped to Square customer {$mappedCustomerId} on payment processor {$processorId}; not re-mapping it to {$customerId}."); + Civi::log('square')->warning("Square: contact {$contactId} is already mapped to Square customer {$mappedCustomerId} on payment processor {$processorId}; not re-mapping it to {$customerId}."); } + return $mappedCustomerId; } } diff --git a/CRM/Square/Form/Settings.php b/CRM/Square/Form/Settings.php index 25a5dd8e..4e65efd4 100644 --- a/CRM/Square/Form/Settings.php +++ b/CRM/Square/Form/Settings.php @@ -7,20 +7,31 @@ * * Administer > System Settings > Square Settings. * - * Lets an admin toggle verbose Square webhook debug logging (event - * dispatch, record lookups, created/updated record IDs) without needing - * shell/API access. See CRM_Core_Payment_SquareDebugLogger. + * Lets an admin toggle verbose Square webhook debug logging (see + * CRM_Core_Payment_SquareDebugLogger), and the import of Square payments + * made outside CiviCRM (see CRM_Square_Reconciler), without needing + * shell/API access. */ class CRM_Square_Form_Settings extends CRM_Core_Form { - const SETTING_NAME = 'square_ipn_debug_logging'; + /** + * The settings on this form, with their labels. + */ + protected function getSquareSettings(): array { + return [ + 'square_ipn_debug_logging' => E::ts('Enable Square IPN Debug Logging'), + 'square_import_external_payments' => E::ts('Import Square payments made outside CiviCRM'), + ]; + } /** * Build the settings form. */ public function buildQuickForm() { CRM_Utils_System::setTitle(E::ts('Square Settings')); - $this->addYesNo(self::SETTING_NAME, E::ts('Enable Square IPN Debug Logging')); + foreach ($this->getSquareSettings() as $name => $label) { + $this->addYesNo($name, $label); + } $this->addButtons([ [ 'type' => 'submit', @@ -32,20 +43,24 @@ public function buildQuickForm() { } /** - * Set the form's default values from the current setting value. + * Set the form's default values from the current setting values. */ public function setDefaultValues() { $defaults = parent::setDefaultValues(); - $defaults[self::SETTING_NAME] = (bool) Civi::settings()->get(self::SETTING_NAME); + foreach (array_keys($this->getSquareSettings()) as $name) { + $defaults[$name] = (int) (bool) Civi::settings()->get($name); + } return $defaults; } /** - * Save the submitted setting value. + * Save the submitted setting values. */ public function postProcess() { $values = $this->exportValues(); - Civi::settings()->set(self::SETTING_NAME, !empty($values[self::SETTING_NAME])); + foreach (array_keys($this->getSquareSettings()) as $name) { + Civi::settings()->set($name, !empty($values[$name])); + } CRM_Core_Session::setStatus(E::ts('Square settings saved.'), E::ts('Saved'), 'success'); parent::postProcess(); } diff --git a/CRM/Square/Gateway.php b/CRM/Square/Gateway.php index fbad3978..26868ae7 100644 --- a/CRM/Square/Gateway.php +++ b/CRM/Square/Gateway.php @@ -152,11 +152,12 @@ public function call(callable $call) { throw $this->apiError($e); } catch (SquareException $e) { - // Transport-level failure (timeout, DNS, connection reset, etc.) — - // there's no reason to believe retrying would fail again the same - // way, so callers processing a queued webhook should retry rather - // than give up permanently. - throw new CRM_Core_Payment_SquareRetryableException('Square API request failed: ' . $e->getMessage()); + // Transport-level failure (timeout, DNS, connection reset, etc.), or + // a successful response the SDK could not read — so the request may + // well have succeeded. A queued webhook is retried; a checkout must + // treat its charge as unconfirmed, not failed (see + // CRM_Core_Payment_Square::paymentOutcomeUnknown()). + throw new CRM_Core_Payment_SquareRetryableException('Square API request failed: ' . $e->getMessage(), 0, [], $e); } } diff --git a/CRM/Square/Reconciler.php b/CRM/Square/Reconciler.php index 68973d5a..aabbd697 100644 --- a/CRM/Square/Reconciler.php +++ b/CRM/Square/Reconciler.php @@ -3,14 +3,16 @@ use Civi\Api4\Contact; use Civi\Api4\Contribution; use Civi\Api4\ContributionRecur; +use Civi\Api4\FinancialTrxn; use Civi\Api4\Payment; use Square\SquareClient; use Square\Types\InvoiceFilter; use Square\Types\InvoiceQuery; use Square\Types\InvoiceSort; -use Square\Customers\Requests\GetCustomersRequest; use Square\Subscriptions\Requests\GetSubscriptionsRequest; +use Square\Invoices\Requests\GetInvoicesRequest; use Square\Invoices\Requests\SearchInvoicesRequest; +use Square\Types\Subscription; use Square\Orders\Requests\GetOrdersRequest; /** @@ -58,6 +60,17 @@ public function __construct(CRM_Square_Gateway $gateway) { */ protected const WEBHOOK_GRACE_SECONDS = 1800; + /** + * Square invoice statuses that mean the invoice has been (or is being) paid. + */ + protected const PAID_INVOICE_STATUSES = [ + 'PAID', + 'PARTIALLY_PAID', + 'PAYMENT_PENDING', + 'REFUNDED', + 'PARTIALLY_REFUNDED', + ]; + /** * Sync a Square payment (from a payment.updated webhook) into CiviCRM. * @@ -112,7 +125,7 @@ public function syncPaymentFromSquare(array $payment) { $invoice = $this->findInvoiceForPayment($payment); if (!empty($invoice['subscription_id'])) { - $recur = $this->findRecurBySubscriptionId($invoice['subscription_id']); + $recur = $this->findOrLinkRecur($invoice['subscription_id']); if (!$recur) { $this->handleUnknownSubscription($invoice['subscription_id'], $payment['created_at'] ?? NULL, "payment {$paymentId}"); return; @@ -137,7 +150,10 @@ public function syncPaymentFromSquare(array $payment) { * * Square reports the fee in a later payment.updated than the one that * first reports the payment COMPLETED. Setting the contribution's - * fee_amount makes CiviCRM record the fee transaction. + * fee_amount makes CiviCRM record the fee transaction. The payment's own + * fee_amount is set first: every later Payment.create that carries a + * fee_amount (mjwshared's refund form sends 0) recalculates the + * contribution's fee as the total of its payments' fees. * * @param array $recorded * As returned by findRecordedPayment(). @@ -155,6 +171,7 @@ protected function recordProcessingFee(array $recorded, array $payment): void { if ($this->getContributionFeeAmount($contributionId) > 0) { return; } + $this->updatePaymentFee((int) $recorded['id'], $fee, (float) $recorded['total_amount']); $this->updateContribution($contributionId, ['fee_amount' => $fee]); CRM_Core_Payment_SquareDebugLogger::log("Square syncPaymentFromSquare(): recorded processing fee {$fee} on contribution {$contributionId} for payment {$payment['id']}."); } @@ -238,6 +255,11 @@ protected function reconcileExistingContributionPayment(array $existing, array $ /** * Import a completed Square payment taken outside CiviCRM as a new contribution. * + * Only when the square_import_external_payments setting is on, and only + * for payments at this processor's location: Square sends webhooks for + * every payment the merchant takes — point of sale, Square Online, other + * locations — and none of those is CiviCRM's to record by default. + * * @param array $payment * Payment object from Square webhooks. * @@ -247,6 +269,16 @@ protected function createContributionFromSquarePayment(array $payment): void { $paymentId = (string) $payment['id']; $orderID = $payment['order_id'] ?? NULL; $referenceId = $payment['reference_id'] ?? NULL; + + if (!$this->isImportingExternalPayments()) { + CRM_Core_Payment_SquareDebugLogger::log("Square syncPaymentFromSquare(): payment {$paymentId} matches nothing in CiviCRM; importing Square payments made outside CiviCRM is disabled, so it is ignored."); + return; + } + $locationId = $payment['location_id'] ?? NULL; + if ($locationId !== $this->gateway->getLocationId()) { + CRM_Core_Payment_SquareDebugLogger::log("Square syncPaymentFromSquare(): payment {$paymentId} was taken at location " . ($locationId ?? 'unknown') . ", not this processor's; ignored."); + return; + } CRM_Core_Payment_SquareDebugLogger::log("Square syncPaymentFromSquare(): no existing contribution found for payment {$paymentId} (order_id={$orderID}), attempting to create a new one."); // Payments made by versions of doRecurPayment() before the subscription @@ -280,7 +312,7 @@ protected function createContributionFromSquarePayment(array $payment): void { // Donation financial type resolved by name, never a hard-coded ID. $financialTypeId = $refRecurContribution['financial_type_id'] ?? CRM_Square_Status::financialTypeId('Donation'); $money = $payment['amount_money'] ?? []; - $amount = isset($money['amount']) ? ((float) $money['amount']) / 100 : 0.0; + $amount = isset($money['amount']) ? CRM_Square_Currency::fromMinorUnits($money['amount'], $money['currency'] ?? NULL) : 0.0; // Create the contribution Pending, then complete it via Payment.create so // the CiviCRM financial ledger (FinancialTrxn / EntityFinancialTrxn) is @@ -381,7 +413,7 @@ protected function installmentFromPayment(array $payment, array $invoice): array return [ 'payment_id' => (string) $payment['id'], 'invoice_id' => $invoice['id'] ?? NULL, - 'amount' => isset($money['amount']) ? ((float) $money['amount']) / 100 : NULL, + 'amount' => isset($money['amount']) ? CRM_Square_Currency::fromMinorUnits($money['amount'], $money['currency'] ?? NULL) : NULL, 'currency' => $money['currency'] ?? NULL, 'fee_amount' => $this->sumProcessingFees($payment['processing_fee'] ?? []), 'trxn_date' => $this->squareTimestampToCivi($payment['created_at'] ?? NULL), @@ -430,9 +462,9 @@ protected function installmentFromInvoice(array $invoice): array { return [ 'payment_id' => (string) $tender['payment_id'], 'invoice_id' => $invoiceId, - 'amount' => isset($money['amount']) ? ((float) $money['amount']) / 100 : NULL, + 'amount' => isset($money['amount']) ? CRM_Square_Currency::fromMinorUnits($money['amount'], $money['currency'] ?? NULL) : NULL, 'currency' => $money['currency'] ?? NULL, - 'fee_amount' => isset($tender['processing_fee_money']['amount']) ? ((float) $tender['processing_fee_money']['amount']) / 100 : NULL, + 'fee_amount' => isset($tender['processing_fee_money']['amount']) ? CRM_Square_Currency::fromMinorUnits($tender['processing_fee_money']['amount'], $tender['processing_fee_money']['currency'] ?? $money['currency'] ?? NULL) : NULL, 'trxn_date' => $this->squareTimestampToCivi($tender['created_at'] ?? $invoice['updated_at'] ?? NULL), 'payment_instrument_id' => CRM_Square_Status::mapPaymentInstrument($tender['type'] ?? NULL), ]; @@ -594,8 +626,8 @@ protected function findInstallmentContribution(array $contributions, array $recu return $contribution; } } - // Already created for this Square invoice (e.g. by invoice.payment_failed - // for an earlier attempt). + // Already created for this Square invoice (e.g. by + // invoice.scheduled_charge_failed for an earlier attempt). if (!empty($installment['invoice_id'])) { foreach ($contributions as $contribution) { if (($contribution['invoice_id'] ?? NULL) === $installment['invoice_id']) { @@ -660,8 +692,8 @@ protected function findSignupContribution(array $contributions, array $recur): ? * @throws \CRM_Core_Exception */ protected function assertAmountMatches(float $expectedAmount, string $expectedCurrency, array $installment, string $expectedBy): void { - $actualCents = $installment['amount'] === NULL ? NULL : (int) round($installment['amount'] * 100); - if ($actualCents === (int) round($expectedAmount * 100) && strcasecmp($expectedCurrency, (string) $installment['currency']) === 0) { + $actual = $installment['amount'] === NULL ? NULL : CRM_Square_Currency::toMinorUnits($installment['amount'], $expectedCurrency); + if ($actual === CRM_Square_Currency::toMinorUnits($expectedAmount, $expectedCurrency) && strcasecmp($expectedCurrency, (string) $installment['currency']) === 0) { return; } $message = sprintf( @@ -736,13 +768,15 @@ protected function squareTimestampToCivi(?string $timestamp): string { * NULL when Square has not reported any fee yet. */ protected function sumProcessingFees(array $processingFees): ?float { - $cents = NULL; + $minorUnits = NULL; + $currency = NULL; foreach ($processingFees as $fee) { if (isset($fee['amount_money']['amount'])) { - $cents = ($cents ?? 0) + (int) $fee['amount_money']['amount']; + $minorUnits = ($minorUnits ?? 0) + (int) $fee['amount_money']['amount']; + $currency = $currency ?? ($fee['amount_money']['currency'] ?? NULL); } } - return $cents === NULL ? NULL : $cents / 100; + return $minorUnits === NULL ? NULL : CRM_Square_Currency::fromMinorUnits($minorUnits, $currency); } /** @@ -789,6 +823,108 @@ protected function findRecurBySubscriptionId(string $subscriptionId): ?array { ->first(); } + /** + * The recurring contribution a Square subscription belongs to, linking it if checkout could not. + * + * Checkout (doRecurPayment()) saves the subscription ID on the recurring + * contribution once Square confirms the subscription. If Square created it + * but that confirmation was lost (e.g. a timeout: see + * CRM_Core_Payment_SquareOutcomeUnknownException), Square still bills it, + * and the subscription still names its recurring contribution and contact + * in its source (see doRecurPayment()). That is trusted only for a + * recurring contribution of this processor not linked to any subscription + * yet, whose contact this processor mapped the subscription's Square + * customer to, at this processor's location. + * + * @param string $subscriptionId + * @param \Square\Types\Subscription|null $subscription + * The subscription, if already fetched from Square. + * + * @return array|null + * As findRecurBySubscriptionId() returns it. + * + * @throws \CRM_Core_Exception + */ + protected function findOrLinkRecur(string $subscriptionId, ?Subscription $subscription = NULL): ?array { + $recur = $this->findRecurBySubscriptionId($subscriptionId); + if ($recur) { + return $recur; + } + + $subscription = $subscription ?? $this->getSquareSubscription($subscriptionId); + $source = $subscription ? json_decode((string) $subscription->getSource()?->getName(), TRUE) : NULL; + $recurId = is_array($source) && ctype_digit((string) ($source['recur_id'] ?? '')) ? (int) $source['recur_id'] : 0; + $contactId = is_array($source) && ctype_digit((string) ($source['contact_id'] ?? '')) ? (int) $source['contact_id'] : 0; + if (!$recurId || !$contactId) { + // Not created by this extension (e.g. in the Square Dashboard). + return NULL; + } + + $recur = $this->findRecurById($recurId); + if (!$recur + || !empty($recur['processor_id']) + || (int) $recur['contact_id'] !== $contactId + || $subscription->getLocationId() !== $this->gateway->getLocationId() + || $this->findContactIdBySquareCustomer((string) $subscription->getCustomerId()) !== $contactId) { + Civi::log('square')->warning("Square subscription {$subscriptionId} names recurring contribution {$recurId} of contact {$contactId}, which could not be confirmed as its own on payment processor {$this->gateway->processorId()}; not linked."); + return NULL; + } + + $this->updateRecur($recurId, ['processor_id' => $subscriptionId, 'trxn_id' => $subscriptionId]); + Civi::log('square')->warning("Square: linked subscription {$subscriptionId} to recurring contribution {$recurId}, which checkout had not linked (its outcome was not confirmed)."); + return ['processor_id' => $subscriptionId] + $recur; + } + + /** + * A recurring contribution of this processor, in its environment, by ID. + * + * @param int $recurId + * + * @return array|null + * As findRecurBySubscriptionId() returns it. + */ + protected function findRecurById(int $recurId): ?array { + return ContributionRecur::get(FALSE) + ->addSelect('id', 'contact_id', 'amount', 'currency', 'processor_id', 'contribution_status_id', 'is_email_receipt', 'is_test') + ->addWhere('id', '=', $recurId) + ->addWhere('payment_processor_id', '=', $this->gateway->processorId()) + ->addWhere('is_test', '=', $this->gateway->isTestMode()) + ->execute() + ->first(); + } + + /** + * A subscription as Square currently reports it. + * + * @param string $subscriptionId + * + * @return \Square\Types\Subscription|null + * + * @throws \CRM_Core_Exception + */ + protected function getSquareSubscription(string $subscriptionId): ?Subscription { + return $this->gateway->call(fn (SquareClient $client) => $client->subscriptions->get( + new GetSubscriptionsRequest(['subscriptionId' => $subscriptionId]) + ))->getSubscription(); + } + + /** + * An invoice's status as Square currently reports it. + * + * @param string $invoiceId + * + * @return string|null + * NULL if Square has no such invoice. + * + * @throws \CRM_Core_Exception + */ + protected function getSquareInvoiceStatus(string $invoiceId): ?string { + $invoice = $this->gateway->call(fn (SquareClient $client) => $client->invoices->get( + new GetInvoicesRequest(['invoiceId' => $invoiceId]) + ))->getInvoice(); + return $invoice ? strtoupper((string) $invoice->getStatus()) : NULL; + } + /** * The contributions of a recurring series, oldest first, excluding templates. * @@ -859,16 +995,44 @@ protected function findRecordedPayment(string $trxnId): ?array { } /** - * Find a contribution in this processor's environment by its trxn_id. + * Find a refund recorded in CiviCRM by its Square refund ID. + * + * By any processor: a refund recorded from CiviCRM's refund form may + * carry none. + * + * @param string $refundId + * + * @return array|null + * With 'id' (financial_trxn ID) and 'contribution_id'. + */ + protected function findRecordedRefund(string $refundId): ?array { + return Payment::get(FALSE) + ->addSelect('id', 'contribution_id') + ->addWhere('trxn_id', '=', $refundId) + ->addWhere('total_amount', '<', 0) + ->execute() + ->first(); + } + + /** + * Find a contribution in this processor's environment by one of its trxn_ids. * * @param string $trxnId * * @return int|null */ protected function findContributionIdByTrxnId(string $trxnId): ?int { + // Payment.create appends each payment's trxn_id to the contribution's, + // comma-separated. + $like = addcslashes($trxnId, '%_\\'); $contribution = Contribution::get(FALSE) ->addSelect('id') - ->addWhere('trxn_id', '=', $trxnId) + ->addClause('OR', + ['trxn_id', '=', $trxnId], + ['trxn_id', 'LIKE', "{$like},%"], + ['trxn_id', 'LIKE', "%,{$like}"], + ['trxn_id', 'LIKE', "%,{$like},%"] + ) ->addWhere('is_test', '=', $this->gateway->isTestMode()) ->execute() ->first(); @@ -989,7 +1153,7 @@ protected function repeatRecurContribution(array $recur, array $values): array { if (!empty($values['invoice_id'])) { // Contribution.repeattransaction does not accept invoice_id. Recording // the Square invoice lets later events for it (e.g. a successful retry - // after invoice.payment_failed) find this contribution. + // after invoice.scheduled_charge_failed) find this contribution. $this->updateContribution($contributionId, ['invoice_id' => $values['invoice_id']]); } @@ -1034,6 +1198,39 @@ protected function updateContribution(int $contributionId, array $values): void ->execute(); } + /** + * Set the fee on a recorded payment. + * + * @param int $financialTrxnId + * @param float $fee + * @param float $totalAmount + * The payment's amount, for its net amount. + * + * @throws \CRM_Core_Exception + */ + protected function updatePaymentFee(int $financialTrxnId, float $fee, float $totalAmount): void { + FinancialTrxn::update(FALSE) + ->addWhere('id', '=', $financialTrxnId) + ->addValue('fee_amount', $fee) + ->addValue('net_amount', $totalAmount - $fee) + ->execute(); + } + + /** + * Update fields on a recurring contribution. + * + * @param int $recurId + * @param array $values + * + * @throws \CRM_Core_Exception + */ + protected function updateRecur(int $recurId, array $values): void { + ContributionRecur::update(FALSE) + ->addWhere('id', '=', $recurId) + ->setValues($values) + ->execute(); + } + /** * Create a contribution. * @@ -1091,6 +1288,16 @@ public function syncRefundFromSquare(array $refund) { CRM_Core_Payment_SquareDebugLogger::log('Square syncRefundFromSquare(): missing payment_id or refund_id, skipping.'); return; } + if (in_array($refundStatus, ['REJECTED', 'FAILED'], TRUE)) { + // CiviCRM records only refunds Square has completed (see doRefund()), + // so this should not happen; if it does, it is not reversed + // automatically. + $recorded = $this->findRecordedRefund($refundId); + if ($recorded) { + Civi::log('square')->error("Square refund {$refundId} of payment {$paymentId} was {$refundStatus}, but CiviCRM recorded it as refunded on contribution {$recorded['contribution_id']}; reverse that refund manually."); + } + return; + } if (!in_array($refundStatus, ['COMPLETED', 'APPROVED'], TRUE)) { // refund.created normally reports PENDING; refund.updated follows once // Square completes (or rejects) the refund. @@ -1099,21 +1306,13 @@ public function syncRefundFromSquare(array $refund) { } $money = $refund['amount_money'] ?? NULL; - $refundAmount = ($money && isset($money['amount'])) ? ((float) $money['amount'] / 100) : NULL; + $refundAmount = ($money && isset($money['amount'])) ? CRM_Square_Currency::fromMinorUnits($money['amount'], $money['currency'] ?? NULL) : NULL; if ($refundAmount === NULL || $refundAmount <= 0) { Civi::log()->error("Square syncRefundFromSquare(): refund {$refundId} for payment {$paymentId} has no usable amount, skipping."); return; } - // refund.created and refund.updated can both report COMPLETED, in - // separate concurrent requests. - $lock = $this->acquireSquareLock('refund.' . $refundId); - try { - $this->recordSquareRefund($refund, $refundAmount); - } - finally { - $lock->release(); - } + $this->recordSquareRefund($refund, $refundAmount); } /** @@ -1141,40 +1340,61 @@ private function recordSquareRefund(array $refund, float $refundAmount): void { if ($original) { $original['contribution_id'] = $contributionId; } - if (!$original || !empty($original['payment_processor_id'])) { + if ($original && !empty($original['payment_processor_id'])) { + CRM_Core_Payment_SquareDebugLogger::log("Square syncRefundFromSquare(): Square payment {$paymentId} was recorded by another payment processor, skipping refund {$refundId}."); + return; + } + if (!$original) { + // Square does not deliver webhooks in order: the payment's own + // webhook (e.g. for a subscription installment, which only a webhook + // records) may not have been processed yet. + if ($this->isWithinWebhookGrace($refund['created_at'] ?? NULL)) { + throw new CRM_Core_Payment_SquareRetryableException("Square refund {$refundId} is for payment {$paymentId}, which is not recorded in CiviCRM yet; retrying in case its webhook has not been processed."); + } CRM_Core_Payment_SquareDebugLogger::log("Square syncRefundFromSquare(): no payment of this processor found for Square payment {$paymentId}, skipping refund {$refundId}."); return; } } $contributionId = (int) $original['contribution_id']; - // Idempotency: a replayed webhook (or refund.created and refund.updated - // both reporting COMPLETED), or a refund CiviCRM already recorded when - // staff refunded from CiviCRM (see doRefund()), must not refund twice. - if ($this->findContributionPayment($contributionId, $refundId)) { - CRM_Core_Payment_SquareDebugLogger::log("Square syncRefundFromSquare(): refund {$refundId} already recorded for contribution {$contributionId}, skipping."); - return; + // Share MJWShared's PaymentMJW.Refund lock so admin refunds and concurrent + // webhooks serialize the duplicate check and Payment.create together. + $lock = Civi::lockManager()->acquire('data.contribute.contribution.' . $contributionId); + if (!$lock->isAcquired()) { + throw new CRM_Core_Payment_SquareRetryableException("Could not acquire lock to record Square refund {$refundId} for contribution {$contributionId}."); } + try { + // Recheck after acquiring the lock: the admin action or another webhook + // may have recorded this refund while we waited. + if ($this->findContributionPayment($contributionId, $refundId)) { + CRM_Core_Payment_SquareDebugLogger::log("Square syncRefundFromSquare(): refund {$refundId} already recorded for contribution {$contributionId}, skipping."); + return; + } - $refundParams = [ - 'contribution_id' => $contributionId, - 'total_amount' => -$refundAmount, - 'trxn_id' => $refundId, - 'trxn_date' => $this->squareTimestampToCivi($refund['updated_at'] ?? $refund['created_at'] ?? NULL), - 'payment_processor_id' => $this->gateway->processorId(), - 'is_send_contribution_notification' => 0, - ]; - // A full refund is linked to the refunded payment, as CiviCRM's own - // Payment.cancel does. Not a partial one: Payment.create reverses every - // allocation of the cancelled payment in full, whatever the refund - // amount. A partial refund is allocated across the line items instead. - $isFullRefund = (int) round($refundAmount * 100) === (int) round((float) $original['total_amount'] * 100); - if ($isFullRefund) { - $refundParams['cancelled_payment_id'] = (int) $original['id']; - } - $this->recordRefundPayment($refundParams); + $refundParams = [ + 'contribution_id' => $contributionId, + 'total_amount' => -$refundAmount, + 'trxn_id' => $refundId, + 'trxn_date' => $this->squareTimestampToCivi($refund['updated_at'] ?? $refund['created_at'] ?? NULL), + 'payment_processor_id' => $this->gateway->processorId(), + 'is_send_contribution_notification' => 0, + ]; + // A full refund is linked to the refunded payment, as CiviCRM's own + // Payment.cancel does. Not a partial one: Payment.create reverses every + // allocation of the cancelled payment in full, whatever the refund + // amount. A partial refund is allocated across the line items instead. + $currency = $refund['amount_money']['currency'] ?? NULL; + $isFullRefund = CRM_Square_Currency::toMinorUnits($refundAmount, $currency) === CRM_Square_Currency::toMinorUnits($original['total_amount'], $currency); + if ($isFullRefund) { + $refundParams['cancelled_payment_id'] = (int) $original['id']; + } + $this->recordRefundPayment($refundParams); - CRM_Core_Payment_SquareDebugLogger::log("Square syncRefundFromSquare(): recorded refund {$refundId} ({$refundAmount}) against contribution {$contributionId}" . ($isFullRefund ? ", cancelling payment {$original['id']}." : '.')); + CRM_Core_Payment_SquareDebugLogger::log("Square syncRefundFromSquare(): recorded refund {$refundId} ({$refundAmount}) against contribution {$contributionId}" . ($isFullRefund ? ", cancelling payment {$original['id']}." : '.')); + } + finally { + $lock->release(); + } } /** @@ -1193,8 +1413,10 @@ public function syncInvoiceFromSquare(array $invoice) { /** * Sync a Square subscription with the corresponding CiviCRM recurring contribution. * - * This is used when Square sends a webhook (subscription.updated or subscription.canceled) - * AND also may be triggered manually by scheduled jobs. + * Called for subscription.created and subscription.updated webhooks. + * Square has no subscription.canceled event: a cancellation arrives as a + * subscription.updated with a canceled_date, while its status is still + * ACTIVE (see applySubscriptionToRecur()). * * @param string $squareSubscriptionId * The subscription ID from Square. @@ -1208,17 +1430,13 @@ public function syncSubscriptionFromSquare(string $squareSubscriptionId) { } // 1. Look up the subscription in Square - $response = $this->gateway->call(fn (SquareClient $client) => $client->subscriptions->get( - new GetSubscriptionsRequest(['subscriptionId' => $squareSubscriptionId]) - )); - $sub = $response->getSubscription(); - + $sub = $this->getSquareSubscription($squareSubscriptionId); if (empty($sub)) { throw new CRM_Core_Exception("Square subscription {$squareSubscriptionId} not found."); } // 2. Find local CiviCRM recurring contribution - $recur = $this->findRecurBySubscriptionId($squareSubscriptionId); + $recur = $this->findOrLinkRecur($squareSubscriptionId, $sub); if (empty($recur)) { // No such recurring record exists — log and stop. CRM_Core_Payment_SquareDebugLogger::log("Square sync: No local contribution_recur record found for subscription {$squareSubscriptionId}"); @@ -1228,7 +1446,7 @@ public function syncSubscriptionFromSquare(string $squareSubscriptionId) { // 3. Apply the status and amount. extractSubscriptionAmount() expects the // REST JSON shape; jsonSerialize() gives us that from the SDK object // without duplicating the extraction logic. - $this->applySubscriptionToRecur($recur, $sub->getStatus() ?? 'UNKNOWN', $this->extractSubscriptionAmount($sub->jsonSerialize())); + $this->applySubscriptionToRecur($recur, $sub->getStatus() ?? 'UNKNOWN', $this->extractSubscriptionAmount($sub->jsonSerialize()), $sub->getCanceledDate()); } /** @@ -1239,8 +1457,10 @@ public function syncSubscriptionFromSquare(string $squareSubscriptionId) { * @param string $squareStatus * @param float|null $amount * The subscription's price override, if any. + * @param string|null $canceledDate + * The subscription's canceled_date (YYYY-MM-DD), if any. */ - protected function applySubscriptionToRecur(array $recur, string $squareStatus, ?float $amount): void { + protected function applySubscriptionToRecur(array $recur, string $squareStatus, ?float $amount, ?string $canceledDate = NULL): void { $recurId = (int) $recur['id']; $currentStatus = (int) $recur['contribution_status_id']; CRM_Core_Payment_SquareDebugLogger::log("Square: applying subscription status {$squareStatus} to contribution_recur {$recurId} (current status {$currentStatus})."); @@ -1250,10 +1470,22 @@ protected function applySubscriptionToRecur(array $recur, string $squareStatus, $updates['amount'] = (float) $amount; } + // A subscription cancelled in Square stays ACTIVE (or PENDING or PAUSED) + // until its canceled_date, the end of the period already paid for, and + // Square may send no webhook when it then becomes CANCELED. So the + // canceled_date is itself the cancellation; no further invoices follow. + if ($canceledDate && in_array(strtoupper($squareStatus), ['ACTIVE', 'PENDING', 'PAUSED'], TRUE)) { + CRM_Core_Payment_SquareDebugLogger::log("Square: subscription for contribution_recur {$recurId} is {$squareStatus} but cancelled as of {$canceledDate}; treating it as CANCELED."); + $squareStatus = 'CANCELED'; + } + $mappedStatus = CRM_Square_Status::mapSubscriptionStatus($squareStatus); if ($mappedStatus !== NULL && $mappedStatus !== $currentStatus) { if ($this->isRecurStatusChangeAllowed($currentStatus, $mappedStatus)) { $updates['contribution_status_id'] = $mappedStatus; + if ($mappedStatus === CRM_Square_Status::recurStatusId('Cancelled')) { + $updates['cancel_date'] = $canceledDate ? date('Y-m-d 00:00:00', strtotime($canceledDate)) : date('Y-m-d H:i:s'); + } } else { CRM_Core_Payment_SquareDebugLogger::log("Square: not applying Square status {$squareStatus} to contribution_recur {$recurId}; its payment-driven status {$currentStatus} is kept."); @@ -1265,10 +1497,7 @@ protected function applySubscriptionToRecur(array $recur, string $squareStatus, return; } - ContributionRecur::update(FALSE) - ->addWhere('id', '=', $recurId) - ->setValues($updates) - ->execute(); + $this->updateRecur($recurId, $updates); CRM_Core_Payment_SquareDebugLogger::log("Square sync: Updated recurring contribution {$recurId}: " . json_encode($updates)); } @@ -1293,15 +1522,15 @@ protected function applySubscriptionToRecur(array $recur, string $squareStatus, * @return bool */ protected function isRecurStatusChangeAllowed(int $currentStatusId, int $newStatusId): bool { - $pending = CRM_Square_Status::contributionStatusId('Pending'); + $pending = CRM_Square_Status::recurStatusId('Pending'); if ($newStatusId === $pending) { return FALSE; } - if ($newStatusId === CRM_Square_Status::contributionStatusId('In Progress')) { + if ($newStatusId === CRM_Square_Status::recurStatusId('In Progress')) { return !in_array($currentStatusId, [ $pending, - CRM_Square_Status::contributionStatusId('Cancelled'), - CRM_Square_Status::contributionStatusId('Completed'), + CRM_Square_Status::recurStatusId('Cancelled'), + CRM_Square_Status::recurStatusId('Completed'), ], TRUE); } return TRUE; @@ -1316,7 +1545,7 @@ protected function isRecurStatusChangeAllowed(int $currentStatusId, int $newStat */ protected function extractSubscriptionAmount(array $subscription) { if (!empty($subscription['price_override_money']['amount'])) { - return ((float) $subscription['price_override_money']['amount']) / 100; + return CRM_Square_Currency::fromMinorUnits($subscription['price_override_money']['amount'], $subscription['price_override_money']['currency'] ?? NULL); } // If no override, fall back to catalog plan pricing (unavailable via subscription API alone). @@ -1358,7 +1587,7 @@ public function handleInvoicePaymentCreated(array $payload) { return; } - $recur = $this->findRecurBySubscriptionId($subscriptionId); + $recur = $this->findOrLinkRecur($subscriptionId); if (!$recur) { $this->handleUnknownSubscription($subscriptionId, $invoice['updated_at'] ?? $invoice['created_at'] ?? NULL, "invoice {$invoiceId}"); return; @@ -1368,7 +1597,7 @@ public function handleInvoicePaymentCreated(array $payload) { } /** - * Sync a Square invoice.payment_failed webhook event. + * Sync a Square invoice.scheduled_charge_failed webhook event. * * @param array $invoice * Invoice object from the webhook payload. @@ -1379,16 +1608,27 @@ public function syncInvoicePaymentFailedFromSquare(array $invoice): void { $invoiceId = $invoice['id'] ?? NULL; $subscriptionId = $invoice['subscription_id'] ?? NULL; if (!$invoiceId || !$subscriptionId) { - CRM_Core_Payment_SquareDebugLogger::log('Square: invoice.payment_failed missing invoice ID or subscription_id, skipping.'); + CRM_Core_Payment_SquareDebugLogger::log('Square: invoice.scheduled_charge_failed missing invoice ID or subscription_id, skipping.'); return; } - $recur = $this->findRecurBySubscriptionId($subscriptionId); + $recur = $this->findOrLinkRecur($subscriptionId); if (!$recur) { $this->handleUnknownSubscription($subscriptionId, $invoice['updated_at'] ?? $invoice['created_at'] ?? NULL, "invoice {$invoiceId}"); return; } + // Square does not deliver webhooks in order, and retries a failed charge, + // so the invoice may have been paid since. A stale failure must not mark + // anything Failed — in particular not create a Failed duplicate of the + // first installment, whose (checkout) contribution carries CiviCRM's + // invoice ID rather than Square's. Square's current invoice decides. + $currentStatus = $this->getSquareInvoiceStatus($invoiceId); + if (in_array($currentStatus, self::PAID_INVOICE_STATUSES, TRUE)) { + CRM_Core_Payment_SquareDebugLogger::log("Square: ignoring invoice.scheduled_charge_failed for invoice {$invoiceId}; Square now reports it {$currentStatus}."); + return; + } + // The same lock as recordSubscriptionInstallment(): a failure and a // success for the series must not decide concurrently. $lock = $this->acquireSquareLock('recur.' . $recur['id']); @@ -1428,29 +1668,13 @@ public function syncInvoicePaymentFailedFromSquare(array $invoice): void { } /** - * Handle a subscription cancellation event coming from Square. + * Find the contact a Square payment made outside CiviCRM belongs to. * - * Triggered by webhook event: subscription.canceled. - * - * @param array $payload - * Full decoded JSON body from Square webhook. - */ - public function handleSubscriptionCancelled(array $payload) { - if (empty($payload['data']['object']['subscription']['id'])) { - CRM_Core_Payment_SquareDebugLogger::log('Square webhook: subscription.canceled missing subscription ID.'); - return; - } - - $this->syncSubscriptionCancellationFromSquare($payload['data']['object']['subscription']['id']); - } - - /** - * Find the contact ID associated with a Square payment. - * - * Attempts to resolve contact by: - * 1. Customer reference_id (if set in Square) - * 2. Email address from payment receipt - * 3. Contribution reference_id if payment is linked to existing contribution. + * By the payment's Square customer, if this processor has mapped it to a + * contact; otherwise by the receipt email, if exactly one contact has it + * as their primary email (family members often share one). Neither the + * customer's nor the payment's reference_id is trusted: other Square + * products and integrations set those to their own values. * * @param array $payment * Payment object from Square API. @@ -1459,55 +1683,22 @@ public function handleSubscriptionCancelled(array $payload) { * CiviCRM contact ID or NULL if not found. */ protected function findContactIdForPayment(array $payment) { - // 1. Try to find via customer reference_id $customerId = $payment['customer_id'] ?? NULL; if ($customerId) { - try { - $customerResponse = $this->gateway->client()->customers->get(new GetCustomersRequest(['customerId' => $customerId])); - $customer = $customerResponse->getCustomer(); - if (!empty($customer) && !empty($customer->getReferenceId())) { - $refId = $customer->getReferenceId(); - if (ctype_digit((string) $refId)) { - $contact = Contact::get(FALSE) - ->addWhere('id', '=', (int) $refId) - ->addSelect('id') - ->execute() - ->first(); - if (!empty($contact)) { - return (int) $contact['id']; - } - } - } - } - catch (\Throwable $e) { - CRM_Core_Payment_SquareDebugLogger::log('Square findContactIdForPayment(): customer lookup error: ' . $e->getMessage()); + $contactId = $this->findContactIdBySquareCustomer((string) $customerId); + if ($contactId) { + return $contactId; } } - // 2. Try via reference_id on payment (if it points to a contribution) - $referenceId = $payment['reference_id'] ?? NULL; - if ($referenceId && ctype_digit((string) $referenceId)) { - $contribution = Contribution::get(FALSE) - ->addWhere('id', '=', (int) $referenceId) - ->addWhere('is_test', 'IN', [TRUE, FALSE]) - ->addSelect('contact_id') - ->execute() - ->first(); - if (!empty($contribution)) { - return (int) $contribution['contact_id']; + $receiptEmail = trim((string) ($payment['buyer_email_address'] ?? '')); + if ($receiptEmail !== '') { + $contactIds = $this->findContactIdsByEmail($receiptEmail); + if (count($contactIds) === 1) { + return $contactIds[0]; } - } - - // 3. Try via receipt email (if available) - $receiptEmail = $payment['receipt_email'] ?? NULL; - if ($receiptEmail) { - $contact = Contact::get(FALSE) - ->addWhere('email', '=', $receiptEmail) - ->addSelect('id') - ->execute() - ->first(); - if (!empty($contact)) { - return (int) $contact['id']; + if (count($contactIds) > 1) { + CRM_Core_Payment_SquareDebugLogger::log('Square findContactIdForPayment(): ' . count($contactIds) . " contacts share the email of payment {$payment['id']}; not choosing one."); } } @@ -1515,39 +1706,44 @@ protected function findContactIdForPayment(array $payment) { } /** - * Sync a Square subscription cancellation into CiviCRM. - * - * Called when Square sends subscription.canceled or subscription.deleted webhook. + * The contact this processor has mapped a Square customer to. * - * @param string $squareSubscriptionId - * The subscription ID from Square. + * @param string $customerId * - * @throws \CRM_Core_Exception + * @return int|null */ - public function syncSubscriptionCancellationFromSquare($squareSubscriptionId) { - CRM_Core_Payment_SquareDebugLogger::log("Square syncSubscriptionCancellationFromSquare(): called from SquareIPN for subscription_id={$squareSubscriptionId}."); - if (empty($squareSubscriptionId)) { - CRM_Core_Payment_SquareDebugLogger::log('Square syncSubscriptionCancellationFromSquare(): missing subscription ID, skipping.'); - return; - } - - // Find the recurring contribution linked to this subscription. - $recur = $this->findRecurBySubscriptionId($squareSubscriptionId); - - if (empty($recur)) { - CRM_Core_Payment_SquareDebugLogger::log("Square syncSubscriptionCancellationFromSquare(): no recurring contribution found for subscription {$squareSubscriptionId}, skipping."); - return; - } - - $recurId = (int) $recur['id']; - CRM_Core_Payment_SquareDebugLogger::log("Square syncSubscriptionCancellationFromSquare(): found contribution_recur {$recurId} (current status {$recur['contribution_status_id']}) for subscription {$squareSubscriptionId}, marking Cancelled."); + protected function findContactIdBySquareCustomer(string $customerId): ?int { + $contactId = CRM_Core_DAO::singleValueQuery( + 'SELECT contact_id FROM square_customer_map WHERE square_customer_id = %1 AND payment_processor_id = %2', + [1 => [$customerId, 'String'], 2 => [$this->gateway->processorId(), 'Integer']] + ); + return $contactId ? (int) $contactId : NULL; + } - ContributionRecur::update(FALSE) - ->addWhere('id', '=', $recurId) - ->addValue('contribution_status_id', CRM_Square_Status::contributionStatusId('Cancelled')) - ->execute(); + /** + * Contacts (not deleted) whose primary email is the given one. + * + * @param string $email + * + * @return int[] + * At most two: enough to tell whether it is unique. + */ + protected function findContactIdsByEmail(string $email): array { + return array_map('intval', Contact::get(FALSE) + ->addSelect('id') + ->addWhere('email_primary.email', '=', $email) + ->setLimit(2) + ->execute() + ->column('id')); + } - CRM_Core_Payment_SquareDebugLogger::log("Square syncSubscriptionCancellationFromSquare(): Updated recurring contribution {$recurId} to Cancelled for subscription {$squareSubscriptionId}."); + /** + * Whether Square payments made outside CiviCRM are imported as contributions. + * + * @return bool + */ + protected function isImportingExternalPayments(): bool { + return (bool) Civi::settings()->get('square_import_external_payments'); } } diff --git a/CRM/Square/Status.php b/CRM/Square/Status.php index e498ee39..a4456a13 100644 --- a/CRM/Square/Status.php +++ b/CRM/Square/Status.php @@ -15,6 +15,18 @@ public static function contributionStatusId(string $name): int { return self::pseudoConstantId('contribution_status_id', $name); } + /** + * Resolve a recurring contribution's contribution_status_id by name. + * + * Recurring contributions use their own option group + * (contribution_recur_status), which has statuses — In Progress, Overdue, + * Processing, Failing — that contribution_status does not, and gives + * values 7 and 8 different meanings. + */ + public static function recurStatusId(string $name): int { + return self::pseudoConstantId('contribution_status_id', $name, 'CRM_Contribute_BAO_ContributionRecur'); + } + /** * Resolve a payment_instrument_id by name without relying on installation-specific IDs. */ @@ -30,14 +42,19 @@ public static function financialTypeId(string $name): int { } /** - * Resolve a Contribution-entity pseudoconstant value by name. + * Resolve a pseudoconstant value by name. * * Replaces the deprecated CRM_Contribute_PseudoConstant::contributionStatus() * (and avoids hard-coding installation-specific numeric IDs for statuses, * payment instruments, and financial types). + * + * @param string $field + * @param string $name + * @param string $baoName + * The entity whose field it is; Contribution unless given. */ - public static function pseudoConstantId(string $field, string $name): int { - $id = \CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', $field, $name); + public static function pseudoConstantId(string $field, string $name, string $baoName = 'CRM_Contribute_BAO_Contribution'): int { + $id = \CRM_Core_PseudoConstant::getKey($baoName, $field, $name); if ($id === FALSE || $id === NULL) { throw new \CRM_Core_Exception("CiviCRM {$field} '{$name}' is unavailable."); } @@ -45,7 +62,7 @@ public static function pseudoConstantId(string $field, string $name): int { } /** - * Map Square subscription statuses to CiviCRM contribution_status_id. + * Map Square subscription statuses to a recurring contribution's contribution_status_id. * * @param string $squareStatus * @@ -61,19 +78,19 @@ public static function mapSubscriptionStatus($squareStatus) { switch ($squareStatus) { case 'PENDING': case 'PAUSED': - return self::contributionStatusId('Pending'); + return self::recurStatusId('Pending'); case 'ACTIVE': - return self::contributionStatusId('In Progress'); + return self::recurStatusId('In Progress'); case 'COMPLETED': - return self::contributionStatusId('Completed'); + return self::recurStatusId('Completed'); case 'CANCELED': - return self::contributionStatusId('Cancelled'); + return self::recurStatusId('Cancelled'); case 'DEACTIVATED': - return self::contributionStatusId('Failed'); + return self::recurStatusId('Failed'); } // If unknown, don't change local status. diff --git a/CRM/Square/Subscriptions.php b/CRM/Square/Subscriptions.php index 7af13266..24e4fefb 100644 --- a/CRM/Square/Subscriptions.php +++ b/CRM/Square/Subscriptions.php @@ -42,7 +42,10 @@ public function __construct(CRM_Square_Gateway $gateway) { } /** - * Square-supported cadence definitions. + * Square-supported cadence definitions (Square's SubscriptionCadence). + * + * A CiviCRM frequency with no equivalent here (e.g. every 3 weeks) cannot + * be billed by Square, and is refused at checkout. */ protected const SQUARE_CADENCES = [ 'DAILY' => [ @@ -60,6 +63,21 @@ public function __construct(CRM_Square_Gateway $gateway) { 'unit' => 'week', 'step' => 2, ], + 'THIRTY_DAYS' => [ + 'label' => 'Every 30 Days', + 'unit' => 'day', + 'step' => 30, + ], + 'SIXTY_DAYS' => [ + 'label' => 'Every 60 Days', + 'unit' => 'day', + 'step' => 60, + ], + 'NINETY_DAYS' => [ + 'label' => 'Every 90 Days', + 'unit' => 'day', + 'step' => 90, + ], 'MONTHLY' => [ 'label' => 'Monthly', 'unit' => 'month', @@ -75,6 +93,11 @@ public function __construct(CRM_Square_Gateway $gateway) { 'unit' => 'month', 'step' => 3, ], + 'EVERY_FOUR_MONTHS' => [ + 'label' => 'Every 4 Months', + 'unit' => 'month', + 'step' => 4, + ], 'EVERY_SIX_MONTHS' => [ 'label' => 'Every 6 Months', 'unit' => 'month', @@ -85,6 +108,11 @@ public function __construct(CRM_Square_Gateway $gateway) { 'unit' => 'year', 'step' => 1, ], + 'EVERY_TWO_YEARS' => [ + 'label' => 'Every 2 Years', + 'unit' => 'year', + 'step' => 2, + ], ]; /** @@ -170,7 +198,7 @@ protected function getOrCreatePlanVariation( $currency ); CRM_Core_Payment_SquareDebugLogger::log("Creating label Square plan variation: {$label}"); - $amountCents = (int) round($amount * 100); + $amountMinorUnits = CRM_Square_Currency::toMinorUnits($amount, $currency); $phaseValues = [ 'ordinal' => 0, @@ -178,7 +206,7 @@ protected function getOrCreatePlanVariation( 'cadence' => strtoupper($cadence), 'pricing' => new SubscriptionPricing([ 'type' => 'STATIC', - 'priceMoney' => new Money(['amount' => $amountCents, 'currency' => $currency]), + 'priceMoney' => new Money(['amount' => $amountMinorUnits, 'currency' => $currency]), ]), ]; // Only finite subscriptions get a periods count — sending periods: 0 @@ -329,7 +357,10 @@ public function changeAmount(string $subscriptionId, float $amount, string $curr } $values = [ - 'priceOverrideMoney' => new Money(['amount' => (int) round($amount * 100), 'currency' => $currency]), + 'priceOverrideMoney' => new Money([ + 'amount' => CRM_Square_Currency::toMinorUnits($amount, $currency), + 'currency' => $currency, + ]), ]; if ($subscription->getVersion() !== NULL) { $values['version'] = $subscription->getVersion(); diff --git a/CRM/Square/Upgrader.php b/CRM/Square/Upgrader.php index 90086f90..70549ab3 100644 --- a/CRM/Square/Upgrader.php +++ b/CRM/Square/Upgrader.php @@ -59,6 +59,31 @@ public function upgrade_1001(): bool { return TRUE; } + /** + * Let a Square payment processor be deleted. + * + * The foreign key from square_customer_map to civicrm_payment_processor + * was ON DELETE RESTRICT, so deleting a processor that had mapped any + * customer failed. A processor's mappings mean nothing without it, so they + * now go with it. + */ + public function upgrade_1002(): bool { + _square_assert_php_version(); + $this->cascadeProcessorDeletes(); + return TRUE; + } + + /** + * Re-create the payment processor foreign key with ON DELETE CASCADE. + */ + protected function cascadeProcessorDeletes(): void { + CRM_Core_BAO_SchemaHandler::safeRemoveFK('square_customer_map', 'FK_square_customer_map_payment_processor_id'); + CRM_Core_DAO::executeQuery( + 'ALTER TABLE `square_customer_map` ADD CONSTRAINT `FK_square_customer_map_payment_processor_id` + FOREIGN KEY (`payment_processor_id`) REFERENCES `civicrm_payment_processor` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT' + ); + } + /** * Explain which customer mappings block upgrade_1001, and how to fix them. * @@ -160,7 +185,7 @@ protected function createSquareCustomerMapTable(bool $uniqueCustomer): void { CONSTRAINT `FK_square_customer_map_contact_id` FOREIGN KEY (`contact_id`) REFERENCES `civicrm_contact` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT, CONSTRAINT `FK_square_customer_map_payment_processor_id` FOREIGN KEY (`payment_processor_id`) - REFERENCES `civicrm_payment_processor` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT + REFERENCES `civicrm_payment_processor` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci SQL); } @@ -172,15 +197,15 @@ protected function createSquareCustomerMapTable(bool $uniqueCustomer): void { * whose value can unambiguously be attributed to a single Square payment * processor. * - * The legacy custom field never recorded which processor (live vs. - * sandbox, or which of several Square merchant accounts) a value came - * from. If exactly one Square processor is configured on this site, every - * legacy value can only ever have belonged to it — no inference is - * needed because there is nothing else it could be. If two or more - * Square processors are configured, a legacy value's owning processor is - * genuinely unknown; we do not guess (in particular, we never assume - * "live"). Those contacts are logged for manual reconciliation and their - * legacy custom-field data is left in place untouched. + * The legacy custom field never recorded which processor (or which of + * several Square merchant accounts) a value came from. Values are + * attributed to the live processor when exactly one live Square + * processor is configured: sandbox processors are not considered, since + * every configured processor has one. If two or more live Square + * processors are configured, a legacy value's owning processor is + * genuinely unknown and is not guessed. Those contacts are logged for + * manual reconciliation and their legacy custom-field data is left in + * place untouched. * * The square_data custom field group is only removed once every legacy * value has been migrated — i.e. once there is no ambiguous data left @@ -202,9 +227,13 @@ protected function backfillSquareCustomerMapFromCustomField(): void { $table = $field['custom_group_id.table_name']; $column = $field['column_name']; + // Live processors only (API4's default, made explicit): each configured + // processor also has a sandbox row, which would otherwise make every + // site look ambiguous. $squareProcessorIds = []; foreach (PaymentProcessor::get(FALSE) ->addWhere('payment_processor_type_id:name', '=', 'Square') + ->addWhere('is_test', '=', FALSE) ->addSelect('id') ->execute() as $processor) { $squareProcessorIds[] = (int) $processor['id']; diff --git a/README.md b/README.md index 06b4907a..7df655f5 100644 --- a/README.md +++ b/README.md @@ -23,13 +23,16 @@ just enable the extension as usual (**Administer → System Settings → Extensi - One-time card payments via Square Payments API (`/v2/payments`) - Recurring contributions via Square Subscriptions API (`/v2/subscriptions`) -- Refunds via Square Refunds API (`/v2/refunds`) -- Subscription cancellation and amount changes synced to Square +- Refunds via Square Refunds API (`/v2/refunds`), recorded in CiviCRM once Square completes them +- Subscription cancellation and amount changes synced to Square, and cancellations made in Square synced back to CiviCRM - Square Web Payments SDK for browser-side card tokenization — card details never pass through CiviCRM +- Card form ZIP/postal code kept in step with the billing address's, so Square never sees two different ones - Card-on-file support through CiviCRM PaymentToken -- Square customer creation and deduplication (by email and `reference_id`) +- Square customer creation and deduplication (by `reference_id`, then email — a customer already mapped to another contact, e.g. a family member sharing the email, is never shared) +- Buyer verification (Strong Customer Authentication) during card tokenization - Webhook event handling with deduplication and delivery logging - Supports sandbox (test) and production environments +- Currency-aware amounts: Square amounts are in each currency's smallest unit, so JPY (which has no cents) is never multiplied by 100 --- @@ -55,11 +58,18 @@ Separate sandbox credentials are supported for test mode. The processor automati | DAILY | Every day | | WEEKLY | Every week | | EVERY_TWO_WEEKS | Every 2 weeks | +| THIRTY_DAYS | Every 30 days | +| SIXTY_DAYS | Every 60 days | +| NINETY_DAYS | Every 90 days | | MONTHLY | Every month | | EVERY_TWO_MONTHS | Every 2 months | | QUARTERLY | Every 3 months | +| EVERY_FOUR_MONTHS | Every 4 months | | EVERY_SIX_MONTHS | Every 6 months | | ANNUAL | Every year | +| EVERY_TWO_YEARS | Every 2 years | + +A CiviCRM frequency with no Square equivalent (for example every 3 weeks) can't be billed by Square, and is refused at checkout before any card is saved. Recurring payments use the Square Catalog API to create subscription plans and plan variations on demand, then create a Square Subscription linked to a card-on-file. The subscription starts immediately and Square itself charges every installment, including the first — no separate charge is made at checkout. The checkout's contribution stays Pending until Square confirms that first charge by webhook, which then completes that same contribution; each later installment becomes a new contribution (via `Contribution.repeattransaction`) completed the same way. All payments are recorded with CiviCRM's `Payment.create`, and the Square payment ID becomes the contribution's and the payment's transaction ID. @@ -82,13 +92,12 @@ hours; any other failure is marked `error`. See | Event | Action | |---|---| | `subscription.created` | Syncs subscription status to `ContributionRecur` | -| `subscription.updated` | Syncs subscription status/amount to `ContributionRecur` | -| `subscription.canceled` | Marks `ContributionRecur` as Cancelled | +| `subscription.updated` | Syncs subscription status/amount to `ContributionRecur`. Square has no `subscription.canceled` event: a cancellation arrives here with a `canceled_date` (the status stays `ACTIVE` until that date), and marks the `ContributionRecur` Cancelled | | `invoice.created` | Nothing is recorded: the invoice is still a draft Square has not charged | | `invoice.payment_made` | Records the installment: completes the checkout's Pending contribution for the first invoice, or creates and completes the next contribution of the series | -| `invoice.payment_failed` | Marks that installment's contribution Failed (the first installment's stays Pending, since Square keeps the invoice open) | -| `payment.updated` | Completes a one-time contribution; for a subscription payment, looks up its invoice at Square and records the installment exactly as `invoice.payment_made` does | -| `refund.created`, `refund.updated` | Records a completed refund as a negative payment against the refunded payment | +| `invoice.scheduled_charge_failed` | Square could not charge the card on file: marks that installment's contribution Failed (the first installment's stays Pending, since Square keeps the invoice open). Ignored if Square reports the invoice paid by the time it is processed, since webhooks can arrive out of order | +| `payment.updated` | Completes a one-time contribution; for a subscription payment, looks up its invoice at Square and records the installment exactly as `invoice.payment_made` does. A payment taken outside CiviCRM (Square Dashboard, Square Online, point of sale) is ignored unless **Import Square payments made outside CiviCRM** is enabled in Square Settings — and even then only at the processor's own Square location | +| `refund.created`, `refund.updated` | Records a completed refund as a negative payment against the refunded payment, including a refund made from CiviCRM that was still `PENDING` at Square. A refund that arrives before its payment is recorded is retried | Webhook deduplication uses the `civicrm_paymentprocessor_webhook` queue (provided by the mjwshared extension) and Square's globally unique event ID. Do not log webhook signatures, access @@ -116,14 +125,19 @@ customer/card records: Earlier versions of this extension stored both as a `square_data` custom field group on the Contact entity. `CRM_Square_Upgrader::upgrade_1000()` migrates that legacy data into `square_customer_map` automatically **only** -when a contact's stored customer ID can be attributed to exactly one -configured Square processor. If more than one Square processor is -configured, the legacy field never recorded which one a given value -belongs to, so migration is skipped for that data (never guessed — live is -never assumed) and it's logged via `Civi::log()->warning()` for manual +when exactly one live Square processor is configured (sandbox processors are +not considered: every configured processor has one). If more than one live +Square processor is configured, the legacy field never recorded which one a +given value belongs to, so migration is skipped for that data (never +guessed) and it's logged via `Civi::log()->warning()` for manual reconciliation. The `square_data` group itself is only removed once nothing ambiguous remains. +When contacts are merged, the removed contact's mappings move to the +contact kept (`square_civicrm_merge()`); where both had a Square customer on +the same processor, the kept contact's is kept. Deleting a payment processor +deletes its mappings. + --- --- @@ -142,7 +156,9 @@ Key globals: - `CRM.vars.orgUschessSquare` — processor settings (Application ID, Location ID, sandbox flag) - `window.civicrmSquareHandleReload` — reinitializes the card element when the billing block is replaced via AJAX -The card element mounts into `#square-card-container`. Tokenization happens on form submit; the resulting nonce is written to a hidden `square_payment_token` field for PHP to read. +The card element mounts into `#square-card-container`. Tokenization happens on form submit; the resulting nonce is written to a hidden `square_payment_token` field for PHP to read. The billing details on the form (name, email, address), amount and currency are passed to `card.tokenize()` as Square's verification details, so Square performs buyer verification (Strong Customer Authentication) as part of tokenizing — with intent `CHARGE` for a one-time payment and `STORE` for a recurring one, whose card Square's subscription charges. + +The card form's ZIP/postal code and the billing address's (`billing_postal_code-N`) are kept in step: the card form starts with the billing postal code and is updated (via `card.configure()`) whenever the donor changes it, an empty billing postal code is filled in as the donor types one in the card form, and submit is stopped with an error if the two still differ. --- @@ -179,6 +195,7 @@ CRM/ Square.php Payment processor adapter (CiviCRM's CRM_Core_Payment contract) SquareIPN.php Webhook event router and queue processing SquareRetryableException.php Marks transient failures for webhook retry + SquareOutcomeUnknownException.php A checkout charge Square may have made without confirming it SquareDebugLogger.php Opt-in verbose debug logging, gated by the square_ipn_debug_logging setting Square/ Gateway.php Square API access (client, errors, idempotency keys) @@ -186,14 +203,15 @@ CRM/ Subscriptions.php Catalog plans/variations; subscription changes and cancellation Reconciler.php Webhook-driven sync into CiviCRM's ledger Status.php CiviCRM option values and Square status mappings - Form/Settings.php Administer > System Settings > Square Settings (debug logging toggle) + Currency.php Amounts in Square's smallest currency units + Form/Settings.php Administer > System Settings > Square Settings (debug logging, external payment import) Upgrader.php Creates/backfills/drops the square_customer_map table (see Database Tables) js/ square.js Browser-side Square Web Payments SDK integration managed/ PaymentProcessorType.mgd.php Registers the Square payment processor type settings/ - Square.setting.php Declares the square_ipn_debug_logging setting + Square.setting.php Declares the square_ipn_debug_logging and square_import_external_payments settings templates/ CRM/Core/Payment/Square/Card.tpl Card container HTML injected into billing block CRM/Square/Form/Settings.tpl Settings form markup diff --git a/civicrm_paymentprocessor_webhook.sql b/civicrm_paymentprocessor_webhook.sql deleted file mode 100644 index 2d011d22..00000000 --- a/civicrm_paymentprocessor_webhook.sql +++ /dev/null @@ -1,94 +0,0 @@ --- phpMyAdmin SQL Dump --- version 5.1.1deb5ubuntu1 --- https://www.phpmyadmin.net/ --- --- Host: localhost:3306 --- Generation Time: Sep 24, 2026 at 01:38 PM --- Server version: 8.0.46-0ubuntu0.22.04.4 --- PHP Version: 8.3.33 - -SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; -START TRANSACTION; -SET time_zone = "+00:00"; - - -/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; -/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; -/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; -/*!40101 SET NAMES utf8mb4 */; - --- --- Database: `skvare8_uscf_civicrm` --- - --- -------------------------------------------------------- - --- --- Table structure for table `civicrm_paymentprocessor_webhook` --- - -CREATE TABLE `civicrm_paymentprocessor_webhook` ( - `id` int UNSIGNED NOT NULL COMMENT 'Unique PaymentprocessorWebhook ID', - `payment_processor_id` int UNSIGNED DEFAULT NULL COMMENT 'Payment Processor for this webhook', - `event_id` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT 'Webhook event ID', - `trigger` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT 'Webhook trigger event type', - `created_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'When the webhook was first received by the IPN code', - `processed_date` timestamp NULL DEFAULT NULL COMMENT 'Has this webhook been processed yet?', - `status` varchar(32) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'new' COMMENT 'Processing status', - `identifier` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT 'Optional key to group webhooks, as needed by some processors.', - `message` varchar(1024) COLLATE utf8mb4_unicode_ci DEFAULT '' COMMENT 'Stores data sent that is needed for processing. JSON suggested.', - `data` text COLLATE utf8mb4_unicode_ci COMMENT 'Stores data sent that is needed for processing. JSON suggested.' -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC; - --- --- Dumping data for table `civicrm_paymentprocessor_webhook` --- - -INSERT INTO `civicrm_paymentprocessor_webhook` (`id`, `payment_processor_id`, `event_id`, `trigger`, `created_date`, `processed_date`, `status`, `identifier`, `message`, `data`) VALUES -(345, 7, 'b87940d8-9c50-369a-83c1-a1af532cde1d', 'payment.updated', '2026-09-24 16:47:00', NULL, 'new', 'n1xYKpEvBD0QyjdHt4l7WW7sgBgZY::', '', '{\"merchant_id\":\"ML0SVZ2P7HY7C\",\"type\":\"payment.updated\",\"event_id\":\"b87940d8-9c50-369a-83c1-a1af532cde1d\",\"created_at\":\"2026-09-24T16:46:58.22Z\",\"data\":{\"type\":\"payment\",\"id\":\"n1xYKpEvBD0QyjdHt4l7WW7sgBgZY\",\"object\":{\"payment\":{\"amount_money\":{\"amount\":1900,\"currency\":\"USD\"},\"application_details\":{\"application_id\":\"sandbox-sq0idb-iKaL0GY_L13b75J0K2qgsw\",\"square_product\":\"OTHER\"},\"approved_money\":{\"amount\":1900,\"currency\":\"USD\"},\"buyer_email_address\":\"sunil@skvare.com\",\"card_details\":{\"avs_status\":\"AVS_ACCEPTED\",\"card\":{\"bin\":\"411111\",\"card_brand\":\"VISA\",\"card_type\":\"CREDIT\",\"exp_month\":11,\"exp_year\":2029,\"fingerprint\":\"sq-1-G1aFRs4kqyICoIiVJ4z9SzaSHv8Xb1i5cgI_bwCvbiSxFWTtBvC-hDBQLERLbKwQaA\",\"last_4\":\"1111\",\"prepaid_type\":\"NOT_PREPAID\"},\"card_payment_timeline\":{\"authorized_at\":\"2026-09-24T16:45:53.894Z\",\"captured_at\":\"2026-09-24T16:45:54.049Z\"},\"cvv_status\":\"CVV_NOT_CHECKED\",\"entry_method\":\"ON_FILE\",\"statement_description\":\"SQ *DEFAULT TEST ACCOUNT\",\"status\":\"CAPTURED\"},\"created_at\":\"2026-09-24T16:45:53.762Z\",\"customer_id\":\"PAGRJWQKJH1E11PCR7KG7SKTY8\",\"delay_action\":\"CANCEL\",\"delay_duration\":\"PT168H\",\"delayed_until\":\"2026-10-01T16:45:53.762Z\",\"id\":\"n1xYKpEvBD0QyjdHt4l7WW7sgBgZY\",\"location_id\":\"L6Z22RREK6NGN\",\"order_id\":\"X4awkGmhfaQe3C7Z4g4o0esoje4F\",\"processing_fee\":[{\"amount_money\":{\"amount\":93,\"currency\":\"USD\"},\"effective_at\":\"2026-09-24T18:45:55.000Z\",\"type\":\"INITIAL\"}],\"receipt_number\":\"n1xY\",\"receipt_url\":\"https://squareupsandbox.com/receipt/preview/n1xYKpEvBD0QyjdHt4l7WW7sgBgZY\",\"risk_evaluation\":{\"created_at\":\"2026-09-24T16:45:53.894Z\",\"risk_level\":\"NORMAL\"},\"source_type\":\"CARD\",\"status\":\"COMPLETED\",\"total_money\":{\"amount\":1900,\"currency\":\"USD\"},\"updated_at\":\"2026-09-24T16:45:55.235Z\",\"version\":3}}}}'), -(344, 7, 'fcc73174-d6ec-3c84-b9dd-b6c45a386587', 'payment.updated', '2026-09-24 16:45:57', NULL, 'new', 'n1xYKpEvBD0QyjdHt4l7WW7sgBgZY::', '', '{\"merchant_id\":\"ML0SVZ2P7HY7C\",\"type\":\"payment.updated\",\"event_id\":\"fcc73174-d6ec-3c84-b9dd-b6c45a386587\",\"created_at\":\"2026-09-24T16:45:55.244Z\",\"data\":{\"type\":\"payment\",\"id\":\"n1xYKpEvBD0QyjdHt4l7WW7sgBgZY\",\"object\":{\"payment\":{\"amount_money\":{\"amount\":1900,\"currency\":\"USD\"},\"application_details\":{\"application_id\":\"sandbox-sq0idb-iKaL0GY_L13b75J0K2qgsw\",\"square_product\":\"OTHER\"},\"approved_money\":{\"amount\":1900,\"currency\":\"USD\"},\"buyer_email_address\":\"sunil@skvare.com\",\"card_details\":{\"avs_status\":\"AVS_ACCEPTED\",\"card\":{\"bin\":\"411111\",\"card_brand\":\"VISA\",\"card_type\":\"CREDIT\",\"exp_month\":11,\"exp_year\":2029,\"fingerprint\":\"sq-1-G1aFRs4kqyICoIiVJ4z9SzaSHv8Xb1i5cgI_bwCvbiSxFWTtBvC-hDBQLERLbKwQaA\",\"last_4\":\"1111\",\"prepaid_type\":\"NOT_PREPAID\"},\"card_payment_timeline\":{\"authorized_at\":\"2026-09-24T16:45:53.894Z\",\"captured_at\":\"2026-09-24T16:45:54.049Z\"},\"cvv_status\":\"CVV_NOT_CHECKED\",\"entry_method\":\"ON_FILE\",\"statement_description\":\"SQ *DEFAULT TEST ACCOUNT\",\"status\":\"CAPTURED\"},\"created_at\":\"2026-09-24T16:45:53.762Z\",\"customer_id\":\"PAGRJWQKJH1E11PCR7KG7SKTY8\",\"delay_action\":\"CANCEL\",\"delay_duration\":\"PT168H\",\"delayed_until\":\"2026-10-01T16:45:53.762Z\",\"id\":\"n1xYKpEvBD0QyjdHt4l7WW7sgBgZY\",\"location_id\":\"L6Z22RREK6NGN\",\"order_id\":\"X4awkGmhfaQe3C7Z4g4o0esoje4F\",\"receipt_number\":\"n1xY\",\"receipt_url\":\"https://squareupsandbox.com/receipt/preview/n1xYKpEvBD0QyjdHt4l7WW7sgBgZY\",\"risk_evaluation\":{\"created_at\":\"2026-09-24T16:45:53.894Z\",\"risk_level\":\"NORMAL\"},\"source_type\":\"CARD\",\"status\":\"COMPLETED\",\"total_money\":{\"amount\":1900,\"currency\":\"USD\"},\"updated_at\":\"2026-09-24T16:45:55.235Z\",\"version\":2}}}}'), -(343, 7, '2422886a-dc5f-5d47-b655-6d5332af1a2c', 'invoice.created', '2026-09-24 16:45:57', NULL, 'new', ':inv:0-ChAIcc-Uqf-MREOs4fwUEwthEIgK:4e6e5d41-a071-4e47-be68-087138ea360a', '', '{\"merchant_id\":\"ML0SVZ2P7HY7C\",\"location_id\":\"L6Z22RREK6NGN\",\"type\":\"invoice.created\",\"event_id\":\"2422886a-dc5f-5d47-b655-6d5332af1a2c\",\"created_at\":\"2026-09-24T16:45:53Z\",\"data\":{\"type\":\"invoice\",\"id\":\"inv:0-ChAIcc-Uqf-MREOs4fwUEwthEIgK\",\"object\":{\"invoice\":{\"accepted_payment_methods\":{\"bank_account\":false,\"buy_now_pay_later\":false,\"card\":true,\"cash_app_pay\":true,\"square_gift_card\":false},\"created_at\":\"2026-09-24T16:45:53Z\",\"delivery_method\":\"EMAIL\",\"id\":\"inv:0-ChAIcc-Uqf-MREOs4fwUEwthEIgK\",\"invoice_number\":\"000066\",\"location_id\":\"L6Z22RREK6NGN\",\"order_id\":\"X4awkGmhfaQe3C7Z4g4o0esoje4F\",\"payment_requests\":[{\"automatic_payment_source\":\"CARD_ON_FILE\",\"card_id\":\"ccof:CA4SEOLiJDT03Hr7z4ss8kEY4GwoAg\",\"computed_amount_money\":{\"amount\":1900,\"currency\":\"USD\"},\"due_date\":\"2026-09-24\",\"request_type\":\"BALANCE\",\"tipping_enabled\":false,\"total_completed_amount_money\":{\"amount\":0,\"currency\":\"USD\"},\"uid\":\"d8fcc799-eabf-42b0-b60f-e37a33ca9013\"}],\"primary_recipient\":{\"customer_id\":\"PAGRJWQKJH1E11PCR7KG7SKTY8\",\"email_address\":\"sunil@skvare.com\",\"family_name\":\"Pawar-1\",\"given_name\":\"Sunil-1\"},\"status\":\"DRAFT\",\"store_payment_method_enabled\":true,\"subscription_id\":\"4e6e5d41-a071-4e47-be68-087138ea360a\",\"timezone\":\"UTC\",\"title\":\"DAILY 19.00 USD Subscription\",\"updated_at\":\"2026-09-24T16:45:53Z\",\"version\":0}}}}'), -(340, 7, '34c65ab4-8a74-3652-acc3-be35708d94ce', 'payment.updated', '2026-09-23 16:47:03', NULL, 'new', 'VM5iP66yfHWI3UEIJWmbEAEzrrBZY::', '', '{\"merchant_id\":\"ML0SVZ2P7HY7C\",\"type\":\"payment.updated\",\"event_id\":\"34c65ab4-8a74-3652-acc3-be35708d94ce\",\"created_at\":\"2026-09-23T16:47:00.942Z\",\"data\":{\"type\":\"payment\",\"id\":\"VM5iP66yfHWI3UEIJWmbEAEzrrBZY\",\"object\":{\"payment\":{\"amount_money\":{\"amount\":1900,\"currency\":\"USD\"},\"application_details\":{\"application_id\":\"sandbox-sq0idb-iKaL0GY_L13b75J0K2qgsw\",\"square_product\":\"OTHER\"},\"approved_money\":{\"amount\":1900,\"currency\":\"USD\"},\"buyer_email_address\":\"sunil@skvare.com\",\"card_details\":{\"avs_status\":\"AVS_ACCEPTED\",\"card\":{\"bin\":\"411111\",\"card_brand\":\"VISA\",\"card_type\":\"CREDIT\",\"exp_month\":11,\"exp_year\":2029,\"fingerprint\":\"sq-1-G1aFRs4kqyICoIiVJ4z9SzaSHv8Xb1i5cgI_bwCvbiSxFWTtBvC-hDBQLERLbKwQaA\",\"last_4\":\"1111\",\"prepaid_type\":\"NOT_PREPAID\"},\"card_payment_timeline\":{\"authorized_at\":\"2026-09-23T16:45:56.915Z\",\"captured_at\":\"2026-09-23T16:45:57.027Z\"},\"cvv_status\":\"CVV_NOT_CHECKED\",\"entry_method\":\"ON_FILE\",\"statement_description\":\"SQ *DEFAULT TEST ACCOUNT\",\"status\":\"CAPTURED\"},\"created_at\":\"2026-09-23T16:45:56.784Z\",\"customer_id\":\"PAGRJWQKJH1E11PCR7KG7SKTY8\",\"delay_action\":\"CANCEL\",\"delay_duration\":\"PT168H\",\"delayed_until\":\"2026-09-30T16:45:56.784Z\",\"id\":\"VM5iP66yfHWI3UEIJWmbEAEzrrBZY\",\"location_id\":\"L6Z22RREK6NGN\",\"order_id\":\"thVIfFwfL8yeD6fM94dvotSh2c4F\",\"processing_fee\":[{\"amount_money\":{\"amount\":93,\"currency\":\"USD\"},\"effective_at\":\"2026-09-23T18:45:58.000Z\",\"type\":\"INITIAL\"}],\"receipt_number\":\"VM5i\",\"receipt_url\":\"https://squareupsandbox.com/receipt/preview/VM5iP66yfHWI3UEIJWmbEAEzrrBZY\",\"risk_evaluation\":{\"created_at\":\"2026-09-23T16:45:56.915Z\",\"risk_level\":\"NORMAL\"},\"source_type\":\"CARD\",\"status\":\"COMPLETED\",\"total_money\":{\"amount\":1900,\"currency\":\"USD\"},\"updated_at\":\"2026-09-23T16:45:58.357Z\",\"version\":3}}}}'), -(339, 7, 'e1fc9a1e-ae5f-3f8a-a079-5eb8c48c096c', 'payment.updated', '2026-09-23 16:46:00', NULL, 'new', 'VM5iP66yfHWI3UEIJWmbEAEzrrBZY::', '', '{\"merchant_id\":\"ML0SVZ2P7HY7C\",\"type\":\"payment.updated\",\"event_id\":\"e1fc9a1e-ae5f-3f8a-a079-5eb8c48c096c\",\"created_at\":\"2026-09-23T16:45:58.364Z\",\"data\":{\"type\":\"payment\",\"id\":\"VM5iP66yfHWI3UEIJWmbEAEzrrBZY\",\"object\":{\"payment\":{\"amount_money\":{\"amount\":1900,\"currency\":\"USD\"},\"application_details\":{\"application_id\":\"sandbox-sq0idb-iKaL0GY_L13b75J0K2qgsw\",\"square_product\":\"OTHER\"},\"approved_money\":{\"amount\":1900,\"currency\":\"USD\"},\"buyer_email_address\":\"sunil@skvare.com\",\"card_details\":{\"avs_status\":\"AVS_ACCEPTED\",\"card\":{\"bin\":\"411111\",\"card_brand\":\"VISA\",\"card_type\":\"CREDIT\",\"exp_month\":11,\"exp_year\":2029,\"fingerprint\":\"sq-1-G1aFRs4kqyICoIiVJ4z9SzaSHv8Xb1i5cgI_bwCvbiSxFWTtBvC-hDBQLERLbKwQaA\",\"last_4\":\"1111\",\"prepaid_type\":\"NOT_PREPAID\"},\"card_payment_timeline\":{\"authorized_at\":\"2026-09-23T16:45:56.915Z\",\"captured_at\":\"2026-09-23T16:45:57.027Z\"},\"cvv_status\":\"CVV_NOT_CHECKED\",\"entry_method\":\"ON_FILE\",\"statement_description\":\"SQ *DEFAULT TEST ACCOUNT\",\"status\":\"CAPTURED\"},\"created_at\":\"2026-09-23T16:45:56.784Z\",\"customer_id\":\"PAGRJWQKJH1E11PCR7KG7SKTY8\",\"delay_action\":\"CANCEL\",\"delay_duration\":\"PT168H\",\"delayed_until\":\"2026-09-30T16:45:56.784Z\",\"id\":\"VM5iP66yfHWI3UEIJWmbEAEzrrBZY\",\"location_id\":\"L6Z22RREK6NGN\",\"order_id\":\"thVIfFwfL8yeD6fM94dvotSh2c4F\",\"receipt_number\":\"VM5i\",\"receipt_url\":\"https://squareupsandbox.com/receipt/preview/VM5iP66yfHWI3UEIJWmbEAEzrrBZY\",\"risk_evaluation\":{\"created_at\":\"2026-09-23T16:45:56.915Z\",\"risk_level\":\"NORMAL\"},\"source_type\":\"CARD\",\"status\":\"COMPLETED\",\"total_money\":{\"amount\":1900,\"currency\":\"USD\"},\"updated_at\":\"2026-09-23T16:45:58.357Z\",\"version\":2}}}}'), -(338, 7, '0314d55c-fc55-5767-b7f3-3c6d4ba74ebb', 'invoice.created', '2026-09-23 16:45:58', NULL, 'new', ':inv:0-ChAsOc2tUbZgeioE6TokE6ODEIgK:4e6e5d41-a071-4e47-be68-087138ea360a', '', '{\"merchant_id\":\"ML0SVZ2P7HY7C\",\"location_id\":\"L6Z22RREK6NGN\",\"type\":\"invoice.created\",\"event_id\":\"0314d55c-fc55-5767-b7f3-3c6d4ba74ebb\",\"created_at\":\"2026-09-23T16:45:56Z\",\"data\":{\"type\":\"invoice\",\"id\":\"inv:0-ChAsOc2tUbZgeioE6TokE6ODEIgK\",\"object\":{\"invoice\":{\"accepted_payment_methods\":{\"bank_account\":false,\"buy_now_pay_later\":false,\"card\":true,\"cash_app_pay\":true,\"square_gift_card\":false},\"created_at\":\"2026-09-23T16:45:56Z\",\"delivery_method\":\"EMAIL\",\"id\":\"inv:0-ChAsOc2tUbZgeioE6TokE6ODEIgK\",\"invoice_number\":\"000065\",\"location_id\":\"L6Z22RREK6NGN\",\"order_id\":\"thVIfFwfL8yeD6fM94dvotSh2c4F\",\"payment_requests\":[{\"automatic_payment_source\":\"CARD_ON_FILE\",\"card_id\":\"ccof:CA4SEOLiJDT03Hr7z4ss8kEY4GwoAg\",\"computed_amount_money\":{\"amount\":1900,\"currency\":\"USD\"},\"due_date\":\"2026-09-23\",\"request_type\":\"BALANCE\",\"tipping_enabled\":false,\"total_completed_amount_money\":{\"amount\":0,\"currency\":\"USD\"},\"uid\":\"2fe49e37-008f-45d1-a8ef-171f91331aeb\"}],\"primary_recipient\":{\"customer_id\":\"PAGRJWQKJH1E11PCR7KG7SKTY8\",\"email_address\":\"sunil@skvare.com\",\"family_name\":\"Pawar-1\",\"given_name\":\"Sunil-1\"},\"status\":\"DRAFT\",\"store_payment_method_enabled\":true,\"subscription_id\":\"4e6e5d41-a071-4e47-be68-087138ea360a\",\"timezone\":\"UTC\",\"title\":\"DAILY 19.00 USD Subscription\",\"updated_at\":\"2026-09-23T16:45:56Z\",\"version\":0}}}}'); - --- --- Indexes for dumped tables --- - --- --- Indexes for table `civicrm_paymentprocessor_webhook` --- -ALTER TABLE `civicrm_paymentprocessor_webhook` - ADD PRIMARY KEY (`id`), - ADD KEY `index_event_id` (`event_id`), - ADD KEY `index_created_date` (`created_date`), - ADD KEY `index_processed_date` (`processed_date`), - ADD KEY `index_status_processed_date` (`status`,`processed_date`), - ADD KEY `index_identifier` (`identifier`), - ADD KEY `FK_civicrm_paymentprocessor_webhook_111edf57e5277dbe` (`payment_processor_id`); - --- --- AUTO_INCREMENT for dumped tables --- - --- --- AUTO_INCREMENT for table `civicrm_paymentprocessor_webhook` --- -ALTER TABLE `civicrm_paymentprocessor_webhook` - MODIFY `id` int UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'Unique PaymentprocessorWebhook ID', AUTO_INCREMENT=346; - --- --- Constraints for dumped tables --- - --- --- Constraints for table `civicrm_paymentprocessor_webhook` --- -ALTER TABLE `civicrm_paymentprocessor_webhook` - ADD CONSTRAINT `FK_civicrm_paymentprocessor_webhook_111edf57e5277dbe` FOREIGN KEY (`payment_processor_id`) REFERENCES `civicrm_payment_processor` (`id`) ON DELETE SET NULL; -COMMIT; - -/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; -/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; -/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; diff --git a/composer.json b/composer.json index a308ec42..0f920c21 100644 --- a/composer.json +++ b/composer.json @@ -8,11 +8,6 @@ "type": "payment" } }, - "autoload": { - "psr-4": { - "CRM\\": "CRM/" - } - }, "license": "AGPL-3.0-or-later", "config": { "platform": { @@ -33,11 +28,6 @@ "issues": "https://github.com/Skvare/org.uschess.square/issues", "source": "https://github.com/Skvare/org.uschess.square" }, - "autoload-dev": { - "psr-4": { - "CRM\\Tests\\": "tests/" - } - }, "require": { "php": ">=8.2", "square/square": "^43.2" diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index e6bf35a2..76d22977 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -10,20 +10,48 @@ | `CRM/Square/Subscriptions.php` | Catalog subscription plans and plan variations (cached per processor), and changes to or cancellation of subscriptions. | | `CRM/Square/Reconciler.php` | Webhook-driven sync into CiviCRM: payments, subscription installments, refunds, and recurring status. Its protected find/record methods are its only CiviCRM data access. | | `CRM/Square/Status.php` | CiviCRM option values by name, and Square-to-CiviCRM status mappings. | +| `CRM/Square/Currency.php` | Conversion between CiviCRM amounts and Square's smallest currency units (cents for USD, whole yen for JPY). | | `CRM/Core/Payment/SquareIPN.php` | Webhook filtering, deduplication, queue persistence, and processing. | | `CRM/Core/Payment/SquareDebugLogger.php` | Opt-in diagnostic logging. | | `CRM/Square/Upgrader.php` | Schema creation, migration, and cleanup. | -| `js/square.js` | Browser card element and tokenization. | +| `js/square.js` | Browser card element and tokenization; keeps the card form's postal code in step with the billing address's. | | `managed/PaymentProcessorType.mgd.php` | Payment processor type registration. | ## Payment flow 1. The processor injects Square SDK configuration and the card container into CiviCRM's billing block. -2. The browser tokenizes card data and adds the payment token to the form. +2. The browser checks that the card form's postal code matches the billing + address's, tokenizes card data, with the buyer's details for Square's + buyer verification, and adds the payment token to the form. (Square's + CreateCard rejects a card whose billing address postal code differs from + the card form's, with "Invalid card data.") 3. The processor sends the token to Square for payment or card-on-file work. 4. The processor returns transaction and status data to CiviCRM. +Failures are reported as CiviCRM's checkout expects: + +- When nothing was charged — a decline, a request Square rejected, or a + failure before the charge — `doPayment()` throws + `PaymentProcessorException`, and the checkout marks the contribution Failed + and deletes the recurring contribution. +- When Square may have charged the card without confirming it (a server + error or timeout after the SDK's retries, an unreadable response), it + throws `CRM_Core_Payment_SquareOutcomeUnknownException` and logs an error to + check in the Square Dashboard. A contribution page keeps its Pending + contribution, for the `payment.updated` webhook to complete if the charge + went through. Event registration only handles `PaymentProcessorException`, + so there it is converted to one. For a recurring checkout, the recurring + contribution is linked to its subscription later, from the subscription's + webhooks (see [WEBHOOKS.md](WEBHOOKS.md#recurring-installments)). + +Refunds made from CiviCRM (`doRefund()`) are recorded only once Square has +completed them. Square accepts a card refund as `PENDING` until it has the +funds; `doRefund()` checks on it for a few seconds, and a refund still +`PENDING` then is reported to staff as not yet recorded, and is recorded by +the `refund.updated` webhook when Square completes it. A refund Square +rejects or fails is never recorded. + Raw card details do not pass through CiviCRM. Recurring contributions create or reuse Square Catalog plans and variations, then link the Square subscription to the CiviCRM recurring contribution. diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index cfb4a9e9..65a4dbdc 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -25,10 +25,50 @@ GitHub Actions (`.github/workflows/ci.yml`) runs the linter, Composer validation and PHPUnit on PHP 8.2, 8.3 and 8.4, and PHPCS and PHPStan against CiviCRM 6.16.5. -Not yet covered: tests against a real CiviCRM database (e.g. `cv` and -`Civi\Test` headless tests on a buildkit site) and browser tests of the -card form. The in-memory fakes stand in for, but do not prove, CiviCRM's own -behaviour. +The in-memory fakes stand in for, but do not prove, CiviCRM's own +behaviour — the stand-ins in `tests/phpunit/bootstrap.php` once let a +lookup of 'In Progress' in the wrong option group pass. So keep their +option values identical to a fresh CiviCRM 6.16 install, and cover CiviCRM +API behaviour in the headless suite. + +## Headless tests + +`tests/phpunit-headless/` runs against a real CiviCRM through `cv` and +`Civi\Test::headless()`: status lookups, Contact email lookups, +Payment.create, Contribution.repeattransaction and refunds, the contact +merge hook, and processor deletion. Square is still mocked at the SDK +client. + +**Only run it on a civibuild (buildkit) site** whose `CIVICRM_UF=UnitTests` +configuration points at a dedicated test database: `Civi\Test::headless()` +drops every table in the database it is given. The mjwshared extension must +be present on the site. + +```bash +cd /path/to/buildkit/site +CIVICRM_UF=UnitTests /path/to/org.uschess.square/vendor/bin/phpunit \ + --configuration /path/to/org.uschess.square/tests/phpunit-headless/phpunit.xml.dist +``` + +Not yet covered: automated tests of `js/square.js` and browser tests of the +card form (including keeping its ZIP/postal code in step with the billing +address's). + +## Release build + +The committed `vendor/` includes the development tools (PHPUnit, PHPCS) +that CI uses. A release must not ship them under the web root. Build the +release from a clean export with only the runtime dependencies: + +```bash +mkdir -p /tmp/release +git archive --format=tar --prefix=org.uschess.square/ HEAD | tar -x -C /tmp/release +cd /tmp/release/org.uschess.square +composer install --no-dev --optimize-autoloader +rm -rf tests .github phpcs.xml.dist phpstan.neon.dist phpstan-baseline.neon +``` + +## Code style The extension uses CiviCRM's two-space, Drupal-derived style. `.editorconfig` defines editor whitespace rules, and `phpcs.xml.dist` is the authoritative lint diff --git a/docs/OVERVIEW.html b/docs/OVERVIEW.html index 3c647ffe..87c028e7 100644 --- a/docs/OVERVIEW.html +++ b/docs/OVERVIEW.html @@ -422,11 +422,11 @@
Card charges through Square's Payments API for contributions, event fees, and donations.
Square Subscriptions API drives renewals; eight cadences from daily to annual.
Square Subscriptions API drives renewals; thirteen cadences from daily to every two years.
Full and partial refunds issued through Square's Refunds API from the CiviCRM contribution.
Cancellations made in CiviCRM sync forward to the live Square subscription.
Cancellations and amount changes made in CiviCRM sync forward to the live Square subscription; a cancellation made in Square marks the recurring contribution Cancelled.
Cards save as standard CiviCRM PaymentToken records — one contact can hold several across processors.
Square customers are matched and reused by email and reference ID instead of duplicating on every charge.
Square customers are matched and reused by reference ID and email instead of duplicating on every charge — but never shared between contacts, such as family members with one email address.
Every Square event is signature-verified, deduplicated, queued, and logged before it touches a record.
Fully separate credentials and data per environment, switchable per processor instance.
square_customer_map, migrates legacy data, drops the table on uninstall.