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 @@

Two loops: charge now, reconcile later

What it handles

One-time payments

Card charges through Square's Payments API for contributions, event fees, and donations.

-

Recurring contributions

Square Subscriptions API drives renewals; eight cadences from daily to annual.

+

Recurring contributions

Square Subscriptions API drives renewals; thirteen cadences from daily to every two years.

Refunds

Full and partial refunds issued through Square's Refunds API from the CiviCRM contribution.

-

Subscription changes

Cancellations made in CiviCRM sync forward to the live Square subscription.

+

Subscription changes

Cancellations and amount changes made in CiviCRM sync forward to the live Square subscription; a cancellation made in Square marks the recurring contribution Cancelled.

Card-on-file

Cards save as standard CiviCRM PaymentToken records — one contact can hold several across processors.

-

Customer deduplication

Square customers are matched and reused by email and reference ID instead of duplicating on every charge.

+

Customer deduplication

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.

Webhook reconciliation

Every Square event is signature-verified, deduplicated, queued, and logged before it touches a record.

Sandbox & production

Fully separate credentials and data per environment, switchable per processor instance.

@@ -444,7 +444,7 @@

Components

CRM/Core/Payment/SquareIPN.phpWebhook filtering, signature verification, deduplication, queue persistence, processing. CRM/Core/Payment/SquareDebugLogger.phpOpt-in diagnostic logging, gated by a setting so it's off by default. CRM/Square/Upgrader.phpCreates square_customer_map, migrates legacy data, drops the table on uninstall. - js/square.jsMounts the Square card element and tokenizes on submit, across native and Webform forms. + js/square.jsMounts the Square card element and tokenizes on submit, across native and Webform forms; keeps the card form's ZIP in step with the billing address's. managed/PaymentProcessorType.mgd.phpRegisters "Square" as a selectable payment processor type. @@ -499,13 +499,12 @@

What Square tells CiviCRM, and when

EventAction subscription.createdSyncs subscription status to ContributionRecur - subscription.updatedSyncs subscription status/amount to ContributionRecur - subscription.canceledMarks ContributionRecur as Cancelled - invoice.createdCreates a Pending contribution for the upcoming invoice - invoice.payment_madeReconciles the paid invoice - invoice.payment_failedReconciles the failed invoice - payment.updatedReconciles an existing contribution - refund.createdReconciles a refund + subscription.updatedSyncs subscription status/amount to ContributionRecur; a cancellation arrives here with a canceled_date (the status stays ACTIVE until then) and marks it Cancelled + invoice.createdNothing is recorded: the invoice is still a draft Square has not charged + invoice.payment_madeRecords the paid installment + invoice.scheduled_charge_failedMarks the failed installment's contribution Failed + payment.updatedCompletes a one-time contribution, or records a subscription installment; payments taken outside CiviCRM are ignored unless importing them is enabled in Square Settings + refund.created, refund.updatedRecords a completed refund as a negative payment diff --git a/docs/WEBHOOKS.md b/docs/WEBHOOKS.md index 3b811afc..5041ea83 100644 --- a/docs/WEBHOOKS.md +++ b/docs/WEBHOOKS.md @@ -11,9 +11,17 @@ https://your-site.example/civicrm/payment/ipn/{processor_id} Replace `{processor_id}` with the CiviCRM payment processor ID. Use the Square application and signature key for the same sandbox or production environment. Subscribe to: `subscription.created`, `subscription.updated`, -`subscription.canceled`, `invoice.created`, `invoice.payment_made`, -`invoice.payment_failed`, `payment.updated`, `refund.created`, and -`refund.updated`. +`invoice.created`, `invoice.payment_made`, `invoice.scheduled_charge_failed`, +`payment.updated`, `refund.created`, and `refund.updated`. + +Square has no `subscription.canceled` or `invoice.payment_failed` event, +although earlier versions of this extension listed them. A cancellation +arrives as `subscription.updated` with a `canceled_date` (the end of the +period already paid for; the status stays `ACTIVE` until then, and Square may +send no further webhook when it becomes `CANCELED`), and a failed charge +of a subscription invoice as `invoice.scheduled_charge_failed`. Check that +existing webhook subscriptions include `invoice.scheduled_charge_failed`: +without it, failed renewals are never recorded in CiviCRM. `invoice.payment_made` is the preferred confirmation of a paid subscription installment, because the invoice names its subscription. Check that existing @@ -34,7 +42,8 @@ refund that is still `PENDING`. - `success` when processed; - `new` after a transient failure — Square unavailable (network error, HTTP 5xx or 429), or a related CiviCRM record not visible yet because - webhooks arrived before the checkout finished saving. The + webhooks arrived before the checkout finished saving, or out of order + (e.g. a refund before the payment it refunds). The **Process Payment Processor Webhooks** scheduled job retries `new` records on every run, for up to 72 hours after the event arrived; - `error` for anything else, including an amount mismatch (see below). @@ -72,6 +81,32 @@ not the subscription, so it is matched to its invoice at Square. already sent a receipt (webform_civicrm does), otherwise according to the recurring contribution's **Send email receipt** setting. Later installments are not receipted. +- If checkout could not confirm the subscription (e.g. Square's response + timed out), the recurring contribution has no subscription ID, but Square + still bills the subscription. The first webhook about it links the two, + from the recurring contribution and contact checkout stored in the + subscription's source — only if that recurring contribution belongs to this + processor and is not linked yet, and its contact is the one this processor + mapped the subscription's Square customer to. Each link made this way is + logged as a warning. +- A failed charge (`invoice.scheduled_charge_failed`) is checked against the + invoice's current status at Square: if it has been paid since (webhooks can + arrive out of order, and Square retries failed charges), nothing is marked + Failed. + +## Refunds + +- Refunds made from CiviCRM's refund form (`doRefund()`) are recorded only + once Square has completed them. Square accepts a card refund as `PENDING` + until it has the funds, which can take a while and can end in `FAILED`. + `doRefund()` checks on it for a few seconds; one still `PENDING` is reported + to staff as not recorded yet, and `refund.updated` records it when Square + completes it. Don't refund the payment again in the meantime. +- Refunds made in the Square Dashboard are recorded from `refund.updated` once + completed. +- A refund that arrives before the payment it refunds is recorded is retried + (for 30 minutes after Square created it), since Square does not deliver + webhooks in order. ## Troubleshooting diff --git a/info.xml b/info.xml index ee6bb2d0..2ffc68bc 100644 --- a/info.xml +++ b/info.xml @@ -32,7 +32,6 @@ CRM/Square 25.10.2 - crmSquare CRM_Square_Upgrader @@ -44,6 +43,5 @@ - diff --git a/js/square.js b/js/square.js index c3448b56..984acef7 100644 --- a/js/square.js +++ b/js/square.js @@ -1,719 +1,945 @@ -/*jshint esversion: 8 */ -/** - * JS Integration between CiviCRM & Square Web Payments SDK. - * - * Supports: - * - CiviCRM native contribution pages and event registration forms - * - Drupal Webform (webform_civicrm module) billing blocks - * - Backend contribution / event forms - * - * Architecture mirrors Stripe (civicrmStripe.js) and AuthNet (civicrmAuthNetAccept.js): - * - CRM.squarePayment — shared form-utility object (equivalent to CRM.payment in mjwshared) - * - window.civicrmSquareHandleReload — reinitializes the card element when the - * billing block is injected or replaced (including webform AJAX loads) - */ -(function ($, ts) { - - // ── Shared payment utilities ──────────────────────────────────────────────── - // Equivalent to the CRM.payment object provided by the mjwshared extension in - // the Stripe/AuthNet ecosystem. We define it here so Square is self-contained. - - var payment = { - form: null, - submitButtons: null, - scripts: {}, - - /** - * Sum visible line items on a webform or fall back to CiviCRM native total. - */ - getTotalAmount: function() { - var totalAmount = 0.0; - if (this.getIsDrupalWebform()) { - $('.line-item:visible', '#wf-crm-billing-items').each(function() { - totalAmount += parseFloat($(this).data('amount')); - }); - return totalAmount; - } - if (typeof calculateTotalFee === 'function') { - return parseFloat(calculateTotalFee()); - } - if (document.getElementById('totalTaxAmount') !== null) { - return this.calculateTaxAmount(); - } - if ($('#priceset [price]').length > 0) { - $('#priceset [price]').each(function() { - totalAmount += $(this).data('line_raw_total'); - }); + /*jshint esversion: 8 */ + /** + * JS Integration between CiviCRM & Square Web Payments SDK. + * + * Supports: + * - CiviCRM native contribution pages and event registration forms + * - Drupal Webform (webform_civicrm module) billing blocks + * - Backend contribution / event forms + * + * Architecture mirrors Stripe (civicrmStripe.js) and AuthNet (civicrmAuthNetAccept.js): + * - CRM.squarePayment — shared form-utility object (equivalent to CRM.payment in mjwshared) + * - window.civicrmSquareHandleReload — reinitializes the card element when the + * billing block is injected or replaced (including webform AJAX loads) + */ + (function ($, ts) { + + // ── Shared payment utilities ──────────────────────────────────────────────── + // Equivalent to the CRM.payment object provided by the mjwshared extension in + // the Stripe/AuthNet ecosystem. We define it here so Square is self-contained. + + var payment = { + form: null, + submitButtons: null, + scripts: {}, + + /** + * Sum visible line items on a webform or fall back to CiviCRM native total. + */ + getTotalAmount: function() { + var totalAmount = 0.0; + if (this.getIsDrupalWebform()) { + $('.line-item:visible', '#wf-crm-billing-items').each(function() { + totalAmount += parseFloat($(this).data('amount')); + }); + return totalAmount; + } + if (typeof calculateTotalFee === 'function') { + return parseFloat(calculateTotalFee()); + } + if (document.getElementById('totalTaxAmount') !== null) { + return this.calculateTaxAmount(); + } + if ($('#priceset [price]').length > 0) { + $('#priceset [price]').each(function() { + totalAmount += $(this).data('line_raw_total'); + }); + return totalAmount; + } + if (document.getElementById('total_amount')) { + return parseFloat(document.getElementById('total_amount').value); + } return totalAmount; - } - if (document.getElementById('total_amount')) { - return parseFloat(document.getElementById('total_amount').value); - } - return totalAmount; - }, - - calculateTaxAmount: function() { - var el = document.getElementById('totalTaxAmount'); - if (!el) return 0; - var totalTaxAmount; - if (el.textContent.length === 0) { - totalTaxAmount = document.getElementById('total_amount').value; - } - else { - var dPoint = (typeof separator !== 'undefined') ? separator : '.'; - var matcher = new RegExp('\\d{1,3}(' + dPoint.replace(/\W/g, '\\$&') + '\\d{0,2})?', 'g'); - totalTaxAmount = el.textContent.match(matcher).join('').replace(dPoint, '.'); - } - totalTaxAmount = parseFloat(totalTaxAmount); - return isNaN(totalTaxAmount) ? 0.0 : totalTaxAmount; - }, - - getCurrency: function(defaultCurrency) { - if (this.form && this.form.querySelector('#currency')) { - return this.form.querySelector('#currency').value; - } - return defaultCurrency; - }, - - /** - * Are we on a Drupal webform? - * Webform 7: .webform-client-form Webform 8/9/10: .webform-submission-form - */ - getIsDrupalWebform: function() { - return this.form !== null && ( - this.form.classList.contains('webform-client-form') || - this.form.classList.contains('webform-submission-form') - ); - }, + }, + + calculateTaxAmount: function() { + var el = document.getElementById('totalTaxAmount'); + if (!el) return 0; + var totalTaxAmount; + if (el.textContent.length === 0) { + totalTaxAmount = document.getElementById('total_amount').value; + } + else { + var dPoint = (typeof separator !== 'undefined') ? separator : '.'; + var matcher = new RegExp('\\d{1,3}(' + dPoint.replace(/\W/g, '\\$&') + '\\d{0,2})?', 'g'); + totalTaxAmount = el.textContent.match(matcher).join('').replace(dPoint, '.'); + } + totalTaxAmount = parseFloat(totalTaxAmount); + return isNaN(totalTaxAmount) ? 0.0 : totalTaxAmount; + }, - /** - * Find the
element that contains the billing block. - * Searches for well-known CiviCRM billing-block markers. - */ - getBillingForm: function() { - var billingFormID = $('div#crm-payment-js-billing-form-container').closest('form').attr('id'); - if (typeof billingFormID === 'undefined' || !billingFormID.length) { - billingFormID = $('input[name=hidden_processor]').closest('form').prop('id'); - } - if (typeof billingFormID === 'undefined' || !billingFormID.length) { - billingFormID = $('div#billing-payment-block').closest('form').prop('id'); - } - if (typeof billingFormID === 'undefined' || !billingFormID.length) { - this.debugging('squarePayment', 'no billing form found'); - this.form = null; + getCurrency: function(defaultCurrency) { + if (this.form && this.form.querySelector('#currency')) { + return this.form.querySelector('#currency').value; + } + return defaultCurrency; + }, + + /** + * Are we on a Drupal webform? + * Webform 7: .webform-client-form Webform 8/9/10: .webform-submission-form + */ + getIsDrupalWebform: function() { + return this.form !== null && ( + this.form.classList.contains('webform-client-form') || + this.form.classList.contains('webform-submission-form') + ); + }, + + /** + * Find the element that contains the billing block. + * Searches for well-known CiviCRM billing-block markers. + */ + getBillingForm: function() { + var billingFormID = $('div#crm-payment-js-billing-form-container').closest('form').attr('id'); + if (typeof billingFormID === 'undefined' || !billingFormID.length) { + billingFormID = $('input[name=hidden_processor]').closest('form').prop('id'); + } + if (typeof billingFormID === 'undefined' || !billingFormID.length) { + billingFormID = $('div#billing-payment-block').closest('form').prop('id'); + } + if (typeof billingFormID === 'undefined' || !billingFormID.length) { + this.debugging('squarePayment', 'no billing form found'); + this.form = null; + return null; + } + this.form = document.getElementById(billingFormID); + return this.form; + }, + + /** + * Return the submit buttons relevant to this billing form. + * Webforms use different button classes than CiviCRM native forms. + */ + getBillingSubmit: function() { + if (this.getIsDrupalWebform()) { + this.submitButtons = this.form.querySelectorAll('[type="submit"].webform-submit'); + if (this.submitButtons.length === 0) { + // Drupal 8/9/10 webform + this.submitButtons = this.form.querySelectorAll('[type="submit"].webform-button--submit'); + } + } + else { + this.submitButtons = this.form.querySelectorAll('[type="submit"].validate'); + } + return this.submitButtons; + }, + + getPaymentProcessorSelectorValue: function() { + var sel = this.form.querySelector('input[name="payment_processor_id"]:checked'); + if (sel) return parseInt(sel.value); + sel = this.form.querySelector('select[name="payment_processor_id"]'); + if (sel) return parseInt(sel.value); return null; - } - this.form = document.getElementById(billingFormID); - return this.form; - }, - - /** - * Return the submit buttons relevant to this billing form. - * Webforms use different button classes than CiviCRM native forms. - */ - getBillingSubmit: function() { - if (this.getIsDrupalWebform()) { - this.submitButtons = this.form.querySelectorAll('[type="submit"].webform-submit'); - if (this.submitButtons.length === 0) { - // Drupal 8/9/10 webform - this.submitButtons = this.form.querySelectorAll('[type="submit"].webform-button--submit'); + }, + + /** + * Return true when an AJAX URL is a CiviCRM payment-form request. + * Used to detect when the webform billing block has been refreshed. + */ + isAJAXPaymentForm: function(url) { + var patterns = [ + '(\\/|%2F)payment(\\/|%2F)form', + '(\\/|%2F)contact(\\/|%2F)view(\\/|%2F)participant', + '(\\/|%2F)contact(\\/|%2F)view(\\/|%2F)membership', + '(\\/|%2F)contact(\\/|%2F)view(\\/|%2F)contribution', + ]; + var basePage = (CRM.config && CRM.config.isFrontend && CRM.vars.payment && CRM.vars.payment.basePage) + ? CRM.vars.payment.basePage : null; + for (var i = 0; i < patterns.length; i++) { + if (basePage && url.match(basePage + patterns[i])) return true; + if (url.match('civicrm' + patterns[i])) return true; } - } - else { - this.submitButtons = this.form.querySelectorAll('[type="submit"].validate'); - } - return this.submitButtons; - }, - - getPaymentProcessorSelectorValue: function() { - var sel = this.form.querySelector('input[name="payment_processor_id"]:checked'); - if (sel) return parseInt(sel.value); - sel = this.form.querySelector('select[name="payment_processor_id"]'); - if (sel) return parseInt(sel.value); - return null; - }, + return false; + }, - /** - * Return true when an AJAX URL is a CiviCRM payment-form request. - * Used to detect when the webform billing block has been refreshed. - */ - isAJAXPaymentForm: function(url) { - var patterns = [ - '(\\/|%2F)payment(\\/|%2F)form', - '(\\/|%2F)contact(\\/|%2F)view(\\/|%2F)participant', - '(\\/|%2F)contact(\\/|%2F)view(\\/|%2F)membership', - '(\\/|%2F)contact(\\/|%2F)view(\\/|%2F)contribution', - ]; - var basePage = (CRM.config && CRM.config.isFrontend && CRM.vars.payment && CRM.vars.payment.basePage) - ? CRM.vars.payment.basePage : null; - for (var i = 0; i < patterns.length; i++) { - if (basePage && url.match(basePage + patterns[i])) return true; - if (url.match('civicrm' + patterns[i])) return true; - } - return false; - }, + resetBillingFieldsRequiredForJQueryValidate: function() { + $('div#priceset input[type="checkbox"], fieldset.crm-profile input[type="checkbox"], #on-behalf-block input[type="checkbox"]').each(function() { + if ($(this).attr('data-name') !== undefined) { + $(this).attr('name', $(this).attr('data-name')); + } + }); + }, - resetBillingFieldsRequiredForJQueryValidate: function() { - $('div#priceset input[type="checkbox"], fieldset.crm-profile input[type="checkbox"], #on-behalf-block input[type="checkbox"]').each(function() { - if ($(this).attr('data-name') !== undefined) { - $(this).attr('name', $(this).attr('data-name')); + setBillingFieldsRequiredForJQueryValidate: function() { + $('div.label span.crm-marker').each(function() { + $(this).closest('div').next('div').find('input[type="checkbox"]').addClass('required'); + }); + $('div#priceset input[type="checkbox"], fieldset.crm-profile input[type="checkbox"], #on-behalf-block input[type="checkbox"]').each(function() { + var name = $(this).attr('name'); + $(this).attr('data-name', name); + $(this).attr('name', name.replace('[' + name.split('[').pop(), '')); + }); + }, + + /** + * Drupal webform needs an "op" hidden field to know which page action fired. + */ + addDrupalWebformActionElement: function(submitAction) { + var hiddenInput = document.getElementById('action') || document.createElement('input'); + hiddenInput.setAttribute('type', 'hidden'); + hiddenInput.setAttribute('name', 'op'); + hiddenInput.setAttribute('id', 'action'); + hiddenInput.setAttribute('value', submitAction); + this.form.appendChild(hiddenInput); + }, + + doStandardFormSubmit: function() { + for (var i = 0; i < this.submitButtons.length; ++i) { + this.submitButtons[i].setAttribute('disabled', true); } - }); - }, - - setBillingFieldsRequiredForJQueryValidate: function() { - $('div.label span.crm-marker').each(function() { - $(this).closest('div').next('div').find('input[type="checkbox"]').addClass('required'); - }); - $('div#priceset input[type="checkbox"], fieldset.crm-profile input[type="checkbox"], #on-behalf-block input[type="checkbox"]').each(function() { - var name = $(this).attr('name'); - $(this).attr('data-name', name); - $(this).attr('name', name.replace('[' + name.split('[').pop(), '')); - }); - }, - - /** - * Drupal webform needs an "op" hidden field to know which page action fired. - */ - addDrupalWebformActionElement: function(submitAction) { - var hiddenInput = document.getElementById('action') || document.createElement('input'); - hiddenInput.setAttribute('type', 'hidden'); - hiddenInput.setAttribute('name', 'op'); - hiddenInput.setAttribute('id', 'action'); - hiddenInput.setAttribute('value', submitAction); - this.form.appendChild(hiddenInput); - }, - - doStandardFormSubmit: function() { - for (var i = 0; i < this.submitButtons.length; ++i) { - this.submitButtons[i].setAttribute('disabled', true); - } - this.resetBillingFieldsRequiredForJQueryValidate(); - this.form.submit(); - }, - - validateReCaptcha: function() { - if (typeof grecaptcha === 'undefined') return true; - if ($(this.form).find('[name=g-recaptcha-response]').length === 0) return true; - if ($(this.form).find('[name=g-recaptcha-response]').val().length > 0) return true; - this.swalFire({ icon: 'warning', text: '', title: ts('Please complete the reCaptcha') }, '.recaptcha-section', true); - this.triggerEvent('crmBillingFormNotValid'); - this.form.dataset.submitted = 'false'; - return false; - }, - - validateCiviDiscount: function() { - if ($('input#discountcode').length && - $('input#discountcode').val().length > 0 && - $('input#discountcode').attr('discount-applied') != 1) { - this.swalFire({ icon: 'error', text: ts('Please apply the Discount Code or clear the Discount Code text-field'), title: '' }, '#crm-container', true); - this.triggerEvent('crmBillingFormNotValid'); - this.form.dataset.submitted = 'false'; - return false; - } - return true; - }, - - validateForm: function() { - if (($(this.form).valid() === false) || $(this.form).data('crmBillingFormValid') === false) { - this.debugging('squarePayment', 'form not valid'); - this.swalFire({ icon: 'error', text: ts('Please check and fill in all required fields!'), title: '' }, '#crm-container', true); + this.resetBillingFieldsRequiredForJQueryValidate(); + this.form.submit(); + }, + + validateReCaptcha: function() { + if (typeof grecaptcha === 'undefined') return true; + if ($(this.form).find('[name=g-recaptcha-response]').length === 0) return true; + if ($(this.form).find('[name=g-recaptcha-response]').val().length > 0) return true; + this.swalFire({ icon: 'warning', text: '', title: ts('Please complete the reCaptcha') }, '.recaptcha-section', true); this.triggerEvent('crmBillingFormNotValid'); this.form.dataset.submitted = 'false'; return false; - } - return true; - }, - - addHandlerNonPaymentSubmitButtons: function() { - var self = this; - var nonPaymentSubmitButtons = this.form.querySelectorAll( - '[type="submit"][formnovalidate="1"], ' + - '[type="submit"][formnovalidate="formnovalidate"], ' + - '[type="submit"].cancel, ' + - '[type="submit"].webform-previous' - ); - for (var i = 0; i < nonPaymentSubmitButtons.length; ++i) { - nonPaymentSubmitButtons[i].addEventListener('click', function() { - self.form.dataset.submitdontprocess = 'true'; - }); - } - }, - - addSupportForCiviDiscount: function() { - var self = this; - var els = this.form.querySelectorAll('input#discountcode'); - for (var i = 0; i < els.length; ++i) { - els[i].addEventListener('keydown', function(event) { - if (event.code === 'Enter') { - event.preventDefault(); + }, + + validateCiviDiscount: function() { + if ($('input#discountcode').length && + $('input#discountcode').val().length > 0 && + $('input#discountcode').attr('discount-applied') != 1) { + this.swalFire({ icon: 'error', text: ts('Please apply the Discount Code or clear the Discount Code text-field'), title: '' }, '#crm-container', true); + this.triggerEvent('crmBillingFormNotValid'); + this.form.dataset.submitted = 'false'; + return false; + } + return true; + }, + + validateForm: function() { + if (($(this.form).valid() === false) || $(this.form).data('crmBillingFormValid') === false) { + this.debugging('squarePayment', 'form not valid'); + this.swalFire({ icon: 'error', text: ts('Please check and fill in all required fields!'), title: '' }, '#crm-container', true); + this.triggerEvent('crmBillingFormNotValid'); + this.form.dataset.submitted = 'false'; + return false; + } + return true; + }, + + addHandlerNonPaymentSubmitButtons: function() { + var self = this; + var nonPaymentSubmitButtons = this.form.querySelectorAll( + '[type="submit"][formnovalidate="1"], ' + + '[type="submit"][formnovalidate="formnovalidate"], ' + + '[type="submit"].cancel, ' + + '[type="submit"].webform-previous' + ); + for (var i = 0; i < nonPaymentSubmitButtons.length; ++i) { + nonPaymentSubmitButtons[i].addEventListener('click', function() { self.form.dataset.submitdontprocess = 'true'; + }); + } + }, + + addSupportForCiviDiscount: function() { + var self = this; + var els = this.form.querySelectorAll('input#discountcode'); + for (var i = 0; i < els.length; ++i) { + els[i].addEventListener('keydown', function(event) { + if (event.code === 'Enter') { + event.preventDefault(); + self.form.dataset.submitdontprocess = 'true'; + } + }); + } + }, + + displayError: function(errorMessage, notify) { + this.debugging('squarePayment', 'error: ' + errorMessage); + var errorElement = document.getElementById('square-card-errors'); + if (errorElement) { + errorElement.style.display = 'block'; + errorElement.textContent = errorMessage; + } + if (this.form) { + this.form.dataset.submitted = 'false'; + } + if (this.submitButtons) { + for (var i = 0; i < this.submitButtons.length; ++i) { + this.submitButtons[i].removeAttribute('disabled'); } - }); - } - }, - - displayError: function(errorMessage, notify) { - this.debugging('squarePayment', 'error: ' + errorMessage); - var errorElement = document.getElementById('square-card-errors'); - if (errorElement) { - errorElement.style.display = 'block'; - errorElement.textContent = errorMessage; - } - if (this.form) { - this.form.dataset.submitted = 'false'; - } - if (this.submitButtons) { - for (var i = 0; i < this.submitButtons.length; ++i) { - this.submitButtons[i].removeAttribute('disabled'); } - } - this.triggerEvent('crmBillingFormNotValid'); - if (notify) { - this.swalFire({ icon: 'error', text: errorMessage, title: '' }, '#crm-container', true); - } - }, - - swalFire: function(parameters, scrollToElement, fallBackToAlert) { - if (typeof Swal === 'function') { - if (scrollToElement && scrollToElement.length > 0) { - var $el = $(scrollToElement); - if ($el.length) { - parameters.didClose = function() { window.scrollTo($el.position()); }; + this.triggerEvent('crmBillingFormNotValid'); + if (notify) { + this.swalFire({ icon: 'error', text: errorMessage, title: '' }, '#crm-container', true); + } + }, + + swalFire: function(parameters, scrollToElement, fallBackToAlert) { + if (typeof Swal === 'function') { + if (scrollToElement && scrollToElement.length > 0) { + var $el = $(scrollToElement); + if ($el.length) { + parameters.didClose = function() { window.scrollTo($el.position()); }; + } } + Swal.fire(parameters); } - Swal.fire(parameters); - } - else if (fallBackToAlert) { - window.alert((parameters.title || '') + ' ' + (parameters.text || '')); - } - }, + else if (fallBackToAlert) { + window.alert((parameters.title || '') + ' ' + (parameters.text || '')); + } + }, - swalClose: function() { - if (typeof Swal === 'function') Swal.close(); - }, + swalClose: function() { + if (typeof Swal === 'function') Swal.close(); + }, - triggerEvent: function(event, scriptName) { - var triggerNow = true; - if (typeof scriptName !== 'undefined' && event === 'crmBillingFormReloadComplete') { - if (this.scripts[scriptName]) { - this.scripts[scriptName].reloadComplete = true; - } - $.each(this.scripts, function(name, obj) { - if (obj.reloadComplete !== true) { - triggerNow = false; - return false; + triggerEvent: function(event, scriptName) { + var triggerNow = true; + if (typeof scriptName !== 'undefined' && event === 'crmBillingFormReloadComplete') { + if (this.scripts[scriptName]) { + this.scripts[scriptName].reloadComplete = true; } - }); - } - if (triggerNow && this.form) { - $(this.form).trigger(event); - } - }, + $.each(this.scripts, function(name, obj) { + if (obj.reloadComplete !== true) { + triggerNow = false; + return false; + } + }); + } + if (triggerNow && this.form) { + $(this.form).trigger(event); + } + }, - registerScript: function(scriptName) { - this.scripts[scriptName] = { reloadComplete: false }; - }, + registerScript: function(scriptName) { + this.scripts[scriptName] = { reloadComplete: false }; + }, - debugging: function(scriptName, errorCode) { - if (typeof CRM.vars !== 'undefined' && - typeof CRM.vars.payment !== 'undefined' && - Boolean(CRM.vars.payment.jsDebug) === true) { - console.log(new Date().toISOString() + ' ' + scriptName + ': ' + errorCode); + debugging: function(scriptName, errorCode) { + if (typeof CRM.vars !== 'undefined' && + typeof CRM.vars.payment !== 'undefined' && + Boolean(CRM.vars.payment.jsDebug) === true) { + console.log(new Date().toISOString() + ' ' + scriptName + ': ' + errorCode); + } } + }; + + if (typeof CRM.squarePayment === 'undefined') { + CRM.squarePayment = payment; } - }; - - if (typeof CRM.squarePayment === 'undefined') { - CRM.squarePayment = payment; - } - else { - $.extend(CRM.squarePayment, payment); - } - - // ── Square processor script ───────────────────────────────────────────────── - - var script = { - name: 'square', - card: null, - sdkPromise: null, - initializing: false, - - debugging: function(msg) { - CRM.squarePayment.debugging(script.name, msg); - }, - - getConfig: function() { - var cfg = (typeof CRM.vars !== 'undefined' && CRM.vars.orgUschessSquare) || {}; - return { - appId: cfg.applicationId || window.squareApplicationId || '', - locationId: cfg.locationId || window.squareLocationId || '', - isSandbox: !!(cfg.isSandbox || window.squareIsSandbox), - processorId: cfg.id ? parseInt(cfg.id) : null, - }; - }, - - ensureSdkLoaded: function(isSandbox) { - if (window.Square && window.Square.payments) return Promise.resolve(); - if (script.sdkPromise) return script.sdkPromise; - - var sdkUrl = isSandbox - ? 'https://sandbox.web.squarecdn.com/v1/square.js' - : 'https://web.squarecdn.com/v1/square.js'; - - script.sdkPromise = new Promise(function(resolve, reject) { - var existing = document.querySelector('script[src="' + sdkUrl + '"]'); - if (existing) { - if (window.Square && window.Square.payments) { resolve(); return; } - existing.addEventListener('load', resolve); - existing.addEventListener('error', function() { reject(new Error('Square SDK load failed')); }); - return; + else { + $.extend(CRM.squarePayment, payment); + } + + // ── Square processor script ───────────────────────────────────────────────── + + var script = { + name: 'square', + card: null, + sdkPromise: null, + initializing: false, + // The postal code in the card form, as last reported by Square. + cardPostalCode: '', + // The value this script last copied into the billing postal code field. + autofilledPostalCode: null, + billingPostalCodePattern: /billing_postal_code(-\d+)?\]?$/, + + debugging: function(msg) { + CRM.squarePayment.debugging(script.name, msg); + }, + + getConfig: function() { + var cfg = (typeof CRM.vars !== 'undefined' && CRM.vars.orgUschessSquare) || {}; + return { + appId: cfg.applicationId || window.squareApplicationId || '', + locationId: cfg.locationId || window.squareLocationId || '', + isSandbox: !!(cfg.isSandbox || window.squareIsSandbox), + processorId: cfg.id ? parseInt(cfg.id) : null, + currency: cfg.currency || 'USD', + countryIsoCodes: cfg.countryIsoCodes || {}, + }; + }, + + /** + * Value of the first form field whose name matches, if any. + * + * CiviCRM names billing fields e.g. billing_city-5 (5 being the billing + * location type); webforms wrap names in submitted[...]. + */ + fieldValue: function(pattern) { + var el = script.findField(pattern); + if (!el) return ''; + if (el.tagName === 'SELECT') { + return el.selectedIndex > 0 || el.value ? { value: el.value, text: (el.options[el.selectedIndex] || {}).text || '' } : ''; } - var s = document.createElement('script'); - s.src = sdkUrl; - s.async = true; - s.onload = resolve; - s.onerror = function() { reject(new Error('Square SDK load failed')); }; - (document.head || document.documentElement).appendChild(s); - }); + return (el.value || '').trim(); + }, + + /** + * The first form field whose name matches (a radio or checkbox only if checked), if any. + */ + findField: function(pattern) { + var form = CRM.squarePayment.form; + if (!form) return null; + for (var i = 0; i < form.elements.length; i++) { + var el = form.elements[i]; + if (!el.name || !pattern.test(el.name)) continue; + if ((el.type === 'radio' || el.type === 'checkbox') && !el.checked) continue; + return el; + } + return null; + }, + + /** + * Whether this checkout sets up a recurring payment. + */ + isRecurring: function() { + var form = CRM.squarePayment.form; + if (!form) return false; + if ($(form).find('input[name="is_recur"]:checked, input[type="hidden"][name="is_recur"][value="1"]').length) return true; + if ($(form).find('input[name="auto_renew"]:checked, input[type="hidden"][name="auto_renew"][value="1"]').length) return true; + // Webform CiviCRM: a frequency other than "one-time" (0). + var frequency = script.fieldValue(/contribution_frequency_unit\]?$/); + frequency = typeof frequency === 'object' ? frequency.value : frequency; + return !!frequency && frequency !== '0'; + }, + + /** + * Buyer details Square uses to verify the buyer (Strong Customer Authentication). + * + * Square performs the verification while tokenizing, and the token + * carries it: nothing more is sent to CiviCRM. A recurring checkout only + * stores the card (Square's subscription charges it), so its intent is + * STORE. + */ + getVerificationDetails: function(totalAmount) { + var cfg = script.getConfig(); + var text = function(value) { + return typeof value === 'object' ? value.text : value; + }; + var contact = {}; + var givenName = script.fieldValue(/(^|\[|_)billing_first_name(\]|$)/) || script.fieldValue(/first_name\]?$/); + var familyName = script.fieldValue(/(^|\[|_)billing_last_name(\]|$)/) || script.fieldValue(/last_name\]?$/); + var email = script.fieldValue(/^email-(\d+|Primary)$/) || script.fieldValue(/email(-\d+)?\]?$/); + var street = script.fieldValue(/billing_street_address(-\d+)?\]?$/); + var street2 = script.fieldValue(/billing_supplemental_address_1(-\d+)?\]?$/); + var city = script.fieldValue(/billing_city(-\d+)?\]?$/); + var state = script.fieldValue(/billing_state_province(_id)?(-\d+)?\]?$/); + var postalCode = script.fieldValue(script.billingPostalCodePattern); + var country = script.fieldValue(/billing_country(_id)?(-\d+)?\]?$/); + if (givenName) contact.givenName = givenName; + if (familyName) contact.familyName = familyName; + if (email) contact.email = email; + if (street) contact.addressLines = street2 ? [street, street2] : [street]; + if (city) contact.city = city; + if (state && text(state)) contact.state = text(state); + if (postalCode) contact.postalCode = postalCode; + if (country) { + var countryCode = typeof country === 'object' ? cfg.countryIsoCodes[country.value] : country; + if (countryCode && /^[A-Za-z]{2}$/.test(countryCode)) contact.countryCode = countryCode.toUpperCase(); + } + return { + amount: Number(totalAmount || 0).toFixed(2), + billingContact: contact, + currencyCode: CRM.squarePayment.getCurrency(cfg.currency), + intent: script.isRecurring() ? 'STORE' : 'CHARGE', + customerInitiated: true, + sellerKeyedIn: false + }; + }, + + /** + * Options for Square's card form: its postal code starts as the billing address's. + * + * A logged-in donor's billing address is often filled in already. + */ + getCardOptions: function() { + var postalCode = script.toCardPostalCode(script.fieldValue(script.billingPostalCodePattern)); + return postalCode ? { postalCode: postalCode } : null; + }, + + /** + * A billing postal code as the card form takes it: a US ZIP+4 is cut to its 5-digit ZIP. + */ + toCardPostalCode: function(postalCode) { + postalCode = (postalCode || '').trim(); + return /^\d{5}-?\d{4}$/.test(postalCode) ? postalCode.slice(0, 5) : postalCode; + }, + + /** + * Update the card form's postal code when the donor changes the billing address's. + * + * A billing postal code that is cleared leaves the card form's as it is. + */ + onBillingPostalCodeChanged: function(billingPostalCode) { + var postalCode = script.toCardPostalCode(billingPostalCode); + var card = script.card; + if (!card || !postalCode || script.postalCodesMatch(postalCode, script.cardPostalCode)) return; + Promise.resolve() + .then(function() { + return card.configure({ postalCode: postalCode }); + }) + .then(function() { + // Square may also report it through postalCodeChanged. + if (script.card === card) { + script.cardPostalCode = postalCode; + } + }) + .catch(function(err) { + // submit() still stops a mismatch. + script.debugging('could not update the card form postal code: ' + (err && err.message || err)); + }); + }, + + /** + * Fill in the billing postal code from the card form's, as the donor types it. + * + * The card form comes before the billing address on CiviCRM's forms, so + * the billing postal code is often still empty. One the donor (or + * CiviCRM) filled in is never overwritten: if it differs, submit() asks + * the donor to correct one of them. + */ + onCardPostalCodeChanged: function(postalCode) { + script.cardPostalCode = (postalCode || '').trim(); + var field = script.findField(script.billingPostalCodePattern); + if (!field || field.disabled || field.readOnly) return; + var current = (field.value || '').trim(); + if (current === '' || current === script.autofilledPostalCode) { + field.value = script.cardPostalCode; + script.autofilledPostalCode = script.cardPostalCode; + } + }, + + /** + * Whether two postal codes are the same, ignoring case, spaces and + * hyphens. US ZIP codes are compared by their first 5 digits, so a + * ZIP+4 matches its ZIP. + */ + postalCodesMatch: function(a, b) { + var normalize = function(value) { + return String(value || '').toUpperCase().replace(/[^0-9A-Z]/g, ''); + }; + a = normalize(a); + b = normalize(b); + var zip = /^\d{5}(\d{4})?$/; + if (zip.test(a) && zip.test(b)) { + return a.slice(0, 5) === b.slice(0, 5); + } + return a === b; + }, + + /** + * The error to show when the card form's postal code differs from the billing address's. + * + * Square verifies the card against the postal code in the card form; + * CiviCRM records the billing address. Both describe the card's billing + * address, so they must agree. + * + * @return {string} + * Empty if they match, or either is blank. + */ + getPostalCodeMismatchError: function(cardPostalCode) { + var billingPostalCode = script.fieldValue(script.billingPostalCodePattern); + if (!cardPostalCode || !billingPostalCode || script.postalCodesMatch(cardPostalCode, billingPostalCode)) { + return ''; + } + return ts('The ZIP/postal code entered with your card (%1) does not match the one in your billing address (%2). Please correct whichever is wrong.', {1: cardPostalCode, 2: billingPostalCode}); + }, + + ensureSdkLoaded: function(isSandbox) { + if (window.Square && window.Square.payments) return Promise.resolve(); + if (script.sdkPromise) return script.sdkPromise; + + var sdkUrl = isSandbox + ? 'https://sandbox.web.squarecdn.com/v1/square.js' + : 'https://web.squarecdn.com/v1/square.js'; + + script.sdkPromise = new Promise(function(resolve, reject) { + var existing = document.querySelector('script[src="' + sdkUrl + '"]'); + if (existing) { + if (window.Square && window.Square.payments) { resolve(); return; } + existing.addEventListener('load', resolve); + existing.addEventListener('error', function() { reject(new Error('Square SDK load failed')); }); + return; + } + var s = document.createElement('script'); + s.src = sdkUrl; + s.async = true; + s.onload = resolve; + s.onerror = function() { reject(new Error('Square SDK load failed')); }; + (document.head || document.documentElement).appendChild(s); + }); - return script.sdkPromise; - }, + return script.sdkPromise; + }, - notScriptProcessor: function() { - script.debugging('payment processor is not Square, cleaning up'); - script.initializing = false; - if (script.card) { - try { script.card.destroy(); } catch(e) {} - script.card = null; - } - var containerEl = document.getElementById('square-card-container'); - if (containerEl) { - containerEl.innerHTML = ''; - } - if (typeof CRM.vars !== 'undefined') { - delete CRM.vars.orgUschessSquare; - } - if (CRM.squarePayment.submitButtons) { - $(CRM.squarePayment.submitButtons).show(); - } - }, + notScriptProcessor: function() { + script.debugging('payment processor is not Square, cleaning up'); + script.initializing = false; + if (script.card) { + try { script.card.destroy(); } catch(e) {} + script.card = null; + } + var containerEl = document.getElementById('square-card-container'); + if (containerEl) { + containerEl.innerHTML = ''; + } + if (typeof CRM.vars !== 'undefined') { + delete CRM.vars.orgUschessSquare; + } + if (CRM.squarePayment.submitButtons) { + $(CRM.squarePayment.submitButtons).show(); + } + }, - checkAndLoad: function() { - if (script.initializing) { - script.debugging('init already in progress, skipping'); - return; - } - if (typeof CRM.vars === 'undefined' || typeof CRM.vars.orgUschessSquare === 'undefined') { - script.debugging('CRM.vars.orgUschessSquare not defined'); - return; - } - var cfg = script.getConfig(); - if (!cfg.appId || !cfg.locationId) { - script.debugging('Square config missing applicationId or locationId'); - return; - } + checkAndLoad: function() { + if (script.initializing) { + script.debugging('init already in progress, skipping'); + return; + } + if (typeof CRM.vars === 'undefined' || typeof CRM.vars.orgUschessSquare === 'undefined') { + script.debugging('CRM.vars.orgUschessSquare not defined'); + return; + } + var cfg = script.getConfig(); + if (!cfg.appId || !cfg.locationId) { + script.debugging('Square config missing applicationId or locationId'); + return; + } - script.initializing = true; + script.initializing = true; - // Destroy any previously mounted card instance before creating a new one. - if (script.card) { - try { script.card.destroy(); } catch(e) {} - script.card = null; - } + // Destroy any previously mounted card instance before creating a new one. + if (script.card) { + try { script.card.destroy(); } catch(e) {} + script.card = null; + } - // Empty the container so Square always starts with a clean slate. - // This prevents the "card appears twice" issue when switching processors. - var containerEl = document.getElementById('square-card-container'); - if (containerEl) { - containerEl.innerHTML = ''; - containerEl.style.display = 'none'; - } + // Empty the container so Square always starts with a clean slate. + // This prevents the "card appears twice" issue when switching processors. + var containerEl = document.getElementById('square-card-container'); + if (containerEl) { + containerEl.innerHTML = ''; + containerEl.style.display = 'none'; + } - script.ensureSdkLoaded(cfg.isSandbox) - .then(function() { - if (!window.Square || !window.Square.payments) { - throw new Error('Square.payments API not available after SDK load'); - } - var payments = window.Square.payments(cfg.appId, cfg.locationId); - return payments.card().then(function(c) { - script.card = c; - return script.card.attach('#square-card-container'); + script.ensureSdkLoaded(cfg.isSandbox) + .then(function() { + if (!window.Square || !window.Square.payments) { + throw new Error('Square.payments API not available after SDK load'); + } + var payments = window.Square.payments(cfg.appId, cfg.locationId); + var cardOptions = script.getCardOptions(); + script.cardPostalCode = cardOptions ? cardOptions.postalCode : ''; + script.autofilledPostalCode = null; + return (cardOptions ? payments.card(cardOptions) : payments.card()).then(function(c) { + script.card = c; + script.card.addEventListener('postalCodeChanged', function(cardInputEvent) { + script.onCardPostalCodeChanged(cardInputEvent.detail && cardInputEvent.detail.postalCodeValue); + }); + return script.card.attach('#square-card-container'); + }); + }) + .then(function() { + script.initializing = false; + var container = document.getElementById('square-card-container'); + if (container) container.style.display = 'block'; + script.doAfterElementsHaveLoaded(); + }) + .catch(function(err) { + script.initializing = false; + script.debugging('Square card init failed: ' + (err && err.message || err)); + var errEl = document.getElementById('square-card-errors'); + if (errEl) { + errEl.textContent = ts('Unable to load secure card entry. Please try again later or contact support.'); + errEl.style.display = 'block'; + } + script.triggerReloadFailed(); }); - }) - .then(function() { - script.initializing = false; - var container = document.getElementById('square-card-container'); - if (container) container.style.display = 'block'; - script.doAfterElementsHaveLoaded(); - }) - .catch(function(err) { - script.initializing = false; - script.debugging('Square card init failed: ' + (err && err.message || err)); - var errEl = document.getElementById('square-card-errors'); - if (errEl) { - errEl.textContent = ts('Unable to load secure card entry. Please try again later or contact support.'); - errEl.style.display = 'block'; - } - script.triggerReloadFailed(); - }); - }, + }, - doAfterElementsHaveLoaded: function() { - CRM.squarePayment.setBillingFieldsRequiredForJQueryValidate(); - CRM.squarePayment.form.dataset.submitdontprocess = 'false'; - CRM.squarePayment.addHandlerNonPaymentSubmitButtons(); + doAfterElementsHaveLoaded: function() { + CRM.squarePayment.setBillingFieldsRequiredForJQueryValidate(); + CRM.squarePayment.form.dataset.submitdontprocess = 'false'; + CRM.squarePayment.addHandlerNonPaymentSubmitButtons(); - var submitButtons = CRM.squarePayment.getBillingSubmit(); - for (var i = 0; i < submitButtons.length; ++i) { - $(submitButtons[i]).off('click.square').on('click.square', submitButtonClick); - } + var submitButtons = CRM.squarePayment.getBillingSubmit(); + for (var i = 0; i < submitButtons.length; ++i) { + $(submitButtons[i]).off('click.square').on('click.square', submitButtonClick); + } - function submitButtonClick(clickEvent) { - if (typeof CRM.vars === 'undefined' || typeof CRM.vars.orgUschessSquare === 'undefined') { - return CRM.squarePayment.doStandardFormSubmit(); + function submitButtonClick(clickEvent) { + if (typeof CRM.vars === 'undefined' || typeof CRM.vars.orgUschessSquare === 'undefined') { + return CRM.squarePayment.doStandardFormSubmit(); + } + CRM.squarePayment.form.dataset.submitdontprocess = 'false'; + return script.submit(clickEvent); } - CRM.squarePayment.form.dataset.submitdontprocess = 'false'; - return script.submit(clickEvent); - } - CRM.squarePayment.addSupportForCiviDiscount(); + CRM.squarePayment.addSupportForCiviDiscount(); - // Webform-specific wiring - if (CRM.squarePayment.getIsDrupalWebform()) { - // Store which submit button was clicked so the op hidden field is set - $('[type=submit]').click(function() { - CRM.squarePayment.addDrupalWebformActionElement(this.value); - }); - // Enter key on webform should also trigger our submit - CRM.squarePayment.form.addEventListener('keydown', function(keydownEvent) { - if (keydownEvent.code === 'Enter') { - CRM.squarePayment.addDrupalWebformActionElement(keydownEvent.target.value || ''); - script.submit(keydownEvent); + // The card form's postal code follows the billing address's. Bound to + // the form, so it also covers billing fields shown or reloaded later. + $(CRM.squarePayment.form).off('change.squarePostalCode').on('change.squarePostalCode', function(changeEvent) { + var target = changeEvent.target; + if (target && target.name && script.billingPostalCodePattern.test(target.name)) { + script.onBillingPostalCodeChanged(target.value); } }); - $('#billingcheckbox:input').hide(); - $('label[for="billingcheckbox"]').hide(); - } - var cardContainer = document.getElementById('square-card-container'); - if (cardContainer && cardContainer.children.length) { - CRM.squarePayment.triggerEvent('crmBillingFormReloadComplete', script.name); - CRM.squarePayment.triggerEvent('crmSquareBillingFormReloadComplete', script.name); - } - else { - script.triggerReloadFailed(); - } - }, + // Webform-specific wiring. Namespaced, and unbound first, because the + // billing block (and so this) is reloaded whenever the processor or + // amount changes. + if (CRM.squarePayment.getIsDrupalWebform()) { + // Store which submit button was clicked so the op hidden field is set + $('[type=submit]', CRM.squarePayment.form).off('click.squareWebform').on('click.squareWebform', function() { + CRM.squarePayment.addDrupalWebformActionElement(this.value); + }); + // Enter key on webform should also trigger our submit + $(CRM.squarePayment.form).off('keydown.squareWebform').on('keydown.squareWebform', function(keydownEvent) { + if (keydownEvent.key === 'Enter' && keydownEvent.target.tagName !== 'TEXTAREA') { + CRM.squarePayment.addDrupalWebformActionElement(keydownEvent.target.value || ''); + script.submit(keydownEvent); + } + }); + $('#billingcheckbox:input').hide(); + $('label[for="billingcheckbox"]').hide(); + } - submit: async function(submitEvent) { - submitEvent.preventDefault(); - script.debugging('submit handler'); + var cardContainer = document.getElementById('square-card-container'); + if (cardContainer && cardContainer.children.length) { + CRM.squarePayment.triggerEvent('crmBillingFormReloadComplete', script.name); + CRM.squarePayment.triggerEvent('crmSquareBillingFormReloadComplete', script.name); + } + else { + script.triggerReloadFailed(); + } + }, - if (CRM.squarePayment.form.dataset.submitted === 'true') { - return; - } - CRM.squarePayment.form.dataset.submitted = 'true'; + submit: async function(submitEvent) { + submitEvent.preventDefault(); + script.debugging('submit handler'); - if (!CRM.squarePayment.validateCiviDiscount()) return false; - if (!CRM.squarePayment.validateForm()) return false; - if (!CRM.squarePayment.validateReCaptcha()) return false; + if (CRM.squarePayment.form.dataset.submitted === 'true') { + return; + } + CRM.squarePayment.form.dataset.submitted = 'true'; - if (typeof CRM.vars === 'undefined' || typeof CRM.vars.orgUschessSquare === 'undefined') { - script.debugging('not a Square processor, submitting normally'); - return CRM.squarePayment.doStandardFormSubmit(); - } + if (!CRM.squarePayment.validateCiviDiscount()) return false; + if (!CRM.squarePayment.validateForm()) return false; + if (!CRM.squarePayment.validateReCaptcha()) return false; - var cfg = script.getConfig(); - var chosenProcessorId = null; + if (typeof CRM.vars === 'undefined' || typeof CRM.vars.orgUschessSquare === 'undefined') { + script.debugging('not a Square processor, submitting normally'); + return CRM.squarePayment.doStandardFormSubmit(); + } + + var cfg = script.getConfig(); + var chosenProcessorId = null; - // Determine which processor the user has selected (matters when multiple processors exist) - if (CRM.squarePayment.getIsDrupalWebform()) { - var $wfProc = $('input[name="submitted[civicrm_1_contribution_1_contribution_payment_processor_id]"]'); - if (!$wfProc.length) { - // Single processor on form — treat it as ours - chosenProcessorId = cfg.processorId; + // Determine which processor the user has selected (matters when multiple processors exist) + if (CRM.squarePayment.getIsDrupalWebform()) { + var $wfProc = $('input[name="submitted[civicrm_1_contribution_1_contribution_payment_processor_id]"]'); + if (!$wfProc.length) { + // Single processor on form — treat it as ours + chosenProcessorId = cfg.processorId; + } + else { + var checkedWf = CRM.squarePayment.form.querySelector('input[name="submitted[civicrm_1_contribution_1_contribution_payment_processor_id]"]:checked'); + chosenProcessorId = checkedWf ? parseInt(checkedWf.value) : null; + } } else { - var checkedWf = CRM.squarePayment.form.querySelector('input[name="submitted[civicrm_1_contribution_1_contribution_payment_processor_id]"]:checked'); - chosenProcessorId = checkedWf ? parseInt(checkedWf.value) : null; - } - } - else { - if ((CRM.squarePayment.form.querySelector('.crm-section.payment_processor-section') !== null) || - (CRM.squarePayment.form.querySelector('.crm-section.credit_card_info-section') !== null)) { - var checkedProc = CRM.squarePayment.form.querySelector('input[name="payment_processor_id"]:checked'); - if (checkedProc) { - chosenProcessorId = parseInt(checkedProc.value); + if ((CRM.squarePayment.form.querySelector('.crm-section.payment_processor-section') !== null) || + (CRM.squarePayment.form.querySelector('.crm-section.credit_card_info-section') !== null)) { + var checkedProc = CRM.squarePayment.form.querySelector('input[name="payment_processor_id"]:checked'); + if (checkedProc) { + chosenProcessorId = parseInt(checkedProc.value); + } } } - } - - // Pay-later or no processor selected → standard submit - if (chosenProcessorId === 0) { - script.debugging('pay-later selected'); - return CRM.squarePayment.doStandardFormSubmit(); - } - // Non-payment submit (e.g. discount "Apply" button) → skip tokenization - if (CRM.squarePayment.form.dataset.submitdontprocess === 'true') { - script.debugging('non-payment submit, skipping tokenization'); - return CRM.squarePayment.doStandardFormSubmit(); - } + // Pay-later or no processor selected → standard submit + if (chosenProcessorId === 0) { + script.debugging('pay-later selected'); + return CRM.squarePayment.doStandardFormSubmit(); + } - if (CRM.squarePayment.getIsDrupalWebform()) { - // Billing block hidden → not a payment step - if ($('#billing-payment-block').is(':hidden')) { - script.debugging('billing block hidden on webform'); + // Non-payment submit (e.g. discount "Apply" button) → skip tokenization + if (CRM.squarePayment.form.dataset.submitdontprocess === 'true') { + script.debugging('non-payment submit, skipping tokenization'); return CRM.squarePayment.doStandardFormSubmit(); } - var $procFields = $('[name="submitted[civicrm_1_contribution_1_contribution_payment_processor_id]"]'); - if ($procFields.length) { - var checkedVal = $procFields.filter(':checked').val(); - if (checkedVal === '0' || parseInt(checkedVal) === 0) { - script.debugging('no payment processor selected on webform'); + + if (CRM.squarePayment.getIsDrupalWebform()) { + // Billing block hidden → not a payment step + if ($('#billing-payment-block').is(':hidden')) { + script.debugging('billing block hidden on webform'); return CRM.squarePayment.doStandardFormSubmit(); } + var $procFields = $('[name="submitted[civicrm_1_contribution_1_contribution_payment_processor_id]"]'); + if ($procFields.length) { + var checkedVal = $procFields.filter(':checked').val(); + if (checkedVal === '0' || parseInt(checkedVal) === 0) { + script.debugging('no payment processor selected on webform'); + return CRM.squarePayment.doStandardFormSubmit(); + } + } } - } - - var totalAmount = CRM.squarePayment.getTotalAmount(); - if (totalAmount === 0.0) { - script.debugging('zero amount, standard submit'); - return CRM.squarePayment.doStandardFormSubmit(); - } - // Disable buttons to prevent double-clicks - var submitButtons = CRM.squarePayment.submitButtons; - for (var i = 0; i < submitButtons.length; ++i) { - submitButtons[i].setAttribute('disabled', true); - } + var totalAmount = CRM.squarePayment.getTotalAmount(); + if (totalAmount === 0.0) { + script.debugging('zero amount, standard submit'); + return CRM.squarePayment.doStandardFormSubmit(); + } - if (!script.card) { - script.debugging('card element not initialized'); - CRM.squarePayment.form.dataset.submitted = 'false'; - for (var j = 0; j < submitButtons.length; ++j) { - submitButtons[j].removeAttribute('disabled'); + // Disable buttons to prevent double-clicks + var submitButtons = CRM.squarePayment.submitButtons; + for (var i = 0; i < submitButtons.length; ++i) { + submitButtons[i].setAttribute('disabled', true); } - CRM.squarePayment.displayError(ts('Secure card entry is not ready. Please wait a moment and try again.'), true); - return false; - } - try { - var result = await script.card.tokenize(); - if (!result || result.status !== 'OK') { - var message = ts('Your card could not be processed. Please check your details.'); - if (result && result.errors && result.errors.length) { - message = result.errors[0].message || message; + if (!script.card) { + script.debugging('card element not initialized'); + CRM.squarePayment.form.dataset.submitted = 'false'; + for (var j = 0; j < submitButtons.length; ++j) { + submitButtons[j].removeAttribute('disabled'); } - CRM.squarePayment.displayError(message, true); + CRM.squarePayment.displayError(ts('Secure card entry is not ready. Please wait a moment and try again.'), true); return false; } - // Write token into the hidden field that the PHP processor reads - var tokenField = CRM.squarePayment.form.querySelector('#square_payment_token') || - CRM.squarePayment.form.querySelector('[name="square_payment_token"]'); - if (!tokenField) { - tokenField = document.createElement('input'); - tokenField.setAttribute('type', 'hidden'); - tokenField.setAttribute('name', 'square_payment_token'); - tokenField.setAttribute('id', 'square_payment_token'); - CRM.squarePayment.form.appendChild(tokenField); + // Checked before tokenizing too, so the donor is not taken through + // buyer verification only to be asked to correct the postal code. + var postalCodeError = script.getPostalCodeMismatchError(script.cardPostalCode); + if (postalCodeError) { + CRM.squarePayment.displayError(postalCodeError, true); + return false; } - tokenField.value = result.token; - CRM.squarePayment.resetBillingFieldsRequiredForJQueryValidate(); - CRM.squarePayment.form.submit(); - } - catch(e) { - CRM.squarePayment.displayError(ts('Unexpected error processing your card. Please try again.'), true); - CRM.squarePayment.form.dataset.submitted = 'false'; - return false; - } - }, - - triggerReloadFailed: function() { - CRM.squarePayment.triggerEvent('crmBillingFormReloadFailed'); - var errEl = document.getElementById('square-card-errors'); - if (errEl) { - errEl.textContent = ts('Could not load payment element. Is there a problem with your network connection?'); - errEl.style.display = 'block'; - } - } - }; + try { + var result = await script.card.tokenize(script.getVerificationDetails(totalAmount)); + if (!result || result.status !== 'OK') { + var message = ts('Your card could not be processed. Please check your details.'); + if (result && result.errors && result.errors.length) { + message = result.errors[0].message || message; + } + CRM.squarePayment.displayError(message, true); + return false; + } - // ── Bootstrap ─────────────────────────────────────────────────────────────── + // The postal code the token carries is the one that counts. + var billing = (result.details && result.details.billing) || {}; + postalCodeError = script.getPostalCodeMismatchError(billing.postalCode); + if (postalCodeError) { + CRM.squarePayment.displayError(postalCodeError, true); + return false; + } - if (CRM.squarePayment.hasOwnProperty(script.name)) { - // Already loaded — just re-run HandleReload in case the billing block was replaced - if (window.civicrmSquareHandleReload) { - window.civicrmSquareHandleReload(); - } - return; - } + // Write token into the hidden field that the PHP processor reads + var tokenField = CRM.squarePayment.form.querySelector('#square_payment_token') || + CRM.squarePayment.form.querySelector('[name="square_payment_token"]'); + if (!tokenField) { + tokenField = document.createElement('input'); + tokenField.setAttribute('type', 'hidden'); + tokenField.setAttribute('name', 'square_payment_token'); + tokenField.setAttribute('id', 'square_payment_token'); + CRM.squarePayment.form.appendChild(tokenField); + } + tokenField.value = result.token; - var crmPaymentObject = {}; - crmPaymentObject[script.name] = script; - $.extend(CRM.squarePayment, crmPaymentObject); + CRM.squarePayment.resetBillingFieldsRequiredForJQueryValidate(); + CRM.squarePayment.form.submit(); + } + catch(e) { + CRM.squarePayment.displayError(ts('Unexpected error processing your card. Please try again.'), true); + CRM.squarePayment.form.dataset.submitted = 'false'; + return false; + } + }, + + triggerReloadFailed: function() { + CRM.squarePayment.triggerEvent('crmBillingFormReloadFailed'); + var errEl = document.getElementById('square-card-errors'); + if (errEl) { + errEl.textContent = ts('Could not load payment element. Is there a problem with your network connection?'); + errEl.style.display = 'block'; + } + } + }; - CRM.squarePayment.registerScript(script.name); + // ── Bootstrap ─────────────────────────────────────────────────────────────── - // Re-init when the billing block is loaded via AJAX (webforms, backend switches) - $(document).ajaxComplete(function(event, xhr, settings) { - if (CRM.squarePayment.isAJAXPaymentForm(settings.url)) { - CRM.squarePayment.debugging(script.name, 'triggered via ajaxComplete'); - load(); + if (CRM.squarePayment.hasOwnProperty(script.name)) { + // Already loaded — just re-run HandleReload in case the billing block was replaced + if (window.civicrmSquareHandleReload) { + window.civicrmSquareHandleReload(); + } + return; } - }); - document.addEventListener('DOMContentLoaded', function() { - CRM.squarePayment.debugging(script.name, 'DOMContentLoaded'); - load(); - }); + var crmPaymentObject = {}; + crmPaymentObject[script.name] = script; + $.extend(CRM.squarePayment, crmPaymentObject); - function load() { - if (window.civicrmSquareHandleReload) { - CRM.squarePayment.debugging(script.name, 'calling civicrmSquareHandleReload'); - window.civicrmSquareHandleReload(); - } - } + CRM.squarePayment.registerScript(script.name); - /** - * (Re-)initialize Square for the current billing block. - * - * Called on DOMContentLoaded and whenever the billing block is reloaded via - * AJAX (e.g. processor switch on a native form, or webform billing step load). - */ - window.civicrmSquareHandleReload = function() { - CRM.squarePayment.scriptName = script.name; - CRM.squarePayment.debugging(script.name, 'HandleReload'); + // Re-init when the billing block is loaded via AJAX (webforms, backend switches) + $(document).ajaxComplete(function(event, xhr, settings) { + if (CRM.squarePayment.isAJAXPaymentForm(settings.url)) { + CRM.squarePayment.debugging(script.name, 'triggered via ajaxComplete'); + load(); + } + }); - // Reset per-reload state so triggerEvent fires correctly after reload - $.each(CRM.squarePayment.scripts, function(name, obj) { - obj.reloadComplete = false; + document.addEventListener('DOMContentLoaded', function() { + CRM.squarePayment.debugging(script.name, 'DOMContentLoaded'); + load(); }); - CRM.squarePayment.form = CRM.squarePayment.getBillingForm(); - if (!CRM.squarePayment.form) { - CRM.squarePayment.debugging(script.name, 'no billing form found'); - return; + function load() { + if (window.civicrmSquareHandleReload) { + CRM.squarePayment.debugging(script.name, 'calling civicrmSquareHandleReload'); + window.civicrmSquareHandleReload(); + } } - $(CRM.squarePayment.getBillingSubmit()).show(); + /** + * (Re-)initialize Square for the current billing block. + * + * Called on DOMContentLoaded and whenever the billing block is reloaded via + * AJAX (e.g. processor switch on a native form, or webform billing step load). + */ + window.civicrmSquareHandleReload = function() { + CRM.squarePayment.scriptName = script.name; + CRM.squarePayment.debugging(script.name, 'HandleReload'); - var cardContainer = document.getElementById('square-card-container'); - if (cardContainer) { - // Always call checkAndLoad — it clears the container and destroys any - // previous card instance before mounting a fresh one. This prevents the - // "card appears twice" issue when switching processors and coming back. - CRM.squarePayment.debugging(script.name, 'mounting Square card element'); - script.checkAndLoad(); - } - else { - // No card container → this form uses a different processor - script.notScriptProcessor(); - CRM.squarePayment.triggerEvent('crmBillingFormReloadComplete', script.name); - } - }; + // Reset per-reload state so triggerEvent fires correctly after reload + $.each(CRM.squarePayment.scripts, function(name, obj) { + obj.reloadComplete = false; + }); + + CRM.squarePayment.form = CRM.squarePayment.getBillingForm(); + if (!CRM.squarePayment.form) { + CRM.squarePayment.debugging(script.name, 'no billing form found'); + return; + } + + $(CRM.squarePayment.getBillingSubmit()).show(); + + var cardContainer = document.getElementById('square-card-container'); + if (cardContainer) { + // Always call checkAndLoad — it clears the container and destroys any + // previous card instance before mounting a fresh one. This prevents the + // "card appears twice" issue when switching processors and coming back. + CRM.squarePayment.debugging(script.name, 'mounting Square card element'); + script.checkAndLoad(); + } + else { + // No card container → this form uses a different processor + script.notScriptProcessor(); + CRM.squarePayment.triggerEvent('crmBillingFormReloadComplete', script.name); + } + }; -}(CRM.$, CRM.ts('org.uschess.square'))); + }(CRM.$, CRM.ts('org.uschess.square'))); diff --git a/managed/PaymentProcessorType.mgd.php b/managed/PaymentProcessorType.mgd.php index 6477c397..6eac662a 100644 --- a/managed/PaymentProcessorType.mgd.php +++ b/managed/PaymentProcessorType.mgd.php @@ -21,18 +21,13 @@ // Public payment-processor class in CRM/Core/Payment/Square.php. 'class_name' => 'Payment_Square', - // Admin form labels (live credentials). + // Admin form labels, for the live and the test credentials alike + // (payment_processor_type has no separate test labels). 'user_name_label' => 'Square Application ID', 'password_label' => 'Square Access Token', 'signature_label' => 'Square Location ID', 'subject_label' => 'Square Webhook Signature Key', - // Admin form labels (test credentials) - 'test_user_name_label' => 'Square Application ID (Test)', - 'test_password_label' => 'Square Access Token (Test)', - 'test_signature_label' => 'Square Location ID (Test)', - 'test_subject_label' => 'Square Webhook Signature Key (Test)', - // Base URLs – we mostly use the SDK, but Civi still likes these sane defaults. // LIVE. 'url_site_default' => 'https://connect.squareup.com', @@ -49,8 +44,8 @@ // 1 = credit card 'payment_type' => 1, - // Capabilities are advertised by CRM_Core_Payment_Square. These fields - // are not valid payment_processor_type managed properties in CiviCRM. + // Supports recurring contributions (see also + // CRM_Core_Payment_Square::supportsRecurring()). 'is_recur' => 1, ], ], diff --git a/review_changes_branch.patch b/review_changes_branch.patch deleted file mode 100644 index 76679a65..00000000 --- a/review_changes_branch.patch +++ /dev/null @@ -1,1735 +0,0 @@ -diff --git a/.gitignore b/.gitignore -new file mode 100644 -index 0000000..d8c5384 ---- /dev/null -+++ b/.gitignore -@@ -0,0 +1,3 @@ -+/tests/phpunit/.phpunit.result.cache -+/tests/phpunit/.phpunit.cache/ -+/.phpunit.result.cache -diff --git a/CRM/Core/Payment/Square.php b/CRM/Core/Payment/Square.php -index ef3db16..2449fb4 100644 ---- a/CRM/Core/Payment/Square.php -+++ b/CRM/Core/Payment/Square.php -@@ -4,6 +4,7 @@ use CRM_Square_ExtensionUtil as E; - use Civi\Api4\Contribution; - use Civi\Api4\Contact; - use Civi\Api4\ContributionRecur; -+use Civi\Api4\Payment; - use Civi\Api4\PaymentToken; - use Civi\Payment\Exception\PaymentProcessorException; - use Civi\Payment\PropertyBag; -@@ -40,6 +41,11 @@ use Square\Refunds\Requests\RefundPaymentRequest; - use Square\Catalog\Requests\BatchUpsertCatalogObjectsRequest; - - require_once E::path() . '/vendor/autoload.php'; -+// Explicit require (rather than relying on CiviCRM's CRM_ classloader, -+// unavailable in the mocked-CiviCRM PHPUnit suite — see tests/phpunit/ -+// bootstrap.php) since callSquare()/squareApiError() below construct this -+// class directly. -+require_once __DIR__ . '/SquareRetryableException.php'; - /** - * Square Payment Processor for CiviCRM. - * -@@ -203,6 +209,11 @@ class CRM_Core_Payment_Square extends CRM_Core_Payment { - - // Enable JS validation so submission only happens after fields are valid. - $form->assign('isJsValidate', TRUE); -+ -+ // We augment the standard billing block rather than replace it, so form -+ // building must continue as normal (CRM_Core_Payment::buildForm()'s -+ // contract: FALSE = "continue normal form building"). -+ return FALSE; - } - - /** -@@ -281,15 +292,37 @@ class CRM_Core_Payment_Square extends CRM_Core_Payment { - } - - /** -- * Resolve a contribution status without relying on installation-specific IDs. */ -+ * Resolve a contribution_status_id by name without relying on installation-specific IDs. -+ */ - protected function contributionStatusId(string $name): int { -- static $statuses = NULL; -- if ($statuses === NULL) { -- $statuses = \CRM_Contribute_PseudoConstant::contributionStatus(); -- } -- $id = array_search($name, $statuses, TRUE); -- if ($id === FALSE) { -- throw new \CRM_Core_Exception("CiviCRM contribution status '{$name}' is unavailable."); -+ return $this->pseudoConstantId('contribution_status_id', $name); -+ } -+ -+ /** -+ * Resolve a payment_instrument_id by name without relying on installation-specific IDs. -+ */ -+ protected function paymentInstrumentId(string $name): int { -+ return $this->pseudoConstantId('payment_instrument_id', $name); -+ } -+ -+ /** -+ * Resolve a financial_type_id by name without relying on installation-specific IDs. -+ */ -+ protected function financialTypeId(string $name): int { -+ return $this->pseudoConstantId('financial_type_id', $name); -+ } -+ -+ /** -+ * Resolve a Contribution-entity 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). -+ */ -+ protected function pseudoConstantId(string $field, string $name): int { -+ $id = \CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', $field, $name); -+ if ($id === FALSE || $id === NULL) { -+ throw new \CRM_Core_Exception("CiviCRM {$field} '{$name}' is unavailable."); - } - return (int) $id; - } -@@ -338,45 +371,54 @@ class CRM_Core_Payment_Square extends CRM_Core_Payment { - $feeAmount = $feeMoney !== NULL ? ($feeMoney / 100) : NULL; - $currency = $money['currency'] ?? 'USD'; - $orderID = $payment['order_id'] ?? NULL; -+ $referenceId = $payment['reference_id'] ?? NULL; - -- // 1. Try to find existing contribution using order id as invoice number, or by -- // trxn_id (Square payment ID). The initial payment of a new subscription is -- // charged directly via doPayment() and only ever gets trxn_id set (no -- // invoice_number/invoice_id), so it must also be matched on trxn_id — otherwise -- // every payment.updated webhook for it fails to find it, falls through to the -- // "create new contribution" branch below, and collides with CiviCRM's own -- // duplicate-transaction guard on trxn_id. -+ // 1. Try to find an existing contribution to reconcile this payment -+ // against, in priority order: -+ // - invoice_id == reference_id: doOneTimePayment() sends CiviCRM's -+ // own invoiceID (civicrm_contribution.invoice_id) as Square's -+ // referenceId when charging, and Square echoes it straight back -+ // on the payment object. This is what ties a contribution CiviCRM -+ // already created as Pending — BEFORE doOneTimePayment() ran, via -+ // the normal Order/Contribution checkout flow — back to this -+ // specific Square payment. Without this match, a webhook arriving -+ // for a payment whose synchronous completion didn't (for whatever -+ // reason) persist trxn_id back onto that Pending contribution -+ // falls through to "create new contribution" below, leaving a -+ // duplicate Completed contribution and an orphaned Pending one. -+ // - trxn_id == payment_id: set once a contribution has already been -+ // completed (synchronously, or by a previous webhook delivery for -+ // the same payment). -+ // - invoice_number == order_id: only ever set on contributions this -+ // webhook handler itself created (see the "create new" branch -+ // below), to match later deliveries of the same event. - $existingQuery = Contribution::get(FALSE) -- ->addSelect('id') -+ ->addSelect('id', 'contribution_status_id', 'total_amount', 'currency') - ->addWhere('is_test', 'IN', [TRUE, FALSE]); -+ $orClauses = [['trxn_id', '=', $paymentId]]; -+ if ($referenceId !== NULL && $referenceId !== '') { -+ $orClauses[] = ['invoice_id', '=', $referenceId]; -+ } - if ($orderID !== NULL) { -- $existingQuery->addClause('OR', ['invoice_number', '=', $orderID], ['trxn_id', '=', $paymentId]); -+ $orClauses[] = ['invoice_number', '=', $orderID]; -+ } -+ if (count($orClauses) === 1) { -+ $existingQuery->addWhere(...$orClauses[0]); - } - else { -- $existingQuery->addWhere('trxn_id', '=', $paymentId); -+ $existingQuery->addClause('OR', ...$orClauses); - } - $existing = $existingQuery->execute()->first(); - - if ($existing) { -- CRM_Core_Payment_SquareDebugLogger::log("Square syncPaymentFromSquare(): found existing contribution {$existing['id']} for payment {$paymentId}, updating."); -- $update = Contribution::update(FALSE) -- ->addWhere('id', '=', $existing['id']) -- ->addValue('total_amount', $amount) -- ->addValue('currency', $currency) -- ->addValue('contribution_status_id', $this->mapPaymentStatus($status)) -- ->addValue('payment_instrument_id', $this->mapPaymentInstrument($sourceType)); -- if ($feeAmount !== NULL) { -- $update->addValue('fee_amount', $feeAmount); -- } -- $update->execute(); -- CRM_Core_Payment_SquareDebugLogger::log("Square syncPaymentFromSquare(): Updated existing contribution {$existing['id']} for payment {$paymentId}."); -+ $this->reconcileExistingContributionPayment($existing, $paymentId, $amount, $currency, $status, $sourceType, $feeAmount); - return; - } - - CRM_Core_Payment_SquareDebugLogger::log("Square syncPaymentFromSquare(): no existing contribution found for payment {$paymentId} (order_id={$orderID}), attempting to create a new one."); - -- // If no contribution exists, try mapping by reference_id → contact or contribution. -- $referenceId = $payment['reference_id'] ?? NULL; -+ // If no contribution exists, try mapping by reference_id → contact (for -+ // recurring payments, where reference_id is the contribution_recur ID). - $contactId = NULL; - - if ($referenceId && ctype_digit((string) $referenceId)) { -@@ -401,8 +443,9 @@ class CRM_Core_Payment_Square extends CRM_Core_Payment { - return; - } - -- // Default financial type is Donation (ID=1) unless better mapping is added later. -- $financialTypeId = 1; -+ // No better mapping available (no recur template) — fall back to the -+ // Donation financial type resolved by name, never a hard-coded ID. -+ $financialTypeId = $this->financialTypeId('Donation'); - - $applicationId = $payment['application_details']['application_id'] ?? ''; - $isTest = str_contains($applicationId, 'sandbox') ? 1 : 0; -@@ -411,24 +454,118 @@ class CRM_Core_Payment_Square extends CRM_Core_Payment { - $financialTypeId = $refRecurContribution['financial_type_id'] ?? $financialTypeId; - } - -+ // Create the contribution Pending, then complete it (if warranted) via -+ // Payment.create so the CiviCRM financial ledger (FinancialTrxn / -+ // EntityFinancialTrxn) is populated correctly — never write a -+ // "Completed" status directly onto the contribution row. - $create = Contribution::create(FALSE) - ->addValue('contact_id', $contactId) - ->addValue('financial_type_id', $financialTypeId) - ->addValue('total_amount', $amount) - ->addValue('currency', $currency) -- ->addValue('contribution_status_id', $this->mapPaymentStatus($status)) -- ->addValue('payment_instrument_id', $this->mapPaymentInstrument($sourceType)) -+ ->addValue('contribution_status_id', $this->contributionStatusId('Pending')) - ->addValue('trxn_id', $paymentId) - ->addValue('is_test', $isTest) - ->addValue('source', 'Square Payment (Webhook)'); -- if ($feeAmount !== NULL) { -- $create->addValue('fee_amount', $feeAmount); -- } - if ($orderID !== NULL) { - $create->addValue('invoice_number', $orderID); - } - $newContribution = $create->execute()->first(); -- CRM_Core_Payment_SquareDebugLogger::log("Square syncPaymentFromSquare(): Created new contribution {$newContribution['id']} for payment {$paymentId}, contact {$contactId}."); -+ $newContributionId = (int) $newContribution['id']; -+ -+ if ($this->mapPaymentStatus($status) === $this->contributionStatusId('Completed')) { -+ $this->completeContributionPayment($newContributionId, $amount, $paymentId, $this->mapPaymentInstrument($sourceType), $feeAmount); -+ CRM_Core_Payment_SquareDebugLogger::log("Square syncPaymentFromSquare(): Created and completed contribution {$newContributionId} for payment {$paymentId}, contact {$contactId}."); -+ } -+ else { -+ CRM_Core_Payment_SquareDebugLogger::log("Square syncPaymentFromSquare(): Created Pending contribution {$newContributionId} for payment {$paymentId} (status {$status}), contact {$contactId}."); -+ } -+ } -+ -+ /** -+ * Reconcile a Square payment against an existing CiviCRM contribution. -+ * -+ * Amount/currency mismatches are never silently corrected — they are -+ * logged as reconciliation errors requiring manual review, preserving -+ * whatever line items and financial allocations the contribution already -+ * has. Completion is only ever recorded via Payment.create so the -+ * financial ledger stays accurate. -+ * -+ * @param array $existing -+ * Contribution row with id, contribution_status_id, total_amount, currency. -+ * @param string $paymentId -+ * Square payment ID. -+ * @param float|null $amount -+ * Amount Square reports for this payment, in dollars. -+ * @param string $currency -+ * Currency Square reports for this payment. -+ * @param string $status -+ * Square payment status (e.g. COMPLETED, PENDING). -+ * @param string|null $sourceType -+ * Square source_type (CARD, BANK_ACCOUNT, etc), for payment_instrument_id mapping. -+ * @param float|null $feeAmount -+ * Processing fee Square reports, in dollars, if any. -+ */ -+ protected function reconcileExistingContributionPayment(array $existing, string $paymentId, ?float $amount, string $currency, string $status, ?string $sourceType, ?float $feeAmount): void { -+ $contributionId = (int) $existing['id']; -+ -+ if ($amount !== NULL && round((float) $existing['total_amount'], 2) !== round($amount, 2)) { -+ Civi::log()->error("Square syncPaymentFromSquare(): amount mismatch for contribution {$contributionId} (payment {$paymentId}): CiviCRM has {$existing['total_amount']} {$existing['currency']}, Square reports {$amount} {$currency}. Not modifying — requires manual reconciliation."); -+ return; -+ } -+ if (!empty($existing['currency']) && strcasecmp((string) $existing['currency'], $currency) !== 0) { -+ Civi::log()->error("Square syncPaymentFromSquare(): currency mismatch for contribution {$contributionId} (payment {$paymentId}): CiviCRM has {$existing['currency']}, Square reports {$currency}. Not modifying — requires manual reconciliation."); -+ return; -+ } -+ -+ $completedStatusId = $this->contributionStatusId('Completed'); -+ if ((int) $existing['contribution_status_id'] === $completedStatusId) { -+ CRM_Core_Payment_SquareDebugLogger::log("Square syncPaymentFromSquare(): contribution {$contributionId} already Completed for payment {$paymentId}, skipping."); -+ return; -+ } -+ -+ if ($this->mapPaymentStatus($status) !== $completedStatusId) { -+ CRM_Core_Payment_SquareDebugLogger::log("Square syncPaymentFromSquare(): payment {$paymentId} status '{$status}' does not indicate completion, leaving contribution {$contributionId} unchanged."); -+ return; -+ } -+ -+ $this->completeContributionPayment( -+ $contributionId, -+ $amount ?? (float) $existing['total_amount'], -+ $paymentId, -+ $this->mapPaymentInstrument($sourceType), -+ $feeAmount -+ ); -+ CRM_Core_Payment_SquareDebugLogger::log("Square syncPaymentFromSquare(): completed contribution {$contributionId} for payment {$paymentId} via Payment.create."); -+ } -+ -+ /** -+ * Complete a Pending contribution's payment via CiviCRM's Payment.create. -+ * -+ * This creates FinancialTrxn/EntityFinancialTrxn ledger rows and runs -+ * CRM_Contribute_BAO_Contribution::completeOrder() as it would for any -+ * other payment processor. -+ * -+ * @throws \CRM_Core_Exception -+ */ -+ protected function completeContributionPayment(int $contributionId, float $amount, string $trxnId, ?int $paymentInstrumentId = NULL, ?float $feeAmount = NULL, ?string $receiveDate = NULL): void { -+ $create = Payment::create(FALSE) -+ ->addValue('contribution_id', $contributionId) -+ ->addValue('total_amount', $amount) -+ ->addValue('trxn_id', $trxnId); -+ if ($paymentInstrumentId !== NULL) { -+ $create->addValue('payment_instrument_id', $paymentInstrumentId); -+ } -+ if ($feeAmount !== NULL) { -+ $create->addValue('fee_amount', $feeAmount); -+ } -+ if ($receiveDate !== NULL) { -+ $create->addValue('trxn_date', $receiveDate); -+ } -+ if (!empty($this->_paymentProcessor['id'])) { -+ $create->addValue('payment_processor_id', (int) $this->_paymentProcessor['id']); -+ } -+ $create->execute(); - } - - /** -@@ -439,11 +576,23 @@ class CRM_Core_Payment_Square extends CRM_Core_Payment { - public function syncRefundFromSquare(array $refund) { - $paymentId = $refund['payment_id'] ?? NULL; - $refundId = $refund['id'] ?? NULL; -- CRM_Core_Payment_SquareDebugLogger::log("Square syncRefundFromSquare(): called from SquareIPN for refund_id={$refundId}, payment_id={$paymentId}."); -+ $refundStatus = strtoupper(trim($refund['status'] ?? '')); -+ CRM_Core_Payment_SquareDebugLogger::log("Square syncRefundFromSquare(): called from SquareIPN for refund_id={$refundId}, payment_id={$paymentId}, status={$refundStatus}."); - if (!$paymentId || !$refundId) { - CRM_Core_Payment_SquareDebugLogger::log('Square syncRefundFromSquare(): missing payment_id or refund_id, skipping.'); - return; - } -+ if (!in_array($refundStatus, ['COMPLETED', 'APPROVED'], TRUE)) { -+ CRM_Core_Payment_SquareDebugLogger::log("Square syncRefundFromSquare(): refund {$refundId} not yet settled (status={$refundStatus}), skipping until it completes."); -+ return; -+ } -+ -+ $money = $refund['amount_money'] ?? NULL; -+ $refundAmount = ($money && isset($money['amount'])) ? ((float) $money['amount'] / 100) : NULL; -+ if ($refundAmount === NULL || $refundAmount <= 0) { -+ Civi::log()->error("Square syncRefundFromSquare(): refund {$refundId} for payment {$paymentId} has no usable amount, skipping."); -+ return; -+ } - - // Find contribution by trxn_id. - $contribution = Contribution::get(FALSE) -@@ -457,16 +606,47 @@ class CRM_Core_Payment_Square extends CRM_Core_Payment { - CRM_Core_Payment_SquareDebugLogger::log("Square syncRefundFromSquare(): no contribution found for payment {$paymentId}, skipping."); - return; - } -+ $contributionId = (int) $contribution['id']; - -- CRM_Core_Payment_SquareDebugLogger::log("Square syncRefundFromSquare(): found contribution {$contribution['id']} for payment {$paymentId}, marking Refunded."); -+ // Idempotency: a replayed refund.created webhook must not double-refund. -+ $alreadyRecorded = civicrm_api3('Payment', 'get', [ -+ 'entity_id' => $contributionId, -+ 'trxn_id' => $refundId, -+ 'options' => ['limit' => 1], -+ ])['count'] ?? 0; -+ if (!empty($alreadyRecorded)) { -+ CRM_Core_Payment_SquareDebugLogger::log("Square syncRefundFromSquare(): refund {$refundId} already recorded for contribution {$contributionId}, skipping."); -+ return; -+ } - -- Contribution::update(FALSE) -- ->addWhere('id', '=', $contribution['id']) -- ->addValue('contribution_status_id', 'Refunded') -- ->addValue('refund_trxn_id', $refundId) -- ->execute(); -+ // Find the original payment being refunded so we can link the refund to -+ // it via cancelled_payment_id, matching CiviCRM's own Payment.cancel -+ // behaviour (api/v3/Payment.php civicrm_api3_payment_cancel()). -+ $originalPayments = civicrm_api3('Payment', 'get', [ -+ 'entity_id' => $contributionId, -+ 'trxn_id' => $paymentId, -+ 'options' => ['limit' => 1, 'sort' => 'id DESC'], -+ ])['values'] ?? []; -+ $originalPaymentId = !empty($originalPayments) ? (int) array_key_first($originalPayments) : NULL; -+ -+ if (!$originalPaymentId) { -+ Civi::log()->error("Square syncRefundFromSquare(): could not find the original Payment record for contribution {$contributionId}, payment {$paymentId}. Cannot record refund {$refundId} unambiguously — requires manual reconciliation."); -+ return; -+ } -+ -+ // Record the refund as a negative payment linked to the original -+ // payment. cancelled_payment_id is only accepted by the API3 action — -+ // API4 Payment::create does not declare it as a writable field — and -+ // the contribution_status_id transition to Refunded/Partially paid is -+ // handled automatically by CRM_Financial_BAO_Payment::create(). -+ civicrm_api3('Payment', 'create', [ -+ 'contribution_id' => $contributionId, -+ 'total_amount' => -$refundAmount, -+ 'trxn_id' => $refundId, -+ 'cancelled_payment_id' => $originalPaymentId, -+ ]); - -- CRM_Core_Payment_SquareDebugLogger::log("Square syncRefundFromSquare(): Updated contribution {$contribution['id']} as Refunded for refund {$refundId}."); -+ CRM_Core_Payment_SquareDebugLogger::log("Square syncRefundFromSquare(): recorded refund {$refundId} ({$refundAmount}) against contribution {$contributionId}, cancelling payment {$originalPaymentId}."); - } - - /** -@@ -519,61 +699,15 @@ class CRM_Core_Payment_Square extends CRM_Core_Payment { - /** - * Sync a Square invoice (recurring payment) into CiviCRM. - * -+ * Not currently called by any webhook route (invoice.payment_made is -+ * handled by handleInvoicePaymentCreated() instead) but kept as public -+ * API surface, so it delegates to the same ledger-safe path rather than -+ * duplicating the old direct-Completed-contribution logic. -+ * - * @param array $invoice - */ - public function syncInvoiceFromSquare(array $invoice) { -- $invoiceId = $invoice['id'] ?? NULL; -- if (!$invoiceId) { -- CRM_Core_Payment_SquareDebugLogger::log('Square syncInvoiceFromSquare(): missing invoice ID.'); -- return; -- } -- -- $subscriptionId = $invoice['subscription_id'] ?? NULL; -- if (!$subscriptionId) { -- CRM_Core_Payment_SquareDebugLogger::log("Square syncInvoiceFromSquare(): invoice {$invoiceId} has no subscription_id."); -- return; -- } -- -- // Find recur. -- $recur = ContributionRecur::get(FALSE) -- ->addSelect('id', 'contact_id', 'financial_type_id', 'currency', 'is_test') -- ->addWhere('processor_id', '=', $subscriptionId) -- ->addWhere('is_test', 'IN', [TRUE, FALSE]) -- ->execute() -- ->first(); -- -- if (!$recur) { -- CRM_Core_Payment_SquareDebugLogger::log("Square syncInvoiceFromSquare(): no recur for subscription {$subscriptionId}"); -- return; -- } -- -- // Prevent duplicates. -- $existing = Contribution::get(FALSE) -- ->addSelect('id') -- ->addWhere('invoice_id', '=', $invoiceId) -- ->addWhere('is_test', 'IN', [TRUE, FALSE]) -- ->execute() -- ->first(); -- -- if ($existing) { -- return; -- } -- -- $money = $invoice['payment_requests'][0]['computed_amount_money'] ?? NULL; -- $amount = $money ? ($money['amount'] / 100) : NULL; -- $currency = $money['currency'] ?? $recur['currency'] ?? 'USD'; -- -- Contribution::create(FALSE) -- ->addValue('contact_id', $recur['contact_id']) -- ->addValue('contribution_recur_id', $recur['id']) -- ->addValue('financial_type_id', $recur['financial_type_id']) -- ->addValue('total_amount', $amount) -- ->addValue('currency', $currency) -- ->addValue('contribution_status_id', 1) -- ->addValue('invoice_id', $invoiceId) -- ->addValue('is_test', $recur['is_test']) -- ->addValue('source', 'Square Invoice (Webhook)') -- ->execute(); -+ $this->handleInvoicePaymentCreated(['data' => ['object' => ['invoice' => $invoice]]]); - } - - /** -@@ -666,31 +800,25 @@ class CRM_Core_Payment_Square extends CRM_Core_Payment { - protected function mapSquareSubscriptionStatusToCivi($squareStatus) { - $squareStatus = strtoupper(trim($squareStatus)); - -- // CiviCRM contribution_status_id values used by this extension for -- // contribution_recur: 1 = Completed, 2 = Pending, 3 = Cancelled, -- // 4 = Failed, 5 = In Progress. -+ // Square subscription statuses per the Subscriptions API: PENDING, -+ // ACTIVE, CANCELED, DEACTIVATED, PAUSED, and (API versions -+ // 2025-09-24+) COMPLETED. There is no SUSPENDED status. - switch ($squareStatus) { -+ case 'PENDING': -+ case 'PAUSED': -+ return $this->contributionStatusId('Pending'); -+ - case 'ACTIVE': -- // In Progress. -- return 5; -+ return $this->contributionStatusId('In Progress'); - -- case 'CANCELED': -- case 'DEACTIVATED': -- // Cancelled. -- return 3; -+ case 'COMPLETED': -+ return $this->contributionStatusId('Completed'); - -- case 'SUSPENDED': -- // Failed / On Hold. -- return 4; -+ case 'CANCELED': -+ return $this->contributionStatusId('Cancelled'); - -- case 'PENDING': -- // Square subscriptions report PENDING until their start_date is -- // reached (we deliberately set start_date to tomorrow — see -- // doRecurPayment()), even when we've already charged and recorded -- // a successful initial payment and marked the recur In Progress. -- // Don't let this calendar-based status downgrade a recurring -- // record that already has a completed payment back to Pending. -- return NULL; -+ case 'DEACTIVATED': -+ return $this->contributionStatusId('Failed'); - } - - // If unknown, don't change local status. -@@ -717,9 +845,9 @@ class CRM_Core_Payment_Square extends CRM_Core_Payment { - * Determine financial_type_id for contributions created by Square. - * - * Priority: -- * 1. Contribution params (financialTypeID / financial_type_id) -- * 2. Recurring template on contribution_recur -- * 3. System default (Donation = 1) -+ * 1. Contribution params (financialTypeID / financial_type_id). -+ * 2. Recurring template on contribution_recur. -+ * 3. "Donation", resolved by name. - * - * @param array $params - * -@@ -748,8 +876,10 @@ class CRM_Core_Payment_Square extends CRM_Core_Payment { - } - } - -- // 3. Fallback to Donation (ID=1) -- return 1; -+ // 3. Fallback to Donation, resolved by name — never a hard-coded ID, -+ // which is not stable across CiviCRM installs. -+ CRM_Core_Payment_SquareDebugLogger::log('Square getFinancialTypeId(): no financial type resolved from params or recurring template; falling back to Donation.'); -+ return $this->financialTypeId('Donation'); - } - - /** -@@ -809,9 +939,9 @@ class CRM_Core_Payment_Square extends CRM_Core_Payment { - return; - } - -- $contactId = (int) $recur['contact_id']; - $recurId = (int) $recur['id']; -- $paymentInstrumentId = $recur['payment_instrument_id'] ?? 1; -+ $paymentInstrumentId = $recur['payment_instrument_id'] ?? $this->paymentInstrumentId('Credit Card'); -+ $completedStatusId = $this->contributionStatusId('Completed'); - - // Check for duplicate contribution by invoice ID. - $existing = Contribution::get(FALSE) -@@ -827,58 +957,100 @@ class CRM_Core_Payment_Square extends CRM_Core_Payment { - - // Check record exist and status completed and recurring is linked. - if (!empty($existing)) { -- if ($existing['contribution_status_id'] == 1 && !empty($existing['contribution_recur_id'])) { -+ if ((int) $existing['contribution_status_id'] === $completedStatusId && !empty($existing['contribution_recur_id'])) { - CRM_Core_Payment_SquareDebugLogger::log("Square webhook: Invoice {$invoiceId} already processed as contribution {$existing['id']}."); - return; - } -- else { -- CRM_Core_Payment_SquareDebugLogger::log("Square webhook: Updating existing contribution {$existing['id']} for invoice {$invoiceId} (subscription {$subscriptionId})."); -- Contribution::update(FALSE) -- ->addWhere('id', '=', $existing['id']) -- ->addValue('total_amount', $amount) -- ->addValue('currency', $currency) -- ->addValue('receive_date', $receiveDate) -- ->addValue('contribution_status_id', 1) -- ->addValue('contribution_recur_id', $recurId) -- ->addValue('payment_instrument_id', $paymentInstrumentId) -- ->execute(); -- try { -- CRM_Contribute_BAO_ContributionRecur::updateOnNewPayment($recurId, 'Completed'); -- } -- catch (Exception $e) { -- Civi::log()->error("Square webhook: Failed to update contribution recur {$recurId} after processing invoice {$invoiceId}: " . $e->getMessage()); -- } -- return; -+ -+ // Complete the existing (Pending) contribution via Payment.create so -+ // the financial ledger (FinancialTrxn/EntityFinancialTrxn) is -+ // populated correctly — never write "Completed" directly onto the -+ // contribution row. -+ $this->completeContributionPayment((int) $existing['id'], $amount, $invoiceId, $paymentInstrumentId, NULL, $receiveDate); -+ try { -+ CRM_Contribute_BAO_ContributionRecur::updateOnNewPayment($recurId, 'Completed'); -+ } -+ catch (\Throwable $e) { -+ Civi::log()->error("Square webhook: Failed to update contribution recur {$recurId} after processing invoice {$invoiceId}: " . $e->getMessage()); -+ } -+ CRM_Core_Payment_SquareDebugLogger::log("Square webhook: Completed existing contribution {$existing['id']} for invoice {$invoiceId} (subscription {$subscriptionId})."); -+ return; -+ } -+ -+ // No contribution matched by invoice_id — for a brand-new -+ // subscription's first invoice there's nothing to match on yet -+ // (Square only assigns an invoice_id once billing starts), but -+ // CiviCRM already created a Pending contribution for this recur at -+ // signup time, before doRecurPayment() ever ran. Complete THAT one -+ // instead of cloning a fresh one via repeattransaction() below — -+ // otherwise the signup-time contribution is orphaned forever while a -+ // duplicate gets created here. Same failure mode as the one-time -+ // flow fixed via invoice_id/reference_id matching in -+ // syncPaymentFromSquare(). This can only ever match the very first -+ // invoice: every contribution repeattransaction() creates gets -+ // invoice_id set immediately after (below), so it's excluded from -+ // this lookup on any later billing cycle. -+ $initialPending = Contribution::get(FALSE) -+ ->addSelect('id') -+ ->addWhere('contribution_recur_id', '=', $recurId) -+ ->addWhere('contribution_status_id', '=', $this->contributionStatusId('Pending')) -+ ->addWhere('invoice_id', 'IS EMPTY') -+ ->addWhere('is_test', 'IN', [TRUE, FALSE]) -+ ->addOrderBy('id', 'ASC') -+ ->setLimit(1) -+ ->execute() -+ ->first(); -+ -+ if (!empty($initialPending)) { -+ $initialContributionId = (int) $initialPending['id']; -+ Contribution::update(FALSE) -+ ->addWhere('id', '=', $initialContributionId) -+ ->addValue('invoice_id', $invoiceId) -+ ->execute(); -+ $this->completeContributionPayment($initialContributionId, $amount, $invoiceId, $paymentInstrumentId, NULL, $receiveDate); -+ try { -+ CRM_Contribute_BAO_ContributionRecur::updateOnNewPayment($recurId, 'Completed'); - } -+ catch (\Throwable $e) { -+ Civi::log()->error("Square webhook: Failed to update contribution recur {$recurId} after processing invoice {$invoiceId}: " . $e->getMessage()); -+ } -+ CRM_Core_Payment_SquareDebugLogger::log("Square webhook: Completed signup-time contribution {$initialContributionId} for invoice {$invoiceId} (subscription {$subscriptionId})."); -+ return; - } - -- // Determine financial type ID. -- $financialTypeId = $this->getFinancialTypeId([ -- 'contributionRecurID' => $recurId, -+ // No existing contribution at all — clone one from the recurring -+ // template via CiviCRM's own repeat-transaction flow (preserves line -+ // items and financial allocations), left Pending by default, then -+ // complete it via Payment.create. This is the normal path for the -+ // second and subsequent billing cycles. -+ $repeatResult = civicrm_api3('Contribution', 'repeattransaction', [ -+ 'contribution_recur_id' => $recurId, -+ 'trxn_id' => $invoiceId, -+ 'total_amount' => $amount, -+ 'receive_date' => $receiveDate, - ]); -+ $newContributionId = (int) ($repeatResult['id'] ?? 0); -+ if (!$newContributionId) { -+ Civi::log()->error("Square webhook: Contribution.repeattransaction did not return a contribution ID for invoice {$invoiceId} (subscription {$subscriptionId})."); -+ return; -+ } - -- // Create new completed contribution. -- Contribution::create(FALSE) -- ->addValue('contact_id', $contactId) -- ->addValue('financial_type_id', $financialTypeId) -- ->addValue('total_amount', $amount) -- ->addValue('currency', $currency) -- ->addValue('receive_date', $receiveDate) -- ->addValue('contribution_recur_id', $recurId) -- ->addValue('contribution_status_id', 1) -- ->addValue('payment_instrument_id', $paymentInstrumentId) -+ // repeattransaction() doesn't accept invoice_id — set it separately so -+ // future webhook deliveries for this invoice can find the contribution. -+ Contribution::update(FALSE) -+ ->addWhere('id', '=', $newContributionId) - ->addValue('invoice_id', $invoiceId) -- ->addValue('is_test', $recur['is_test']) -- ->addValue('source', 'Square Recurring Payment') - ->execute(); - -+ $this->completeContributionPayment($newContributionId, $amount, $invoiceId, $paymentInstrumentId, NULL, $receiveDate); -+ - try { - CRM_Contribute_BAO_ContributionRecur::updateOnNewPayment($recurId, 'Completed'); - } -- catch (Exception $e) { -+ catch (\Throwable $e) { - Civi::log()->error("Square webhook: Failed to update contribution recur {$recurId} after processing invoice {$invoiceId}: " . $e->getMessage()); - } -- CRM_Core_Payment_SquareDebugLogger::log("Square webhook: Created contribution for invoice {$invoiceId} (subscription {$subscriptionId})."); -+ CRM_Core_Payment_SquareDebugLogger::log("Square webhook: Created and completed contribution {$newContributionId} for invoice {$invoiceId} (subscription {$subscriptionId})."); - } - - /** -@@ -989,7 +1161,19 @@ class CRM_Core_Payment_Square extends CRM_Core_Payment { - * @throws \CRM_Core_Exception - */ - protected function doOneTimePayment(&$params) { -- // 1. Extract Web Payments SDK token. -+ // 1. Determine amount and currency first — a zero-amount contribution -+ // (e.g. a 100%-discount code) needs no card at all, so it must not be -+ // rejected for lacking a Square token. -+ $amount = $params['amount'] ?? $params['total_amount'] ?? NULL; -+ if ($amount === NULL || $amount === '') { -+ throw new \CRM_Core_Exception('Missing contribution amount.'); -+ } -+ -+ if ((float) $amount === 0.0) { -+ return $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'] -@@ -1006,21 +1190,27 @@ class CRM_Core_Payment_Square extends CRM_Core_Payment { - // Persist it back into $params so downstream code can see it. - $params['square_payment_token'] = $token; - -- // 2. Determine amount and currency. -- $amount = $params['amount'] ?? $params['total_amount'] ?? NULL; -- if ($amount === NULL || $amount === '') { -- throw new \CRM_Core_Exception('Missing contribution amount.'); -- } -- -- if ((float) $amount === 0.0) { -- return $params; -- } -- - $amountCents = (int) round(((float) $amount) * 100); - $currency = $params['currency'] ?? $params['currencyID'] ?? 'USD'; - -- // 3. Idempotency key. -- $idempotencyKey = $this->idempotencyKey('payment', (string) ($params['invoiceID'] ?? $params['invoice_id'] ?? $params['contributionID'] ?? $params['contribution_id'] ?? 'unknown')); -+ // 3. Idempotency key. The previous fallback was the shared literal -+ // 'unknown' when no invoice/contribution reference was available — -+ // meaning any two payments both missing a reference would collide on -+ // the exact same idempotency key, and Square would silently treat the -+ // second as a duplicate of the first rather than charging it. A -+ // per-call-random reference can never collide with a different -+ // payment; it just can't protect that specific request against a -+ // network-level client retry (no stable reference exists to retry -+ // against), which is the same behaviour this fallback always had. -+ $paymentReference = $params['invoiceID'] ?? $params['invoice_id'] ?? $params['contributionID'] ?? $params['contribution_id'] ?? NULL; -+ if ($paymentReference === NULL || $paymentReference === '') { -+ // No stable reference available — a per-call random one can never -+ // collide with a different payment, unlike the previous literal -+ // 'unknown' fallback, but (like that fallback) can't protect this -+ // specific request against a client-level network retry either. -+ $paymentReference = bin2hex(random_bytes(16)); -+ } -+ $idempotencyKey = $this->idempotencyKey('payment', (string) $paymentReference); - - // 4. Build payload for CreatePayment. - $requestValues = [ -@@ -1052,11 +1242,61 @@ class CRM_Core_Payment_Square extends CRM_Core_Payment { - } - - $trxnId = $payment->getId(); -+ $squareStatus = $payment->getStatus() ?? 'UNKNOWN'; -+ $mappedStatusId = $this->mapPaymentStatus($squareStatus); -+ $completedStatusId = $this->contributionStatusId('Completed'); - -- // 6. Set required CiviCRM transaction fields. -+ // 6. Set transaction fields so CiviCRM's caller and any later -+ // payment.updated webhook can both reference this payment. - $params['trxn_id'] = $trxnId; -- $params['payment_status_id'] = $this->contributionStatusId('Completed'); -- $params['contribution_status_id'] = $this->contributionStatusId('Completed'); -+ -+ if ($mappedStatusId === $completedStatusId) { -+ // Square already confirmed this payment as settled within the same -+ // request (the common case — captured immediately) — complete the -+ // contribution's ledger right now instead of waiting on the -+ // asynchronous webhook, which may be delayed, or may never arrive -+ // if this environment's CiviCRM cron isn't reliably running the -+ // webhook backstop job. -+ // -+ // If CiviCRM's own calling code ALSO completes this contribution -+ // from the status/trxn_id returned below (the standard front-end -+ // payment-processor contract), that second attempt will find the -+ // contribution already Completed and throw -+ // "Contribution already completed" from -+ // CRM_Financial_BAO_Payment::create() — harmless here (swallowed -+ // below), since the ledger is already correct either way. A later -+ // payment.updated webhook for the same trxn_id is likewise a safe -+ // no-op (see reconcileExistingContributionPayment()). -+ $contributionId = $params['contributionID'] ?? $params['contribution_id'] ?? NULL; -+ if ($contributionId) { -+ try { -+ $processingFees = $payment->getProcessingFee() ?? []; -+ $feeAmount = !empty($processingFees[0]) && $processingFees[0]->getAmountMoney() -+ ? ((float) $processingFees[0]->getAmountMoney()->getAmount()) / 100 -+ : NULL; -+ $this->completeContributionPayment( -+ (int) $contributionId, -+ (float) $amount, -+ $trxnId, -+ $this->mapPaymentInstrument($payment->getSourceType()), -+ $feeAmount -+ ); -+ } -+ catch (\Throwable $e) { -+ CRM_Core_Payment_SquareDebugLogger::log("Square doOneTimePayment(): self-completion for contribution {$contributionId} (trxn {$trxnId}) did not apply, presumably already completed: " . $e->getMessage()); -+ } -+ } -+ $params['payment_status_id'] = $completedStatusId; -+ $params['contribution_status_id'] = $completedStatusId; -+ } -+ else { -+ // Authorized but not yet captured/settled (e.g. a delayed-capture -+ // hold) — leave the contribution Pending. The payment.updated -+ // webhook will complete it once Square reports COMPLETED. -+ $pendingStatusId = $this->contributionStatusId('Pending'); -+ $params['payment_status_id'] = $pendingStatusId; -+ $params['contribution_status_id'] = $pendingStatusId; -+ } - - return $params; - } -@@ -1141,12 +1381,7 @@ class CRM_Core_Payment_Square extends CRM_Core_Payment { - // 5. Determine plan ID - $planVariationId = $this->getPlanVariationIdForParams($params); - CRM_Core_Payment_SquareDebugLogger::log("Square doRecurPayment: Using plan variation ID {$planVariationId} for CiviCRM recur ID {$recurId}"); -- // 6. Determine start date (Square-safe) -- // Square rejects same-day start if UTC has rolled to next day. -- // To avoid timezone hell: always start tomorrow. -- $startDate = (new DateTime('tomorrow'))->format('Y-m-d'); -- -- // 7. Generate idempotency key tied to the recurring record so re-posts don't duplicate. -+ // 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'] ?? ''), -@@ -1156,18 +1391,25 @@ class CRM_Core_Payment_Square extends CRM_Core_Payment { - // convert array to string with maintain key value. - $note = json_encode($source, JSON_UNESCAPED_SLASHES); - -- // 8. Build subscription payload -+ // 7. Build subscription payload. startDate is deliberately omitted — -+ // Square defaults it to "today" in the location's timezone, and Square -+ // bills the first invoice ON start_date. Previously this code set -+ // start_date to "tomorrow" AND made a separate immediate CreatePayment -+ // call for "today", which double-charges the donor once Square's own -+ // invoice for tomorrow is paid. The initial charge is now handled -+ // exactly once, entirely by Square's subscription billing, confirmed -+ // asynchronously via the invoice.payment_made webhook (see -+ // handleInvoicePaymentCreated()). - $createSubscriptionRequest = new CreateSubscriptionRequest([ - 'idempotencyKey' => $idempotencyKey, - 'locationId' => $this->getLocationId(), - 'planVariationId' => $planVariationId, - 'customerId' => $customerId, - 'cardId' => $cardId, -- 'startDate' => $startDate, - 'source' => new SubscriptionSource(['name' => $note]), - ]); - -- // 9. Send subscription create request -+ // 8. Send subscription create request - $response = $this->callSquare(fn (SquareClient $client) => $client->subscriptions->create($createSubscriptionRequest)); - $subscription = $response->getSubscription(); - -@@ -1180,72 +1422,23 @@ class CRM_Core_Payment_Square extends CRM_Core_Payment { - 'recur_id' => $recurId, - ])); - -- // 10. Handle initial payment (if needed) -- // Square subscriptions don't charge on creation, they start on start_date. -- // If the user wants to charge immediately, we need to make a one-time payment. -- $initialPaymentNeeded = !empty($params['send_receipt']) || !empty($params['is_recur']); -- -- if ($initialPaymentNeeded) { -- $amountCents = (int) round(((float) $amount) * 100); -- $currency = $params['currency'] ?? $params['currencyID'] ?? 'USD'; -- try { -- // Make an initial one-time payment for the first billing cycle. -- // Use a distinct operation name (rather than prefixing $idempotencyKey, -- // which is already truncated to Square's 45-char max) so this stays <= 45 chars. -- $initialPaymentIdempotencyKey = $this->idempotencyKey('subscription-init', (string) $recurId); -- $initialPaymentRequest = new CreatePaymentRequest([ -- 'idempotencyKey' => $initialPaymentIdempotencyKey, -- 'sourceId' => $cardId, -- 'amountMoney' => new Money(['amount' => $amountCents, 'currency' => $currency]), -- 'locationId' => $this->getLocationId(), -- 'customerId' => $customerId, -- 'referenceId' => (string) $recurId, -- ]); -- -- $paymentResponse = $this->callSquare(fn (SquareClient $client) => $client->payments->create($initialPaymentRequest)); -- $initialPayment = $paymentResponse->getPayment(); -- if (!empty($initialPayment) && !empty($initialPayment->getId())) { -- $transactionId = $initialPayment->getId(); -- $status = $initialPayment->getStatus() ?? 'UNKNOWN'; -- ContributionRecur::update(FALSE) -- ->addWhere('id', '=', $recurId) -- ->addValue('processor_id', $subscriptionId) -- ->addValue('trxn_id', $subscriptionId) -- // In Progress. -- ->addValue('contribution_status_id', 5) -- ->execute(); -- CRM_Core_Payment_SquareDebugLogger::log("Square initial payment for subscription {$subscriptionId} created with transaction ID {$transactionId} and status {$status}"); -- return [ -- // Completed. -- 'payment_status_id' => 1, -- // Completed. -- 'contribution_status_id' => 1, -- 'trxn_id' => $transactionId, -- 'subscription_id' => $subscriptionId, -- ]; -- } -- } -- catch (Exception $e) { -- // Log but don't fail - subscription is already created. -- CRM_Core_Payment_SquareDebugLogger::log('Square initial payment failed (non-fatal): ' . $e->getMessage()); -- } -- } -- -- // 11. Update the recurring contribution record -+ // 9. Record the subscription on the recurring contribution. Leave it -+ // Pending — Square has not charged anything yet. The first successful -+ // charge is confirmed via the invoice.payment_made webhook, which -+ // completes both this recurring record (via updateOnNewPayment()) and -+ // the initial contribution (via Payment.create). - ContributionRecur::update(FALSE) - ->addWhere('id', '=', $recurId) - ->addValue('processor_id', $subscriptionId) - ->addValue('trxn_id', $subscriptionId) -- // Pending. -- ->addValue('contribution_status_id', 2) -+ ->addValue('contribution_status_id', $this->contributionStatusId('Pending')) - ->execute(); - -- // 12. Return CiviCRM-standard response -+ // 10. Return CiviCRM-standard response: the initial contribution stays -+ // Pending until Square confirms the charge via webhook. - return [ -- // Pending. -- 'payment_status_id' => 2, -- // Pending. -- 'contribution_status_id' => 2, -+ 'payment_status_id' => $this->contributionStatusId('Pending'), -+ 'contribution_status_id' => $this->contributionStatusId('Pending'), - 'trxn_id' => $subscriptionId, - 'subscription_id' => $subscriptionId, - ]; -@@ -1354,13 +1547,22 @@ class CRM_Core_Payment_Square extends CRM_Core_Payment { - throw $this->squareApiError($e); - } - catch (SquareException $e) { -- throw new CRM_Core_Exception('Square API request failed: ' . $e->getMessage()); -+ // 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()); - } - } - - /** - * Convert a Square SDK API exception to the message shape callers expect. - * -+ * HTTP 5xx and 429 are treated as transient (Square-side outage or rate -+ * limiting) so webhook processing retries them; 4xx (other than 429) -+ * indicates a malformed/rejected request that will fail identically on -+ * retry, so it is treated as permanent. -+ * - * @param \Square\Exceptions\SquareApiException $e - * - * @return \CRM_Core_Exception -@@ -1372,11 +1574,15 @@ class CRM_Core_Payment_Square extends CRM_Core_Payment { - $detail = $err->getDetail() ?? ''; - $errorDetails[] = "{$code}: {$detail}"; - } -- $msg = "Square API returned HTTP {$e->getStatusCode()}."; -+ $statusCode = $e->getStatusCode(); -+ $msg = "Square API returned HTTP {$statusCode}."; - if ($errorDetails) { - $msg .= ' ' . implode(' | ', $errorDetails); - } -- return new CRM_Core_Exception($msg); -+ $exceptionClass = ($statusCode >= 500 || $statusCode === 429) -+ ? CRM_Core_Payment_SquareRetryableException::class -+ : CRM_Core_Exception::class; -+ return new $exceptionClass($msg); - } - - /** -@@ -1549,7 +1755,7 @@ class CRM_Core_Payment_Square extends CRM_Core_Payment { - return $migratedCustomerId; - } - } -- catch (\Exception $e) { -+ catch (\Throwable $e) { - CRM_Core_Payment_SquareDebugLogger::log('Square migration lookup error: ' . $e->getMessage()); - } - $existingCustomerId = $this->getSquareCustomerId($contactID); -@@ -1682,7 +1888,11 @@ class CRM_Core_Payment_Square extends CRM_Core_Payment { - } - - $requestValues = [ -- 'idempotencyKey' => uniqid('square_card_', TRUE), -+ // Deterministic on the (single-use) nonce, rather than uniqid() — -+ // uniqid() is never the same twice, which defeats the point of an -+ // idempotency key: an accidental double-submit with the same nonce -+ // would otherwise create two cards. -+ 'idempotencyKey' => $this->idempotencyKey('card', $cardNonce), - 'sourceId' => $cardNonce, - 'card' => new Card($cardValues), - ]; -@@ -1914,10 +2124,13 @@ class CRM_Core_Payment_Square extends CRM_Core_Payment { - catch (PaymentProcessorException $e) { - throw $e; - } -- catch (\Exception $e) { -+ catch (\Throwable $e) { - $errorMessage = E::ts('Failed to cancel the Square subscription: ') . $e->getMessage(); - \Civi::log('square')->error($errorMessage); -- throw new PaymentProcessorException($errorMessage, 0, $e); -+ // $previous is CRM_Core_Exception's 4th constructor argument -+ // ($message, $error_code, $errorData, $previous) — passing $e as the -+ // 3rd argument silently drops it into the $errorData slot instead. -+ throw new PaymentProcessorException($errorMessage, 0, [], $e); - } - - return ['message' => E::ts('Successfully cancelled the Square subscription.')]; -@@ -1945,60 +2158,67 @@ class CRM_Core_Payment_Square extends CRM_Core_Payment { - } - - /** -- * Update subscription amount at Square. -+ * Change the amount of an active Square subscription. - * -- * @param string $subscriptionId -- * @param float $newAmount -- * @param string $currency -+ * This is CiviCRM's real "change recurring amount" contract — see -+ * CRM_Core_Payment_AuthorizeNet::changeSubscriptionAmount() and -+ * CRM_Core_Payment_PayPalImpl::changeSubscriptionAmount(). It is not a -+ * declared abstract on the base class, so a processor that names its -+ * equivalent method anything else (as this one previously did, with -+ * updateSubscriptionAmount()) is simply never called by CiviCRM's -+ * "change amount" UI. - * -- * @throws \CRM_Core_Exception -+ * @param string $message -+ * @param array $params -+ * Expects 'subscriptionId' (Square subscription ID) and 'amount' -+ * (new total amount); optionally 'currency'. -+ * -+ * @return bool -+ * -+ * @throws \Civi\Payment\Exception\PaymentProcessorException - */ -- public function updateSubscriptionAmount($subscriptionId, $newAmount, $currency = 'USD') { -- $amountCents = (int) round(((float) $newAmount) * 100); -+ public function changeSubscriptionAmount(&$message = '', $params = []) { -+ $subscriptionId = $params['subscriptionId'] ?? NULL; -+ $newAmount = $params['amount'] ?? NULL; -+ if (empty($subscriptionId) || $newAmount === NULL) { -+ $message = E::ts('Missing subscription ID or amount for Square subscription amount change.'); -+ throw new PaymentProcessorException($message); -+ } - -- $this->callSquare(fn (SquareClient $client) => $client->subscriptions->update(new UpdateSubscriptionRequest([ -- 'subscriptionId' => $subscriptionId, -- 'subscription' => new Subscription([ -+ $currency = $params['currency'] ?? $this->_paymentProcessor['currency'] ?? 'USD'; -+ -+ try { -+ // Square requires the current object version on every update to -+ // guard against concurrent modification, so fetch it immediately -+ // before applying the change. -+ $current = $this->callSquare(fn (SquareClient $client) => $client->subscriptions->get( -+ new GetSubscriptionsRequest(['subscriptionId' => $subscriptionId]) -+ ))->getSubscription(); -+ $version = $current ? $current->getVersion() : NULL; -+ -+ $amountCents = (int) round(((float) $newAmount) * 100); -+ $subscriptionValues = [ - 'priceOverrideMoney' => new Money(['amount' => $amountCents, 'currency' => $currency]), -- ]), -- ]))); -- } -+ ]; -+ if ($version !== NULL) { -+ $subscriptionValues['version'] = $version; -+ } - -- /** -- * Update the billing day / next billing date for a Square subscription. -- * -- * @param string $subscriptionId -- * @param string $nextBillingDate -- * Format: YYYY-MM-DD. -- * -- * @throws \CRM_Core_Exception -- */ -- public function updateSubscriptionBillingDate($subscriptionId, $nextBillingDate) { -- $this->callSquare(fn (SquareClient $client) => $client->subscriptions->update(new UpdateSubscriptionRequest([ -- 'subscriptionId' => $subscriptionId, -- 'subscription' => new Subscription([ -- 'startDate' => $nextBillingDate, -- ]), -- ]))); -- } -+ $this->callSquare(fn (SquareClient $client) => $client->subscriptions->update(new UpdateSubscriptionRequest([ -+ 'subscriptionId' => $subscriptionId, -+ 'subscription' => new Subscription($subscriptionValues), -+ ]))); -+ } -+ catch (PaymentProcessorException $e) { -+ throw $e; -+ } -+ catch (\Throwable $e) { -+ $message = E::ts('Failed to change Square subscription amount: ') . $e->getMessage(); -+ throw new PaymentProcessorException($message, 0, [], $e); -+ } - -- /** -- * Update the cadence (frequency) of a subscription. -- * -- * @param string $subscriptionId -- * @param string $newPlanId -- * Square plan *variation* ID — the SDK's Subscription resource only has -- * a planVariationId field (no legacy plan_id equivalent). -- * -- * @throws \CRM_Core_Exception -- */ -- public function updateSubscriptionPlan($subscriptionId, $newPlanId) { -- $this->callSquare(fn (SquareClient $client) => $client->subscriptions->update(new UpdateSubscriptionRequest([ -- 'subscriptionId' => $subscriptionId, -- 'subscription' => new Subscription([ -- 'planVariationId' => $newPlanId, -- ]), -- ]))); -+ $message = E::ts('Square subscription amount updated.'); -+ return TRUE; - } - - /** -@@ -2157,24 +2377,32 @@ class CRM_Core_Payment_Square extends CRM_Core_Payment { - } - - /** -- * Validate payment processor settings on save. -+ * Validate the billing-block submission before doPayment() is invoked. -+ * -+ * Overrides CRM_Core_Payment::validatePaymentInstrument(), the actual -+ * hook CiviCRM calls for processor-specific checkout validation. The -+ * previous validateForm($values, &$errors) method had a signature that -+ * doesn't match any CiviCRM contract (checkConfig() already validates -+ * processor *settings*), so it was never invoked by anything. -+ * -+ * @param array $values -+ * @param array $errors - */ -- public function validateForm($values, &$errors) { -- if (($values['payment_processor_type_id:name'] ?? '') !== 'Square') { -+ public function validatePaymentInstrument($values, &$errors) { -+ $amount = (float) ($values['amount'] ?? $values['total_amount'] ?? 0); -+ if ($amount === 0.0) { -+ // No card is required (or collected) for zero-amount contributions. - return; - } - -- if (empty($values['user_name'])) { -- $errors['user_name'] = ts('Square Application ID is required.'); -- } -- if (empty($values['password'])) { -- $errors['password'] = ts('Square Access Token is required.'); -- } -- if (empty($values['signature'])) { -- $errors['signature'] = ts('Square Location ID is required.'); -- } -- if (empty($values['subject'])) { -- $errors['subject'] = ts('Webhook Signature Key is required.'); -+ $hasToken = !empty($values['square_payment_token']) -+ || !empty($values['payment_token']) -+ || !empty($values['token']) -+ || !empty($_POST['square_payment_token']) -+ || !empty($_REQUEST['square_payment_token']); -+ -+ if (!$hasToken) { -+ $errors['square_payment_token'] = ts('Please enter your card details.'); - } - } - -@@ -2204,7 +2432,20 @@ class CRM_Core_Payment_Square extends CRM_Core_Payment { - CRM_Core_Payment_SquareDebugLogger::log("Looking up Square plan variation: {$planId}, {$amount} {$currency}, every {$intervalStep} {$intervalUnit}"); - $cadence = $this->resolveCadence($intervalUnit, $intervalStep); - CRM_Core_Payment_SquareDebugLogger::log("Resolved Square cadence: {$cadence}"); -- $cacheKey = "{$planId}_{$cadence}_{$amount}"; -+ // Scope the cache by everything that changes what gets created in -+ // Square, not just plan/cadence/amount — two processor records (or a -+ // staging clone) pointing at the same Square account/location must -+ // never reuse each other's cached variation IDs. -+ $cacheKey = implode('_', [ -+ (int) ($this->_paymentProcessor['id'] ?? 0), -+ $this->isTestMode() ? 'test' : 'live', -+ $this->getLocationId(), -+ $planId, -+ $cadence, -+ $amount, -+ $currency, -+ $installments ?: 'indefinite', -+ ]); - $cache = Civi::settings()->get('org_square_plan_variation_cache') ?? []; - - if (!empty($cache[$cacheKey])) { -@@ -2220,16 +2461,22 @@ class CRM_Core_Payment_Square extends CRM_Core_Payment { - CRM_Core_Payment_SquareDebugLogger::log("Creating label Square plan variation: {$label}"); - $amountCents = (int) round($amount * 100); - -- $phase = new SubscriptionPhase([ -+ $phaseValues = [ - 'ordinal' => 0, - // MONTHLY, ANNUAL. - 'cadence' => strtoupper($cadence), -- 'periods' => $installments ?? 0, - 'pricing' => new SubscriptionPricing([ - 'type' => 'STATIC', - 'priceMoney' => new Money(['amount' => $amountCents, 'currency' => $currency]), - ]), -- ]); -+ ]; -+ // Only finite subscriptions get a periods count — sending periods: 0 -+ // for an open-ended subscription is wrong (0 periods, not indefinite); -+ // omitting the field entirely is what tells Square the phase never ends. -+ if (!empty($installments)) { -+ $phaseValues['periods'] = $installments; -+ } -+ $phase = new SubscriptionPhase($phaseValues); - - $catalogObject = CatalogObject::subscriptionPlanVariation(new CatalogObjectSubscriptionPlanVariation([ - 'id' => '#var_' . md5($cacheKey), -@@ -2241,7 +2488,7 @@ class CRM_Core_Payment_Square extends CRM_Core_Payment { - ])); - - $response = $this->callSquare(fn (SquareClient $client) => $client->catalog->batchUpsert(new BatchUpsertCatalogObjectsRequest([ -- 'idempotencyKey' => uniqid('plan_var_', TRUE), -+ 'idempotencyKey' => $this->idempotencyKey('plan-variation', $cacheKey), - 'batches' => [new CatalogObjectBatch(['objects' => [$catalogObject]])], - ]))); - -@@ -2292,24 +2539,29 @@ class CRM_Core_Payment_Square extends CRM_Core_Payment { - * @throws CRM_Core_Exception - */ - protected function getOrCreateSubscriptionPlan(string $name): string { -- // CRM_Core_Payment_SquareDebugLogger::log("Looking up Square subscription plan: {$name}"); -- // Cache via Civi setting. -+ // Scope the cache by processor + environment + location, same reasoning -+ // as getOrCreatePlanVariation() above. -+ $cacheKey = implode('_', [ -+ (int) ($this->_paymentProcessor['id'] ?? 0), -+ $this->isTestMode() ? 'test' : 'live', -+ $this->getLocationId(), -+ $name, -+ ]); - $cache = Civi::settings()->get('org_square_plan_cache') ?? []; - -- if (!empty($cache[$name])) { -- return $cache[$name]; -+ if (!empty($cache[$cacheKey])) { -+ return $cache[$cacheKey]; - } - - $catalogObject = CatalogObject::subscriptionPlan(new CatalogObjectSubscriptionPlan([ -- 'id' => '#plan_' . md5($name), -+ 'id' => '#plan_' . md5($cacheKey), - 'subscriptionPlanData' => new CatalogSubscriptionPlan([ - 'name' => $name, - ]), - ])); - -- // CRM_Core_Payment_SquareDebugLogger::log("Creating Square subscription plan: {$name}");. - $response = $this->callSquare(fn (SquareClient $client) => $client->catalog->batchUpsert(new BatchUpsertCatalogObjectsRequest([ -- 'idempotencyKey' => uniqid('plan_', TRUE), -+ 'idempotencyKey' => $this->idempotencyKey('plan', $cacheKey), - 'batches' => [new CatalogObjectBatch(['objects' => [$catalogObject]])], - ]))); - -@@ -2319,7 +2571,7 @@ class CRM_Core_Payment_Square extends CRM_Core_Payment { - throw new CRM_Core_Exception('Failed to create Square subscription plan.'); - } - -- $cache[$name] = $planId; -+ $cache[$cacheKey] = $planId; - Civi::settings()->set('org_square_plan_cache', $cache); - - return $planId; -@@ -2340,23 +2592,19 @@ class CRM_Core_Payment_Square extends CRM_Core_Payment { - switch ($squareStatus) { - case 'COMPLETED': - case 'APPROVED': -- // Completed. -- return 1; -+ return $this->contributionStatusId('Completed'); - - case 'PENDING': - case 'PROCESSING': -- // Pending. -- return 2; -+ return $this->contributionStatusId('Pending'); - - case 'FAILED': - case 'DECLINED': - case 'CANCELED': -- // Failed. -- return 4; -+ return $this->contributionStatusId('Failed'); - - case 'REFUNDED': -- // Refunded. -- return 7; -+ return $this->contributionStatusId('Refunded'); - - default: - return NULL; -@@ -2378,20 +2626,17 @@ class CRM_Core_Payment_Square extends CRM_Core_Payment { - case 'WALLET': - case 'BUY_NOW_PAY_LATER': - case 'SQUARE_ACCOUNT': -- // Credit Card. -- return 1; -+ return $this->paymentInstrumentId('Credit Card'); - - case 'BANK_ACCOUNT': -- // EFT. -- return 5; -+ return $this->paymentInstrumentId('EFT'); - - case 'CASH': -- // Cash. -- return 3; -+ return $this->paymentInstrumentId('Cash'); - - default: - // Credit Card (Square's most common instrument) -- return 1; -+ return $this->paymentInstrumentId('Credit Card'); - } - } - -@@ -2430,7 +2675,8 @@ class CRM_Core_Payment_Square extends CRM_Core_Payment { - } - } - } -- catch (\Exception $e) { -+ catch (\Throwable $e) { -+ CRM_Core_Payment_SquareDebugLogger::log('Square findContactIdForPayment(): customer lookup error: ' . $e->getMessage()); - } - } - -diff --git a/CRM/Core/Payment/SquareIPN.php b/CRM/Core/Payment/SquareIPN.php -index 013760a..e9ef9e7 100644 ---- a/CRM/Core/Payment/SquareIPN.php -+++ b/CRM/Core/Payment/SquareIPN.php -@@ -18,8 +18,22 @@ use Civi\Api4\PaymentprocessorWebhook; - * - * Webhook lifecycle: - * 1. onReceiveWebhook() validates the event type, deduplicates via -- * civicrm_paymentprocessor_webhook and returns. CiviCRM's "Process -- * Pending Webhooks" scheduled job invokes the processor later. -+ * civicrm_paymentprocessor_webhook (a table owned by the mjwshared -+ * extension, not CiviCRM core — this extension requires it, see -+ * info.xml), records the event, and processes it IMMEDIATELY in the -+ * same request — donors/staff see the result right away rather than -+ * waiting on cron. -+ * 2. mjwshared's "Process Payment Processor Webhooks" scheduled job -+ * (Job.process_paymentprocessor_webhooks) is a BACKSTOP: it polls -+ * rows still sitting in status='new' and calls -+ * CRM_Core_Payment_Square::processWebhookEvent(), which invokes -+ * processQueuedWebhookEvent() here. A row only stays 'new' if the -+ * immediate attempt hit a transient failure (network blip, Square -+ * 5xx/429 — see CRM_Core_Payment_SquareRetryableException); anything -+ * else resolves to 'success' or 'error' immediately, so a healthy -+ * site should rarely depend on this job at all. If it never runs -+ * (e.g. CiviCRM cron not configured), only genuinely transient -+ * failures go unretried — normal webhooks are unaffected. - */ - class CRM_Core_Payment_SquareIPN { - -@@ -109,9 +123,18 @@ class CRM_Core_Payment_SquareIPN { - /** - * Main entry point — called from Square::handlePaymentNotification(). - * -- * Records the webhook in civicrm_paymentprocessor_webhook for deduplication -- * and audit trail. Webhook delivery must be quick: processing is deferred to -- * CiviCRM's queue worker. -+ * Records the webhook in civicrm_paymentprocessor_webhook for -+ * deduplication and audit trail, then processes it immediately, in the -+ * same request — donors and staff see a completed payment right away -+ * instead of waiting for the next cron run. -+ * -+ * mjwshared's "Process Payment Processor Webhooks" scheduled job (Job. -+ * process_paymentprocessor_webhooks) is a BACKSTOP, not the primary -+ * path: it polls rows still sitting in status='new' and calls -+ * CRM_Core_Payment_Square::processWebhookEvent() for them. A row only -+ * stays 'new' here if this immediate attempt hit a transient failure -+ * (see processQueuedWebhookEvent()) — normally every row resolves to -+ * 'success' or 'error' before this method returns. - * - * @param array $payload - * Decoded JSON webhook payload. -@@ -142,26 +165,46 @@ class CRM_Core_Payment_SquareIPN { - return FALSE; - } - -- // Deduplicate across every queue state. A previously failed event remains -- // retryable; accepting a replay must not create a second queue record. -- $existingWebhooks = PaymentprocessorWebhook::get(FALSE) -- ->addWhere('payment_processor_id', '=', $processorId) -- ->addWhere('event_id', '=', (string) $eventId) -- ->execute(); -- -- foreach ($existingWebhooks as $existing) { -- CRM_Core_Payment_SquareDebugLogger::log("Square IPN: duplicate event '{$eventId}' already queued, skipping."); -+ // Guard the check-then-insert dedup below with a lock scoped to this -+ // processor+event, so two concurrent deliveries of the same event -+ // (Square does redeliver) can't both pass the "no existing row" check -+ // and create duplicate queue records. -+ $lock = new CRM_Core_Lock("worker.square.webhook.{$processorId}.{$eventId}", 30); -+ if (!$lock->acquire()) { -+ CRM_Core_Payment_SquareDebugLogger::log("Square IPN: could not acquire dedup lock for event '{$eventId}', treating as in-flight duplicate."); - return TRUE; - } - -- $newWebhookEvent = PaymentprocessorWebhook::create(FALSE) -- ->addValue('payment_processor_id', $processorId) -- ->addValue('trigger', $eventType) -- ->addValue('identifier', $identifier) -- ->addValue('event_id', (string) ($eventId ?? '')) -- ->addValue('data', $this->getData()) -- ->execute() -- ->first(); -+ $newWebhookEvent = NULL; -+ try { -+ // Deduplicate across every queue state. A previously failed event -+ // remains retryable; accepting a replay must not create a second -+ // queue record. It's intentionally NOT reprocessed here — if it's -+ // still 'new'/'error', the scheduled job's backstop will pick it up, -+ // rather than risking two concurrent processing attempts for the -+ // same event from rapid Square redeliveries. -+ $existingWebhooks = PaymentprocessorWebhook::get(FALSE) -+ ->addWhere('payment_processor_id', '=', $processorId) -+ ->addWhere('event_id', '=', (string) $eventId) -+ ->execute(); -+ -+ foreach ($existingWebhooks as $existing) { -+ CRM_Core_Payment_SquareDebugLogger::log("Square IPN: duplicate event '{$eventId}' already queued, skipping."); -+ return TRUE; -+ } -+ -+ $newWebhookEvent = PaymentprocessorWebhook::create(FALSE) -+ ->addValue('payment_processor_id', $processorId) -+ ->addValue('trigger', $eventType) -+ ->addValue('identifier', $identifier) -+ ->addValue('event_id', (string) ($eventId ?? '')) -+ ->addValue('data', $this->getData()) -+ ->execute() -+ ->first(); -+ } -+ finally { -+ $lock->release(); -+ } - - return $this->processQueuedWebhookEvent($newWebhookEvent); - } -@@ -169,8 +212,12 @@ class CRM_Core_Payment_SquareIPN { - /** - * Process a single queued webhook event and update its record. - * -- * Called inline from onReceiveWebhook() and may also be called by the -- * CiviCRM "Process Pending Webhooks" scheduled job. -+ * Called two ways: -+ * - Immediately, from onReceiveWebhook() above, right after the row is -+ * created (the normal path). -+ * - Later, via CRM_Core_Payment_Square::processWebhookEvent(), which -+ * mjwshared's Job.process_paymentprocessor_webhooks invokes as a -+ * backstop for any row still sitting in status='new'. - * - * @param array $webhookEvent - * -@@ -191,21 +238,33 @@ class CRM_Core_Payment_SquareIPN { - $this->setInputParameters($payload, $eventType); - - $ok = FALSE; -+ // 'error' = permanent failure, will not be retried by the scheduled -+ // job. 'new' = transient failure, left for the job to retry. -+ $status = 'error'; - $message = ''; - - try { - $this->processWebhookEvent($payload, $eventType); - $ok = TRUE; -+ $status = 'success'; - $message = 'Processed successfully'; - } -- catch (Exception $e) { -+ catch (CRM_Core_Payment_SquareRetryableException $e) { -+ $status = 'new'; -+ $message = $e->getMessage(); -+ Civi::log()->warning("Square IPN: processQueuedWebhookEvent transient failure, will retry. EventID: {$this->event_id}: " . $e->getMessage()); -+ } -+ catch (\Throwable $e) { -+ // Catches Error/TypeError too, not just Exception — otherwise a bug -+ // here would leave the queue row stuck in 'processing' forever -+ // (see api/v3/Job/ProcessPaymentprocessorWebhooks.php in mjwshared). - $message = $e->getMessage() . "\n" . $e->getTraceAsString(); - Civi::log()->error("Square IPN: processQueuedWebhookEvent failed. EventID: {$this->event_id}: " . $e->getMessage()); - } - - $update = PaymentprocessorWebhook::update(FALSE) - ->addWhere('id', '=', $webhookEvent['id']) -- ->addValue('status', $ok ? 'success' : 'error') -+ ->addValue('status', $status) - ->addValue('message', preg_replace('/^(.{250}).*/su', '$1 ...', $message)); - if ($ok) { - $update->addValue('processed_date', 'now'); -diff --git a/CRM/Core/Payment/SquareRetryableException.php b/CRM/Core/Payment/SquareRetryableException.php -new file mode 100644 -index 0000000..6cc428c ---- /dev/null -+++ b/CRM/Core/Payment/SquareRetryableException.php -@@ -0,0 +1,18 @@ -+createSquareCustomerMapTable(); - } - -@@ -25,6 +26,7 @@ class CRM_Square_Upgrader extends CRM_Extension_Upgrader_Base { - * now-superseded custom field group. - */ - public function upgrade_1000(): bool { -+ _square_assert_php_version(); - $this->createSquareCustomerMapTable(); - $this->backfillSquareCustomerMapFromCustomField(); - return TRUE; -diff --git a/square.php b/square.php -index 4aefcb3..750c4ff 100644 ---- a/square.php -+++ b/square.php -@@ -14,6 +14,32 @@ require_once 'square.civix.php'; - use Civi\Api4\CustomGroup; - use Civi\Api4\CustomField; - -+/** -+ * Minimum PHP version this extension requires. -+ * -+ * Composer.json's "php" constraint only governs `composer install`; it is -+ * never checked at enable/upgrade time, so a site could still enable this -+ * extension on an older, unsupported PHP — CiviCRM 6.16 itself still -+ * supports PHP 8.1. -+ */ -+const SQUARE_MIN_PHP_VERSION = '8.2.0'; -+ -+/** -+ * Abort enable/upgrade with a clear error if running on an unsupported PHP. -+ * -+ * @throws \CRM_Core_Exception -+ */ -+function _square_assert_php_version(): void { -+ if (version_compare(PHP_VERSION, SQUARE_MIN_PHP_VERSION, '<')) { -+ throw new CRM_Core_Exception( -+ \CRM_Square_ExtensionUtil::ts('The Square payment processor extension requires PHP %1 or newer; this site is running PHP %2.', [ -+ 1 => SQUARE_MIN_PHP_VERSION, -+ 2 => PHP_VERSION, -+ ]) -+ ); -+ } -+} -+ - /** - * Implements hook_civicrm_config(). - */ -@@ -25,6 +51,7 @@ function square_civicrm_config(\CRM_Core_Config $config): void { - * Implements hook_civicrm_install(). - */ - function square_civicrm_install(): void { -+ _square_assert_php_version(); - _square_civix_civicrm_install(); - } - -@@ -59,6 +86,7 @@ function square_civicrm_uninstall(): void { - * Implements hook_civicrm_enable(). - */ - function square_civicrm_enable(): void { -+ _square_assert_php_version(); - _square_civix_civicrm_enable(); - } - -diff --git a/tests/phpunit/.phpunit.result.cache b/tests/phpunit/.phpunit.result.cache -deleted file mode 100644 -index 3ad35dc..0000000 ---- a/tests/phpunit/.phpunit.result.cache -+++ /dev/null -@@ -1 +0,0 @@ --{"version":1,"defects":{"CRM_Core_Payment_Square_ExceptionHandlingTest::testCallSquareTranslatesApiExceptionIntoCrmCoreException":3,"CRM_Core_Payment_Square_ExceptionHandlingTest::testCallSquareTranslatesGenericSquareExceptionIntoCrmCoreException":3,"CRM_Core_Payment_Square_MoneyConversionTest::testOneTimePaymentConvertsDollarsToCents with data set \"simple\"":4,"CRM_Core_Payment_Square_MoneyConversionTest::testOneTimePaymentConvertsDollarsToCents with data set \"small fraction\"":4,"CRM_Core_Payment_Square_MoneyConversionTest::testOneTimePaymentConvertsDollarsToCents with data set \"rounds half up\"":4,"CRM_Core_Payment_Square_MoneyConversionTest::testOneTimePaymentConvertsDollarsToCents with data set \"whole dollars\"":4,"CRM_Core_Payment_Square_MoneyConversionTest::testRefundRejectsZeroAmount":3,"CRM_Core_Payment_Square_MoneyConversionTest::testRefundRejectsNegativeAmount":3,"CRM_Core_Payment_Square_RequestShapeTest::testRefundRequestShape":4,"CRM_Core_Payment_Square_StatusMappingTest::testMapSquareSubscriptionStatusToCivi with data set \"pending is intentionally left unmapped\"":3},"times":{"CRM_Core_Payment_Square_ConfigurationTest::testCheckConfigReportsEveryMissingCredential":0.004,"CRM_Core_Payment_Square_ConfigurationTest::testCheckConfigAcceptsCompleteCredentials":0,"CRM_Core_Payment_Square_ConfigurationTest::testCheckConfigReportsOnlyTheFieldsActuallyMissing":0.001,"CRM_Core_Payment_Square_ConfigurationTest::testGetLocationIdThrowsWhenSignatureIsEmpty":0.001,"CRM_Core_Payment_Square_ConfigurationTest::testGetLocationIdTrimsWhitespace":0,"CRM_Core_Payment_Square_ConfigurationTest::testApiBaseUrlDefaultsToSandboxInTestMode":0,"CRM_Core_Payment_Square_ConfigurationTest::testApiBaseUrlDefaultsToLiveOutsideTestMode":0,"CRM_Core_Payment_Square_ConfigurationTest::testApiBaseUrlHonorsConfiguredOverrideEvenInTestMode":0,"CRM_Core_Payment_Square_ConfigurationTest::testBuildSquareClientReturnsASquareClientForEitherEnvironment":0.05,"CRM_Core_Payment_Square_ExceptionHandlingTest::testSquareApiErrorFormatsHttpCodeAndErrorDetails":0.001,"CRM_Core_Payment_Square_ExceptionHandlingTest::testSquareApiErrorJoinsMultipleErrors":0,"CRM_Core_Payment_Square_ExceptionHandlingTest::testCallSquareTranslatesApiExceptionIntoCrmCoreException":0.013,"CRM_Core_Payment_Square_ExceptionHandlingTest::testCallSquareTranslatesGenericSquareExceptionIntoCrmCoreException":0,"CRM_Core_Payment_Square_ExceptionHandlingTest::testTranslateSquareCardErrorHumanMessages with data set \"card declined\"":0,"CRM_Core_Payment_Square_ExceptionHandlingTest::testTranslateSquareCardErrorHumanMessages with data set \"generic decline\"":0,"CRM_Core_Payment_Square_ExceptionHandlingTest::testTranslateSquareCardErrorHumanMessages with data set \"invalid expiration\"":0,"CRM_Core_Payment_Square_ExceptionHandlingTest::testTranslateSquareCardErrorHumanMessages with data set \"cvv failure\"":0,"CRM_Core_Payment_Square_ExceptionHandlingTest::testTranslateSquareCardErrorHumanMessages with data set \"address verification failure\"":0,"CRM_Core_Payment_Square_ExceptionHandlingTest::testTranslateSquareCardErrorHumanMessages with data set \"insufficient funds\"":0,"CRM_Core_Payment_Square_ExceptionHandlingTest::testTranslateSquareCardErrorFallsBackToDetailForUnknownCodes":0,"CRM_Core_Payment_Square_ExceptionHandlingTest::testTranslateSquareCardErrorFallsBackToGenericMessageWithNoDetail":0,"CRM_Core_Payment_Square_IdempotencyTest::testKeyIsStableForTheSameOperationAndReference":0,"CRM_Core_Payment_Square_IdempotencyTest::testKeyDiffersByOperation":0,"CRM_Core_Payment_Square_IdempotencyTest::testKeyDiffersBetweenSubscriptionAndSubscriptionInit":0.001,"CRM_Core_Payment_Square_IdempotencyTest::testKeyDiffersBetweenLiveAndSandboxForTheSameReference":0,"CRM_Core_Payment_Square_IdempotencyTest::testKeyDiffersBetweenPaymentProcessorInstances":0,"CRM_Core_Payment_Square_IdempotencyTest::testKeyNeverExceeds45Characters with data set \"short reference\"":0,"CRM_Core_Payment_Square_IdempotencyTest::testKeyNeverExceeds45Characters with data set \"long invoice reference\"":0,"CRM_Core_Payment_Square_IdempotencyTest::testKeyNeverExceeds45Characters with data set \"subscription-init with a large recur id\"":0,"CRM_Core_Payment_Square_IdempotencyTest::testKeyNeverExceeds45Characters with data set \"refund composite reference\"":0,"CRM_Core_Payment_Square_MoneyConversionTest::testOneTimePaymentConvertsDollarsToCents with data set \"simple\"":0.001,"CRM_Core_Payment_Square_MoneyConversionTest::testOneTimePaymentConvertsDollarsToCents with data set \"small fraction\"":0,"CRM_Core_Payment_Square_MoneyConversionTest::testOneTimePaymentConvertsDollarsToCents with data set \"rounds half up\"":0,"CRM_Core_Payment_Square_MoneyConversionTest::testOneTimePaymentConvertsDollarsToCents with data set \"whole dollars\"":0,"CRM_Core_Payment_Square_MoneyConversionTest::testZeroAmountOneTimePaymentShortCircuitsWithoutCallingSquare":0,"CRM_Core_Payment_Square_MoneyConversionTest::testRefundRejectsZeroAmount":0.001,"CRM_Core_Payment_Square_MoneyConversionTest::testRefundRejectsNegativeAmount":0,"CRM_Core_Payment_Square_RequestShapeTest::testOneTimePaymentRequestShape":0,"CRM_Core_Payment_Square_RequestShapeTest::testOneTimePaymentOmitsReferenceIdWhenNoInvoiceId":0,"CRM_Core_Payment_Square_RequestShapeTest::testRefundRequestShape":0.001,"CRM_Core_Payment_Square_RequestShapeTest::testCreateCardOnFileRequestShapeWithBillingAddress":0.002,"CRM_Core_Payment_Square_RequestShapeTest::testCreateCardOnFileOmitsBillingAddressWhenNotSupplied":0,"CRM_Core_Payment_Square_StatusMappingTest::testMapPaymentStatus with data set \"completed\"":0,"CRM_Core_Payment_Square_StatusMappingTest::testMapPaymentStatus with data set \"approved\"":0,"CRM_Core_Payment_Square_StatusMappingTest::testMapPaymentStatus with data set \"pending\"":0,"CRM_Core_Payment_Square_StatusMappingTest::testMapPaymentStatus with data set \"processing\"":0,"CRM_Core_Payment_Square_StatusMappingTest::testMapPaymentStatus with data set \"failed\"":0,"CRM_Core_Payment_Square_StatusMappingTest::testMapPaymentStatus with data set \"declined\"":0,"CRM_Core_Payment_Square_StatusMappingTest::testMapPaymentStatus with data set \"canceled\"":0,"CRM_Core_Payment_Square_StatusMappingTest::testMapPaymentStatus with data set \"refunded\"":0,"CRM_Core_Payment_Square_StatusMappingTest::testMapPaymentStatus with data set \"lowercase is normalized\"":0,"CRM_Core_Payment_Square_StatusMappingTest::testMapPaymentStatus with data set \"unknown status is unmapped\"":0,"CRM_Core_Payment_Square_StatusMappingTest::testMapSquareSubscriptionStatusToCivi with data set \"active maps to In Progress, not Completed\"":0,"CRM_Core_Payment_Square_StatusMappingTest::testMapSquareSubscriptionStatusToCivi with data set \"canceled maps to Cancelled\"":0,"CRM_Core_Payment_Square_StatusMappingTest::testMapSquareSubscriptionStatusToCivi with data set \"deactivated maps to Cancelled\"":0,"CRM_Core_Payment_Square_StatusMappingTest::testMapSquareSubscriptionStatusToCivi with data set \"suspended maps to Failed\/On Hold\"":0,"CRM_Core_Payment_Square_StatusMappingTest::testMapSquareSubscriptionStatusToCivi with data set \"pending is intentionally left unmapped\"":0,"CRM_Core_Payment_Square_StatusMappingTest::testMapSquareSubscriptionStatusToCivi with data set \"unknown status is unmapped\"":0,"CRM_Core_Payment_Square_StatusMappingTest::testMapPaymentInstrument with data set \"card\"":0,"CRM_Core_Payment_Square_StatusMappingTest::testMapPaymentInstrument with data set \"wallet tokenizes as card\"":0,"CRM_Core_Payment_Square_StatusMappingTest::testMapPaymentInstrument with data set \"buy now pay later\"":0,"CRM_Core_Payment_Square_StatusMappingTest::testMapPaymentInstrument with data set \"square account\"":0,"CRM_Core_Payment_Square_StatusMappingTest::testMapPaymentInstrument with data set \"bank account is EFT\"":0,"CRM_Core_Payment_Square_StatusMappingTest::testMapPaymentInstrument with data set \"cash\"":0,"CRM_Core_Payment_Square_StatusMappingTest::testMapPaymentInstrument with data set \"unknown defaults to credit card\"":0,"CRM_Core_Payment_Square_StatusMappingTest::testMapPaymentInstrument with data set \"null defaults to credit card\"":0,"CRM_Core_Payment_SquareTest::testCheckConfigReportsEveryMissingCredential":0,"CRM_Core_Payment_SquareTest::testCheckConfigAcceptsCompleteCredentials":0,"CRM_Core_Payment_SquareTest::testIdempotencyKeyIsStableAndScoped":0,"CRM_Core_Payment_SquareTest::testRefundReturnsCiviRefundStatus":0}} -\ No newline at end of file -diff --git a/tests/phpunit/CRM/Core/Payment/Square/IdempotencyTest.php b/tests/phpunit/CRM/Core/Payment/Square/IdempotencyTest.php -index 7d48bf1..cf85341 100644 ---- a/tests/phpunit/CRM/Core/Payment/Square/IdempotencyTest.php -+++ b/tests/phpunit/CRM/Core/Payment/Square/IdempotencyTest.php -@@ -38,10 +38,13 @@ class CRM_Core_Payment_Square_IdempotencyTest extends CRM_Core_Payment_Square_Sq - } - - public function testKeyDiffersBetweenSubscriptionAndSubscriptionInit(): void { -- // Regression test: these two operations share the same $recurId -- // reference and must not collide with each other or with the plain -- // subscription create key (see doRecurPayment()'s 'subscription-init' -- // fix for the VALUE_TOO_LONG idempotency-key bug). -+ // Regression test for the generic idempotencyKey() helper: two -+ // operations sharing the same reference (e.g. a recur ID) must never -+ // collide. doRecurPayment() no longer makes a separate -+ // 'subscription-init' call itself (removed to fix the double-charge -+ // bug -- the initial charge is now handled entirely by Square's own -+ // subscription billing), but the helper's collision-avoidance -+ // guarantee is still load-bearing for every other caller. - $processor = $this->processor(); - $recurId = '999'; - $subscriptionKey = $this->key($processor, 'subscription', $recurId); -diff --git a/tests/phpunit/CRM/Core/Payment/Square/StatusMappingTest.php b/tests/phpunit/CRM/Core/Payment/Square/StatusMappingTest.php -index 2f838c3..a63aa18 100644 ---- a/tests/phpunit/CRM/Core/Payment/Square/StatusMappingTest.php -+++ b/tests/phpunit/CRM/Core/Payment/Square/StatusMappingTest.php -@@ -49,14 +49,16 @@ class CRM_Core_Payment_Square_StatusMappingTest extends CRM_Core_Payment_Square_ - - public static function subscriptionStatusProvider(): array { - return [ -+ // Real Square subscription statuses: PENDING, ACTIVE, CANCELED, -+ // DEACTIVATED, PAUSED, and (API versions 2025-09-24+) COMPLETED. -+ // SUSPENDED does not exist and must never be matched/mapped. -+ 'pending maps to Pending' => ['PENDING', 2], -+ 'paused maps to Pending' => ['PAUSED', 2], - 'active maps to In Progress, not Completed' => ['ACTIVE', 5], -+ 'completed maps to Completed' => ['COMPLETED', 1], - 'canceled maps to Cancelled' => ['CANCELED', 3], -- 'deactivated maps to Cancelled' => ['DEACTIVATED', 3], -- 'suspended maps to Failed/On Hold' => ['SUSPENDED', 4], -- // Square subscriptions report PENDING until start_date is reached, -- // even after a successful initial payment already moved the local -- // recur to In Progress -- must NOT downgrade back to Pending. -- 'pending is intentionally left unmapped' => ['PENDING', NULL], -+ 'deactivated maps to Failed' => ['DEACTIVATED', 4], -+ 'nonexistent suspended status is unmapped' => ['SUSPENDED', NULL], - 'unknown status is unmapped' => ['SOMETHING_NEW', NULL], - ]; - } -diff --git a/tests/phpunit/bootstrap.php b/tests/phpunit/bootstrap.php -index f423111..cc33e44 100644 ---- a/tests/phpunit/bootstrap.php -+++ b/tests/phpunit/bootstrap.php -@@ -87,9 +87,11 @@ if (!class_exists('CRM_Contribute_PseudoConstant')) { - /** - * Minimal stand-in for CiviCRM core's contribution-status lookup. - * -- * Used by CRM_Core_Payment_Square::contributionStatusId(). Values match -- * CiviCRM's own default 'contribution_status' option group so tests -- * exercise the same IDs the production code assumes elsewhere. -+ * Kept even though production code no longer calls this directly -+ * (CRM_Core_Payment_Square::contributionStatusId() now goes through -+ * CRM_Core_PseudoConstant::getKey(), matching CiviCRM's real, current -+ * convention) — some tests still exercise it directly as a regression -+ * guard against reintroducing the deprecated call. - */ - class CRM_Contribute_PseudoConstant { - -@@ -110,6 +112,59 @@ if (!class_exists('CRM_Contribute_PseudoConstant')) { - - } - } -+if (!class_exists('CRM_Core_PseudoConstant')) { -+ -+ /** -+ * Minimal stand-in for CiviCRM core's pseudoconstant lookup. -+ * -+ * Used by CRM_Core_Payment_Square::pseudoConstantId() for -+ * contribution_status_id, payment_instrument_id, and financial_type_id. -+ * Values match CiviCRM's own default option groups, seeded on every -+ * fresh install, so tests exercise the same IDs the production code -+ * assumes elsewhere. -+ */ -+ class CRM_Core_PseudoConstant { -+ -+ /** -+ * @param string $baoName -+ * @param string $fieldName -+ * @param string $value -+ * -+ * @return int|false -+ */ -+ public static function getKey($baoName, $fieldName, $value) { -+ $options = [ -+ 'contribution_status_id' => [ -+ 1 => 'Completed', -+ 2 => 'Pending', -+ 3 => 'Cancelled', -+ 4 => 'Failed', -+ 5 => 'In Progress', -+ 6 => 'Overdue', -+ 7 => 'Refunded', -+ ], -+ 'payment_instrument_id' => [ -+ 1 => 'Credit Card', -+ 2 => 'Debit Card', -+ 3 => 'Cash', -+ 4 => 'Check', -+ 5 => 'EFT', -+ 6 => 'Money Order', -+ ], -+ 'financial_type_id' => [ -+ 1 => 'Donation', -+ 2 => 'Member Dues', -+ 3 => 'Campaign Contribution', -+ 4 => 'Event Fee', -+ 5 => 'Gift', -+ ], -+ ]; -+ $id = array_search($value, $options[$fieldName] ?? [], TRUE); -+ return $id === FALSE ? FALSE : $id; -+ } -+ -+ } -+} - - // CiviCRM test bootstrap (if available). Not required for mock-only tests, - // but harmless if present. diff --git a/settings/Square.setting.php b/settings/Square.setting.php index 9720f789..4134ab78 100644 --- a/settings/Square.setting.php +++ b/settings/Square.setting.php @@ -20,4 +20,18 @@ 'help_text' => NULL, 'settings_pages' => ['square' => ['weight' => 10]], ], + 'square_import_external_payments' => [ + 'name' => 'square_import_external_payments', + 'type' => 'Boolean', + 'html_type' => 'checkbox', + 'quick_form_type' => 'YesNo', + 'default' => FALSE, + 'add' => '1.2.0', + 'is_domain' => 1, + 'is_contact' => 0, + 'title' => \CRM_Square_ExtensionUtil::ts('Import Square Payments Made Outside CiviCRM'), + 'description' => \CRM_Square_ExtensionUtil::ts('When enabled, a completed Square payment that matches no CiviCRM contribution or subscription (for example a Square Dashboard or Square Online sale) is recorded as a new Donation contribution, if it was taken at the payment processor\'s Square location and its contact can be identified. Payments at other locations, including point of sale, are always ignored.'), + 'help_text' => NULL, + 'settings_pages' => ['square' => ['weight' => 20]], + ], ]; diff --git a/square.civix.php b/square.civix.php index 526d8b8a..ccc3a93f 100644 --- a/square.civix.php +++ b/square.civix.php @@ -198,43 +198,3 @@ function _square_civix_fixNavigationMenuItems(&$nodes, &$maxNavID, $parentID) { } } } - -/** - * Search directory tree for files which match a glob pattern. - * - * Note: Dot-directories (like "..", ".git", or ".svn") will be ignored. - * Note: Delegate to CRM_Utils_File::findFiles(), this function kept only - * for backward compatibility of extension code that uses it. - * - * @param string $dir base dir - * @param string $pattern , glob pattern, eg "*.txt" - * - * @return array - */ -function _square_civix_find_files($dir, $pattern) { - return CRM_Utils_File::findFiles($dir, $pattern); -} - -/** - * (Delegated) Implements hook_civicrm_managed(). - * - * Find any *.mgd.php files, merge their content, and return. - * - * @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_managed - */ -function _square_civix_civicrm_managed(&$entities) { - $mgdFiles = _square_civix_find_files(__DIR__, '*.mgd.php'); - sort($mgdFiles); - foreach ($mgdFiles as $file) { - $es = include $file; - foreach ($es as $e) { - if (empty($e['module'])) { - $e['module'] = E::LONG_NAME; - } - if (empty($e['params']['version'])) { - $e['params']['version'] = '3'; - } - $entities[] = $e; - } - } -} \ No newline at end of file diff --git a/square.php b/square.php index 750c4ffd..5b49825d 100644 --- a/square.php +++ b/square.php @@ -58,8 +58,10 @@ function square_civicrm_install(): void { /** * Implements hook_civicrm_uninstall(). * - * Removes the square_data custom group (and its fields) created on - * install so uninstalling the extension doesn't leave orphaned schema. + * Removes the legacy square_data custom group (and its fields), if an + * earlier version left one behind, so uninstalling the extension doesn't + * leave orphaned schema. square_customer_map is dropped by + * CRM_Square_Upgrader::uninstall(). */ function square_civicrm_uninstall(): void { try { @@ -91,14 +93,23 @@ function square_civicrm_enable(): void { } /** - * Implements hook_civicrm_managed(). + * Implements hook_civicrm_merge(). * - * Wires up the managed entities declared under managed/ (currently just - * the Square payment processor type, see - * managed/PaymentProcessorType.mgd.php). + * Moves the merged-away contact's Square customer mappings to the contact + * kept. Where both contacts have a customer for the same payment processor, + * the kept contact's mapping wins (UPDATE IGNORE skips the row the unique + * contact/processor key would reject) and the other is dropped. Registering + * the table in 'cidRefs' instead would make core run a plain UPDATE, which + * that key would make fail. */ -function square_civicrm_managed(&$entities): void { - _square_civix_civicrm_managed($entities); +function square_civicrm_merge($type, &$data, $mainId = NULL, $otherId = NULL, $tables = NULL): void { + if ($type !== 'sqls' || empty($mainId) || empty($otherId)) { + return; + } + $mainId = (int) $mainId; + $otherId = (int) $otherId; + $data[] = "UPDATE IGNORE square_customer_map SET contact_id = {$mainId} WHERE contact_id = {$otherId}"; + $data[] = "DELETE FROM square_customer_map WHERE contact_id = {$otherId}"; } /** diff --git a/templates/CRM/Core/Payment/Square/Card.tpl b/templates/CRM/Core/Payment/Square/Card.tpl index c1b60e56..a5239a55 100644 --- a/templates/CRM/Core/Payment/Square/Card.tpl +++ b/templates/CRM/Core/Payment/Square/Card.tpl @@ -1,22 +1,21 @@ {* * Billing block template for Square Web Payments. * - * The inline -{/literal} {crmScope extensionKey='org.uschess.square'}
diff --git a/templates/CRM/Square/Form/Settings.tpl b/templates/CRM/Square/Form/Settings.tpl index c9d1c30d..becd44dd 100644 --- a/templates/CRM/Square/Form/Settings.tpl +++ b/templates/CRM/Square/Form/Settings.tpl @@ -1,14 +1,23 @@ +{crmScope extensionKey='org.uschess.square'}
-
- {ts}When enabled, verbose Square webhook processing details (which event was received, which record was found/created/updated) are written to the CiviCRM debug log. Leave disabled in normal operation.{/ts} -
- + + + + +
{$form.square_ipn_debug_logging.label}{$form.square_ipn_debug_logging.html} + {$form.square_ipn_debug_logging.html} +
{ts}When enabled, verbose Square webhook processing details (which event was received, which record was found/created/updated) are written to the CiviCRM debug log. Leave disabled in normal operation.{/ts}
+
{$form.square_import_external_payments.label} + {$form.square_import_external_payments.html} +
{ts}Square notifies CiviCRM of every payment the merchant account takes. When enabled, a completed payment that matches no CiviCRM contribution or subscription is recorded as a new Donation contribution — but only if it was taken at the payment processor's Square location and its contact can be identified (by the Square customer CiviCRM created, or by an email address only one contact has). Payments at other locations, such as point of sale, are always ignored.{/ts}
+
{include file="CRM/common/formButtons.tpl" location="bottom"}
+{/crmScope} diff --git a/tests/phpunit-headless/CRM/Square/ContactsHeadlessTest.php b/tests/phpunit-headless/CRM/Square/ContactsHeadlessTest.php new file mode 100644 index 00000000..182ec5b5 --- /dev/null +++ b/tests/phpunit-headless/CRM/Square/ContactsHeadlessTest.php @@ -0,0 +1,89 @@ +createContact('Pat', 'pat@example.org'); + $customers = new class($this->gateway($this->squareClient())) extends CRM_Square_Customers { + + public function details(int $contactId): ?array { + return $this->getContactDetails($contactId); + } + + }; + + // API4 Contact has no "email" field: it is email_primary.email. + $this->assertSame('pat@example.org', $customers->details($contactId)['email']); + } + + public function testAPaymentsEmailIdentifiesOnlyAnUnsharedAddress(): void { + $patId = $this->createContact('Pat', 'pat@example.org'); + $this->createContact('Sam', 'family@example.org'); + $this->createContact('Alex', 'family@example.org'); + $reconciler = new class($this->gateway($this->squareClient())) extends CRM_Square_Reconciler { + + public function contactFor(array $payment): ?int { + return $this->findContactIdForPayment($payment); + } + + }; + + $this->assertSame($patId, $reconciler->contactFor(['id' => 'P1', 'buyer_email_address' => 'pat@example.org'])); + $this->assertNull($reconciler->contactFor(['id' => 'P2', 'buyer_email_address' => 'family@example.org'])); + } + + public function testAPaymentsMappedCustomerIdentifiesItsContact(): void { + $patId = $this->createContact('Pat'); + $this->mapCustomer($patId, 'CUSTOMER-PAT'); + $reconciler = new class($this->gateway($this->squareClient())) extends CRM_Square_Reconciler { + + public function contactFor(array $payment): ?int { + return $this->findContactIdForPayment($payment); + } + + }; + + $this->assertSame($patId, $reconciler->contactFor(['id' => 'P1', 'customer_id' => 'CUSTOMER-PAT'])); + } + + public function testMergeMovesCustomerMappingsToTheKeptContact(): void { + $keptId = $this->createContact('Pat', 'pat@example.org'); + $removedId = $this->createContact('Pat', 'pat@example.org'); + $this->mapCustomer($removedId, 'CUSTOMER-REMOVED'); + + civicrm_api3('Contact', 'merge', ['to_keep_id' => $keptId, 'to_remove_id' => $removedId, 'mode' => 'aggressive']); + + $this->assertSame(['CUSTOMER-REMOVED' => $keptId], $this->customerMap()); + } + + public function testMergeKeepsTheKeptContactsOwnCustomer(): void { + $keptId = $this->createContact('Pat', 'pat@example.org'); + $removedId = $this->createContact('Pat', 'pat@example.org'); + $this->mapCustomer($keptId, 'CUSTOMER-KEPT'); + $this->mapCustomer($removedId, 'CUSTOMER-REMOVED'); + + // Without the merge hook's UPDATE IGNORE, the unique contact/processor + // key would make the merge fail. + civicrm_api3('Contact', 'merge', ['to_keep_id' => $keptId, 'to_remove_id' => $removedId, 'mode' => 'aggressive']); + + $this->assertSame(['CUSTOMER-KEPT' => $keptId], $this->customerMap()); + } + + public function testDeletingAProcessorDeletesItsMappings(): void { + $this->mapCustomer($this->createContact('Pat'), 'CUSTOMER-PAT'); + + PaymentProcessor::delete(FALSE) + ->addWhere('id', '=', $this->processor['id']) + ->execute(); + + $this->assertSame([], $this->customerMap()); + } + +} diff --git a/tests/phpunit-headless/CRM/Square/HeadlessTestCase.php b/tests/phpunit-headless/CRM/Square/HeadlessTestCase.php new file mode 100644 index 00000000..5c0fc14d --- /dev/null +++ b/tests/phpunit-headless/CRM/Square/HeadlessTestCase.php @@ -0,0 +1,132 @@ +install(['mjwshared']) + ->installMe(__DIR__) + ->apply(); + } + + protected function setUp(): void { + parent::setUp(); + $this->processor = PaymentProcessor::create(FALSE) + ->setValues([ + 'payment_processor_type_id:name' => 'Square', + 'name' => 'Square headless test', + 'is_test' => FALSE, + 'is_active' => TRUE, + 'user_name' => 'application-id', + 'password' => 'access-token', + 'signature' => 'LOCATION-1', + 'subject' => 'signature-key', + ]) + ->execute() + ->single(); + } + + /** + * A Gateway for the test processor, using the given Square client. + * + * @param \Square\SquareClient $client + * + * @return \CRM_Square_Gateway + */ + protected function gateway(SquareClient $client): CRM_Square_Gateway { + return new CRM_Square_Gateway($this->processor, fn () => $client); + } + + /** + * A SquareClient that never reaches Square. + * + * @param array $subClients + * Mocked sub-clients, by SquareClient property name. + * + * @return \Square\SquareClient + */ + protected function squareClient(array $subClients = []): SquareClient { + $client = new SquareClient(token: 'test-token', options: ['baseUrl' => 'https://example.invalid']); + foreach ($subClients as $property => $subClient) { + $client->$property = $subClient; + } + return $client; + } + + /** + * Create an individual, optionally with a primary email. + * + * @param string $firstName + * @param string|null $email + * + * @return int + */ + protected function createContact(string $firstName, ?string $email = NULL): int { + $contactId = (int) Contact::create(FALSE) + ->setValues(['contact_type' => 'Individual', 'first_name' => $firstName, 'last_name' => 'Doe']) + ->execute() + ->single()['id']; + if ($email) { + Email::create(FALSE) + ->setValues(['contact_id' => $contactId, 'email' => $email, 'is_primary' => TRUE]) + ->execute(); + } + return $contactId; + } + + /** + * Map a Square customer to a contact for the test processor. + * + * @param int $contactId + * @param string $customerId + */ + protected function mapCustomer(int $contactId, string $customerId): void { + CRM_Core_DAO::executeQuery( + 'INSERT INTO square_customer_map (contact_id, payment_processor_id, square_customer_id) VALUES (%1, %2, %3)', + [1 => [$contactId, 'Integer'], 2 => [$this->processor['id'], 'Integer'], 3 => [$customerId, 'String']] + ); + } + + /** + * The test processor's customer mappings, as square_customer_id => contact_id. + * + * @return array + */ + protected function customerMap(): array { + $map = []; + $dao = CRM_Core_DAO::executeQuery( + 'SELECT square_customer_id, contact_id FROM square_customer_map WHERE payment_processor_id = %1', + [1 => [$this->processor['id'], 'Integer']] + ); + while ($dao->fetch()) { + $map[$dao->square_customer_id] = (int) $dao->contact_id; + } + return $map; + } + +} diff --git a/tests/phpunit-headless/CRM/Square/LedgerHeadlessTest.php b/tests/phpunit-headless/CRM/Square/LedgerHeadlessTest.php new file mode 100644 index 00000000..4dd97962 --- /dev/null +++ b/tests/phpunit-headless/CRM/Square/LedgerHeadlessTest.php @@ -0,0 +1,314 @@ +assertGreaterThan(0, $inProgress); + $this->assertSame($inProgress, CRM_Square_Status::recurStatusId('In Progress')); + $this->assertSame($inProgress, CRM_Square_Status::mapSubscriptionStatus('ACTIVE')); + $this->assertSame(CRM_Square_Status::recurStatusId('Cancelled'), CRM_Square_Status::mapSubscriptionStatus('CANCELED')); + } + + public function testContributionStatusesHaveNoInProgress(): void { + // Why recurring statuses need recurStatusId(): on a 6.16 schema this + // status exists only for recurring contributions. + $this->expectException(CRM_Core_Exception::class); + CRM_Square_Status::contributionStatusId('In Progress'); + } + + public function testInstallmentsRefundAndCancellationAreRecorded(): void { + $contactId = $this->createContact('Pat'); + $recurId = $this->createRecur($contactId); + $signupId = $this->createPendingContribution($contactId, $recurId); + $reconciler = $this->reconciler(); + + // The first invoice completes the checkout's Pending contribution. + $this->squareBills('ORDER-1', 'PAYMENT-1'); + $reconciler->handleInvoicePaymentCreated($this->invoicePaidEvent('INVOICE-1', 'ORDER-1')); + + $this->assertSame('Completed', $this->contributionStatus($signupId)); + $this->assertSame(['PAYMENT-1'], $this->paymentTrxnIds($signupId)); + $this->assertSame(CRM_Square_Status::recurStatusId('In Progress'), $this->recur($recurId)['contribution_status_id']); + + // Square reports its processing fee in a later payment.updated: it is + // recorded on the payment and the contribution alike. + $reconciler->syncPaymentFromSquare([ + 'id' => 'PAYMENT-1', + 'status' => 'COMPLETED', + 'processing_fee' => [['amount_money' => ['amount' => 93, 'currency' => 'USD']]], + ]); + $this->assertSame(0.93, (float) Contribution::get(FALSE)->addSelect('fee_amount')->addWhere('id', '=', $signupId)->execute()->single()['fee_amount']); + $this->assertSame(0.93, (float) Payment::get(FALSE)->addSelect('fee_amount')->addWhere('trxn_id', '=', 'PAYMENT-1')->execute()->single()['fee_amount']); + + // The second creates the next contribution of the series, and replays + // record nothing further. + $this->squareBills('ORDER-2', 'PAYMENT-2'); + $reconciler->handleInvoicePaymentCreated($this->invoicePaidEvent('INVOICE-2', 'ORDER-2')); + $reconciler->handleInvoicePaymentCreated($this->invoicePaidEvent('INVOICE-2', 'ORDER-2')); + + $series = $this->seriesContributions($recurId); + $this->assertCount(2, $series); + $second = $series[1]; + $this->assertSame('Completed', $second['contribution_status_id:name']); + $this->assertSame(19.0, (float) $second['total_amount']); + $this->assertSame(['PAYMENT-2'], $this->paymentTrxnIds((int) $second['id'])); + + // A completed refund of the second installment, reported twice. + $refund = [ + 'id' => 'REFUND-1', + 'payment_id' => 'PAYMENT-2', + 'status' => 'COMPLETED', + 'amount_money' => ['amount' => 1900, 'currency' => 'USD'], + ]; + $reconciler->syncRefundFromSquare($refund); + $reconciler->syncRefundFromSquare($refund); + + $refunds = Payment::get(FALSE) + ->addSelect('total_amount') + ->addWhere('contribution_id', '=', $second['id']) + ->addWhere('trxn_id', '=', 'REFUND-1') + ->execute(); + $this->assertCount(1, $refunds); + $this->assertSame(-19.0, (float) $refunds->first()['total_amount']); + + // What doRefund() keys a refund's idempotency on. + $processorRow = $this->processor; + $square = new class('live', $processorRow) extends CRM_Core_Payment_Square { + + public function refundContext(string $paymentId): array { + return $this->getRefundContext($paymentId); + } + + }; + $this->assertSame(['USD', 1], $square->refundContext('PAYMENT-2')); + $this->assertSame(['USD', 0], $square->refundContext('PAYMENT-1')); + $this->assertSame([NULL, 0], $square->refundContext('PAYMENT-UNKNOWN')); + + // Cancelled at Square: arrives as subscription.updated. + $this->subscriptions[self::SUBSCRIPTION_ID] = new Subscription([ + 'id' => self::SUBSCRIPTION_ID, + 'status' => 'CANCELED', + 'canceledDate' => '2026-10-15', + ]); + $reconciler->syncSubscriptionFromSquare(self::SUBSCRIPTION_ID); + + $recur = $this->recur($recurId); + $this->assertSame(CRM_Square_Status::recurStatusId('Cancelled'), $recur['contribution_status_id']); + $this->assertSame('2026-10-15 00:00:00', $recur['cancel_date']); + } + + /** + * The reconciler for the test processor, with Square mocked. + * + * @return \CRM_Square_Reconciler + */ + private function reconciler(): CRM_Square_Reconciler { + $orders = $this->createMock(OrdersClient::class); + $orders->method('get')->willReturnCallback(fn ($request) => new GetOrderResponse([ + 'order' => $this->orders[$request->getOrderId()] ?? NULL, + ])); + $subscriptions = $this->createMock(SubscriptionsClient::class); + $subscriptions->method('get')->willReturnCallback(fn ($request) => new GetSubscriptionResponse([ + 'subscription' => $this->subscriptions[$request->getSubscriptionId()] ?? NULL, + ])); + return new CRM_Square_Reconciler($this->gateway($this->squareClient([ + 'orders' => $orders, + 'subscriptions' => $subscriptions, + ]))); + } + + /** + * Make Square show an invoice's order as paid by a payment. + * + * @param string $orderId + * @param string $paymentId + */ + private function squareBills(string $orderId, string $paymentId): void { + $this->orders[$orderId] = new Order([ + 'id' => $orderId, + 'locationId' => 'LOCATION-1', + 'tenders' => [ + new Tender([ + 'type' => 'CARD', + 'paymentId' => $paymentId, + 'amountMoney' => new Money(['amount' => 1900, 'currency' => 'USD']), + 'createdAt' => gmdate('Y-m-d\TH:i:s\Z'), + ]), + ], + ]); + } + + /** + * An invoice.payment_made payload. + * + * @param string $invoiceId + * @param string $orderId + * + * @return array + */ + private function invoicePaidEvent(string $invoiceId, string $orderId): array { + return [ + 'data' => [ + 'object' => [ + 'invoice' => [ + 'id' => $invoiceId, + 'order_id' => $orderId, + 'subscription_id' => self::SUBSCRIPTION_ID, + 'status' => 'PAID', + 'updated_at' => gmdate('Y-m-d\TH:i:s\Z'), + ], + ], + ], + ]; + } + + /** + * A Pending recurring contribution linked to the test subscription. + * + * @param int $contactId + * + * @return int + */ + private function createRecur(int $contactId): int { + return (int) ContributionRecur::create(FALSE) + ->setValues([ + 'contact_id' => $contactId, + 'amount' => 19.00, + 'currency' => 'USD', + 'frequency_unit' => 'month', + 'frequency_interval' => 1, + 'financial_type_id:name' => 'Donation', + 'payment_processor_id' => $this->processor['id'], + 'processor_id' => self::SUBSCRIPTION_ID, + 'contribution_status_id:name' => 'Pending', + 'is_test' => FALSE, + // No receipt emails from a test. + 'is_email_receipt' => FALSE, + ]) + ->execute() + ->single()['id']; + } + + /** + * The Pending contribution CiviCRM's checkout creates for the first installment. + * + * @param int $contactId + * @param int $recurId + * + * @return int + */ + private function createPendingContribution(int $contactId, int $recurId): int { + return (int) Contribution::create(FALSE) + ->setValues([ + 'contact_id' => $contactId, + 'contribution_recur_id' => $recurId, + 'total_amount' => 19.00, + 'currency' => 'USD', + 'financial_type_id:name' => 'Donation', + 'contribution_status_id:name' => 'Pending', + 'payment_processor_id' => $this->processor['id'], + 'is_pay_later' => FALSE, + 'is_test' => FALSE, + ]) + ->execute() + ->single()['id']; + } + + /** + * @param int $contributionId + * + * @return string + */ + private function contributionStatus(int $contributionId): string { + return Contribution::get(FALSE) + ->addSelect('contribution_status_id:name') + ->addWhere('id', '=', $contributionId) + ->execute() + ->single()['contribution_status_id:name']; + } + + /** + * The trxn_ids of the (positive) payments recorded on a contribution. + * + * @param int $contributionId + * + * @return string[] + */ + private function paymentTrxnIds(int $contributionId): array { + return Payment::get(FALSE) + ->addSelect('trxn_id') + ->addWhere('contribution_id', '=', $contributionId) + ->addWhere('total_amount', '>', 0) + ->execute() + ->column('trxn_id'); + } + + /** + * @param int $recurId + * + * @return array + */ + private function recur(int $recurId): array { + $recur = ContributionRecur::get(FALSE) + ->addSelect('contribution_status_id', 'cancel_date') + ->addWhere('id', '=', $recurId) + ->execute() + ->single(); + $recur['contribution_status_id'] = (int) $recur['contribution_status_id']; + return $recur; + } + + /** + * @param int $recurId + * + * @return array + */ + private function seriesContributions(int $recurId): array { + return Contribution::get(FALSE) + ->addSelect('id', 'total_amount', 'contribution_status_id:name') + ->addWhere('contribution_recur_id', '=', $recurId) + ->addWhere('is_template', '=', FALSE) + ->addOrderBy('id') + ->execute() + ->getArrayCopy(); + } + +} diff --git a/tests/phpunit-headless/bootstrap.php b/tests/phpunit-headless/bootstrap.php new file mode 100644 index 00000000..983bf5f3 --- /dev/null +++ b/tests/phpunit-headless/bootstrap.php @@ -0,0 +1,76 @@ +add('CRM_', [$extensionRoot, __DIR__]); +$loader->register(); + +/** + * Call the "cv" command. + * + * @param string $cmd + * The rest of the command to send. + * @param string $decode + * Ex: 'json' or 'phpcode'. + * + * @return mixed + * Response output (if the command executed normally). + * For 'raw' or 'phpcode', this will be a string. For 'json', it could be any JSON value. + * + * @throws \RuntimeException + * If the command terminates abnormally. + */ +function cv(string $cmd, string $decode = 'json') { + $cmd = 'cv ' . $cmd; + $descriptorSpec = [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => STDERR]; + $oldOutput = getenv('CV_OUTPUT'); + putenv('CV_OUTPUT=json'); + + // Execute `cv` in the original folder. This is a work-around for + // phpunit/codeception, which seem to manipulate PWD. + $cmd = sprintf('cd %s; %s', escapeshellarg(getenv('PWD')), $cmd); + + $process = proc_open($cmd, $descriptorSpec, $pipes, __DIR__); + putenv("CV_OUTPUT=$oldOutput"); + fclose($pipes[0]); + $result = stream_get_contents($pipes[1]); + fclose($pipes[1]); + if (proc_close($process) !== 0) { + throw new RuntimeException("Command failed ($cmd):\n$result"); + } + switch ($decode) { + case 'raw': + return $result; + + case 'phpcode': + // If the last output is /*PHPCODE*/, then we managed to complete execution. + if (substr(trim($result), 0, 12) !== '/*BEGINPHP*/' || substr(trim($result), -10) !== '/*ENDPHP*/') { + throw new RuntimeException("Command failed ($cmd):\n$result"); + } + return $result; + + case 'json': + return json_decode($result, TRUE); + + default: + throw new RuntimeException("Bad decoder format ($decode)"); + } +} diff --git a/tests/phpunit-headless/phpunit.xml.dist b/tests/phpunit-headless/phpunit.xml.dist new file mode 100644 index 00000000..cb35ad41 --- /dev/null +++ b/tests/phpunit-headless/phpunit.xml.dist @@ -0,0 +1,26 @@ + + + + + + ./CRM + + + + + + diff --git a/tests/phpunit/CRM/Core/Payment/Square/ChangeSubscriptionAmountTest.php b/tests/phpunit/CRM/Core/Payment/Square/ChangeSubscriptionAmountTest.php index 44902cc0..63be00bd 100644 --- a/tests/phpunit/CRM/Core/Payment/Square/ChangeSubscriptionAmountTest.php +++ b/tests/phpunit/CRM/Core/Payment/Square/ChangeSubscriptionAmountTest.php @@ -37,6 +37,17 @@ public function testAmountChangeIsSentToSquare(): void { $this->assertSame(3, $this->updates[0]->getSubscription()->getVersion()); } + /** + * The form passes the amount as typed, thousands separator and all. + */ + public function testFormattedAmountIsAccepted(): void { + $message = ''; + + $this->processor()->changeSubscriptionAmount($message, $this->formParams(['amount' => '1,250.50'])); + + $this->assertSame(125050, $this->updates[0]->getSubscription()->getPriceOverrideMoney()->getAmount()); + } + /** * CiviCRM would save new installments Square cannot apply. */ diff --git a/tests/phpunit/CRM/Core/Payment/Square/ExceptionHandlingTest.php b/tests/phpunit/CRM/Core/Payment/Square/ExceptionHandlingTest.php index 6d944e07..2068e116 100644 --- a/tests/phpunit/CRM/Core/Payment/Square/ExceptionHandlingTest.php +++ b/tests/phpunit/CRM/Core/Payment/Square/ExceptionHandlingTest.php @@ -126,16 +126,75 @@ public static function nonDeclineErrorProvider(): array { ]; } - public function testTransportFailureKeepsItsRetryableException(): void { + public function testUnconfirmedChargeKeepsTheContributionPageContributionPending(): void { $paymentsMock = $this->createMock(PaymentsClient::class); $paymentsMock->method('create')->willThrowException(new SquareException('connection timed out')); $processor = $this->processorWithMockClient(['payments' => $paymentsMock]); - - $this->expectException(CRM_Core_Payment_SquareRetryableException::class); - $this->expectExceptionMessage('Square API request failed: connection timed out'); $params = ['token' => 'cnon:timeout', 'amount' => '10.00', 'invoiceID' => 'inv-timeout']; - $processor->doPayment($params); + + try { + $processor->doPayment($params); + $this->fail('An unconfirmed charge must throw.'); + } + catch (PaymentProcessorException $e) { + $this->fail('Square may have charged the card: CiviCRM must not mark the contribution Failed.'); + } + catch (CRM_Core_Payment_SquareOutcomeUnknownException $e) { + $this->assertStringContainsString('could not confirm', $e->getMessage()); + $this->assertInstanceOf(CRM_Core_Payment_SquareRetryableException::class, $e->getPrevious()); + } + $this->assertLogged('error', 'could not confirm the outcome of payment inv-timeout'); + } + + public function testUnconfirmedChargeAtEventRegistrationIsAPaymentFailure(): void { + $paymentsMock = $this->createMock(PaymentsClient::class); + $paymentsMock->method('create')->willThrowException($this->apiException(503, [ + ['category' => 'API_ERROR', 'code' => 'SERVICE_UNAVAILABLE', 'detail' => 'Try again.'], + ])); + + $processor = $this->processorWithMockClient(['payments' => $paymentsMock]); + $params = ['token' => 'cnon:503', 'amount' => '10.00', 'invoiceID' => 'inv-event']; + + // Event registration only handles PaymentProcessorException; anything + // else is a fatal error page for the registrant. + $this->expectException(PaymentProcessorException::class); + $this->expectExceptionMessage('could not confirm'); + $processor->doPayment($params, 'event'); + } + + public function testRejectedRequestIsAPaymentFailure(): void { + $paymentsMock = $this->createMock(PaymentsClient::class); + $paymentsMock->method('create')->willThrowException($this->apiException(400, [ + ['category' => 'INVALID_REQUEST_ERROR', 'code' => 'CARD_TOKEN_USED', 'detail' => 'Card nonce already used.'], + ])); + + $processor = $this->processorWithMockClient(['payments' => $paymentsMock]); + $params = ['token' => 'cnon:used', 'amount' => '10.00', 'invoiceID' => 'inv-used']; + + // Square refused the request, so nothing was charged: CiviCRM's checkout + // may clean up as for a decline. + try { + $processor->doPayment($params); + $this->fail('A rejected request must throw.'); + } + catch (PaymentProcessorException $e) { + $this->assertStringNotContainsString('CARD_TOKEN_USED', $e->getMessage()); + $this->assertStringContainsString('CARD_TOKEN_USED', $e->getPrevious()->getMessage()); + } + } + + /** + * Assert a message containing $needle was logged at $level. + */ + private function assertLogged(string $level, string $needle): void { + foreach (Civi::$logged as [$loggedLevel, $message]) { + if ($loggedLevel === $level && str_contains($message, $needle)) { + $this->addToAssertionCount(1); + return; + } + } + $this->fail("Nothing containing '{$needle}' was logged at level {$level}."); } /** diff --git a/tests/phpunit/CRM/Core/Payment/Square/ExternalPaymentTest.php b/tests/phpunit/CRM/Core/Payment/Square/ExternalPaymentTest.php new file mode 100644 index 00000000..f58a7b4d --- /dev/null +++ b/tests/phpunit/CRM/Core/Payment/Square/ExternalPaymentTest.php @@ -0,0 +1,84 @@ +processor = $this->ledgerProcessor(['signature' => self::LOCATION_ID]); + $this->seedCheckout($this->processor); + } + + protected function tearDown(): void { + unset(Civi::$settings['square_import_external_payments']); + parent::tearDown(); + } + + public function testExternalPaymentIsIgnoredByDefault(): void { + $this->deliver($this->externalPaymentEvent(self::LOCATION_ID)); + + $this->assertSame([], $this->processor->createCalls); + $this->assertSame([], $this->processor->payments); + } + + public function testPaymentAtAnotherLocationIsIgnored(): void { + Civi::$settings['square_import_external_payments'] = TRUE; + + $this->deliver($this->externalPaymentEvent('L-TOURNAMENT-POS')); + + $this->assertSame([], $this->processor->createCalls); + } + + public function testPaymentAtThisLocationIsImportedWhenEnabled(): void { + Civi::$settings['square_import_external_payments'] = TRUE; + + $this->deliver($this->externalPaymentEvent(self::LOCATION_ID)); + + $this->assertCount(1, $this->processor->createCalls); + $this->assertSame('PAY-EXTERNAL', $this->processor->createCalls[0]['trxn_id']); + $this->assertSame(25.0, $this->processor->createCalls[0]['total_amount']); + $payments = array_values(array_filter($this->processor->payments, fn ($payment) => $payment['trxn_id'] === 'PAY-EXTERNAL')); + $this->assertCount(1, $payments); + } + + /** + * A payment.updated for a card payment taken outside CiviCRM, two hours ago. + * + * @param string $locationId + * + * @return array + */ + private function externalPaymentEvent(string $locationId): array { + $createdAt = gmdate('Y-m-d\TH:i:s\Z', time() - 7200); + return [ + 'type' => 'payment.updated', + 'event_id' => 'EVENT-EXTERNAL', + 'data' => [ + 'type' => 'payment', + 'id' => 'PAY-EXTERNAL', + 'object' => [ + 'payment' => [ + 'id' => 'PAY-EXTERNAL', + 'status' => 'COMPLETED', + 'source_type' => 'CARD', + 'location_id' => $locationId, + 'amount_money' => ['amount' => 2500, 'currency' => 'USD'], + 'buyer_email_address' => 'pat@example.org', + 'created_at' => $createdAt, + 'updated_at' => $createdAt, + ], + ], + ], + ]; + } + +} diff --git a/tests/phpunit/CRM/Core/Payment/Square/RecurringInstallmentTest.php b/tests/phpunit/CRM/Core/Payment/Square/RecurringInstallmentTest.php index cc7cef29..8444206c 100644 --- a/tests/phpunit/CRM/Core/Payment/Square/RecurringInstallmentTest.php +++ b/tests/phpunit/CRM/Core/Payment/Square/RecurringInstallmentTest.php @@ -112,6 +112,8 @@ public function testProcessingFeeReportedLaterIsRecorded(): void { $this->assertFirstInstallmentRecordedOnce(); $this->assertSame(0.93, $this->processor->contributions[self::SIGNUP_CONTRIBUTION_ID]['fee_amount']); + // On the payment too, so CiviCRM's recalculation from payments keeps it. + $this->assertSame(0.93, reset($this->processor->payments)['fee_amount']); } /** @@ -391,7 +393,7 @@ public static function otherProcessorProvider(): array { * A failed first charge leaves the checkout's contribution Pending — no Failed duplicate. */ public function testFailedFirstChargeKeepsTheCheckoutContributionPending(): void { - $this->deliver($this->invoicePaymentFailedEvent(self::FIRST)); + $this->deliver($this->invoiceScheduledChargeFailedEvent(self::FIRST)); $this->assertCount(1, $this->seriesContributions()); $this->assertSame('Pending', $this->processor->contributions[self::SIGNUP_CONTRIBUTION_ID]['status']); @@ -408,7 +410,7 @@ public function testFailedFirstChargeKeepsTheCheckoutContributionPending(): void public function testFailedLaterInstallmentIsCompletedWhenCollected(): void { $this->payFirstInstallment(); - $this->deliver($this->invoicePaymentFailedEvent(self::SECOND)); + $this->deliver($this->invoiceScheduledChargeFailedEvent(self::SECOND)); $this->assertCount(2, $this->seriesContributions()); $failed = $this->seriesContributions()[1]; $this->assertSame('Failed', $failed['status']); @@ -423,6 +425,36 @@ public function testFailedLaterInstallmentIsCompletedWhenCollected(): void { $this->assertSame(self::SECOND['payment_id'], $this->processor->contributions[$failed['id']]['trxn_id']); } + /** + * A failure of the first invoice delivered after it was paid creates nothing. + * + * Square does not deliver webhooks in order, and retries a failed charge. + * The checkout's contribution carries CiviCRM's invoice ID, not Square's, + * so only Square's current invoice status shows the failure is stale. + */ + public function testDelayedFailureOfAPaidFirstInstallmentCreatesNothing(): void { + $this->payFirstInstallment(); + + $this->deliver($this->invoiceScheduledChargeFailedEvent(self::FIRST)); + + $this->assertCount(1, $this->seriesContributions()); + $this->assertSame([], $this->processor->repeatCalls); + $this->assertSame('Completed', $this->processor->contributions[self::SIGNUP_CONTRIBUTION_ID]['status']); + } + + /** + * A failure of a later invoice delivered after it was paid leaves it Completed. + */ + public function testDelayedFailureOfAPaidLaterInstallmentLeavesItCompleted(): void { + $this->payFirstInstallment(); + $this->squareBills(self::SECOND); + $this->deliver($this->invoicePaymentMadeEvent(self::SECOND)); + + $this->deliver($this->invoiceScheduledChargeFailedEvent(self::SECOND)); + + $this->assertSame(['Completed', 'Completed'], array_column($this->seriesContributions(), 'status')); + } + /** * A one-time payment Square cancels after checkout left it Pending is marked Failed. */ diff --git a/tests/phpunit/CRM/Core/Payment/Square/RefundTest.php b/tests/phpunit/CRM/Core/Payment/Square/RefundTest.php index f48f25ba..11862953 100644 --- a/tests/phpunit/CRM/Core/Payment/Square/RefundTest.php +++ b/tests/phpunit/CRM/Core/Payment/Square/RefundTest.php @@ -15,6 +15,15 @@ class CRM_Core_Payment_Square_RefundTest extends CRM_Core_Payment_Square_SquareL protected function setUp(): void { parent::setUp(); $this->payFirstInstallment(); + $lock = $this->getMockBuilder(stdClass::class)->addMethods(['isAcquired', 'release'])->getMock(); + $lock->method('isAcquired')->willReturn(TRUE); + Civi::$lockManager = $this->getMockBuilder(stdClass::class)->addMethods(['acquire'])->getMock(); + Civi::$lockManager->method('acquire')->willReturn($lock); + } + + protected function tearDown(): void { + Civi::$lockManager = NULL; + parent::tearDown(); } public function testPendingRefundRecordsNothing(): void { @@ -24,6 +33,43 @@ public function testPendingRefundRecordsNothing(): void { $this->assertSame('Completed', $this->processor->contributions[self::SIGNUP_CONTRIBUTION_ID]['status']); } + /** + * A refund CiviCRM recorded that Square then reports rejected. + * + * CiviCRM records only refunds Square has completed (see doRefund()), so + * this should not happen; if it does, it is reported for manual follow-up. + * + * @dataProvider refusedRefundStatusProvider + */ + public function testRefusedRefundAlreadyRecordedIsReportedNotReversed(string $status): void { + $this->processor->payments[800] = [ + 'contribution_id' => self::SIGNUP_CONTRIBUTION_ID, + 'trxn_id' => self::REFUND_ID, + 'total_amount' => -19.00, + 'payment_processor_id' => self::PROCESSOR_ID, + ]; + + $this->deliver($this->refundEvent('refund.updated', $status, 1900)); + + $this->assertCount(1, $this->refunds()); + $expected = "Square refund REFUND-1 of payment " . self::FIRST['payment_id'] . " was {$status}, but CiviCRM recorded it as refunded on contribution " . self::SIGNUP_CONTRIBUTION_ID . '; reverse that refund manually.'; + $this->assertSame([['error', $expected]], Civi::$logged); + } + + /** + * @dataProvider refusedRefundStatusProvider + */ + public function testRefusedRefundNeverRecordedIsIgnored(string $status): void { + $this->deliver($this->refundEvent('refund.updated', $status, 1900)); + + $this->assertSame([], $this->refunds()); + $this->assertSame([], Civi::$logged); + } + + public static function refusedRefundStatusProvider(): array { + return [['REJECTED'], ['FAILED']]; + } + /** * A full refund reverses the refunded payment, as Payment.cancel does. */ @@ -81,16 +127,151 @@ public function testRefundAlreadyRecordedFromCiviCrmIsSkipped(): void { $this->assertCount(1, $this->refunds()); } + public function testAdminRefundCompletedWhileAcquiringLockIsNotRecordedTwice(): void { + $lock = $this->getMockBuilder(stdClass::class)->addMethods(['isAcquired', 'release'])->getMock(); + $lock->method('isAcquired')->willReturn(TRUE); + $lock->expects($this->once())->method('release'); + Civi::$lockManager = $this->getMockBuilder(stdClass::class)->addMethods(['acquire'])->getMock(); + Civi::$lockManager->expects($this->once())->method('acquire') + ->with('data.contribute.contribution.' . self::SIGNUP_CONTRIBUTION_ID) + ->willReturnCallback(function () use ($lock) { + // The admin action finishes recording while the webhook waits for + // its contribution lock. The duplicate lookup must happen afterwards. + $this->processor->payments[800] = [ + 'contribution_id' => self::SIGNUP_CONTRIBUTION_ID, + 'trxn_id' => self::REFUND_ID, + 'total_amount' => -5.00, + 'payment_processor_id' => self::PROCESSOR_ID, + ]; + return $lock; + }); + + $this->deliver($this->refundEvent('refund.updated', 'COMPLETED', 500)); + + $this->assertCount(1, $this->refunds()); + $this->assertSame(-5.00, array_sum(array_column($this->refunds(), 'total_amount'))); + } + + public function testBusyContributionLockLeavesRefundForRetry(): void { + $lock = $this->getMockBuilder(stdClass::class)->addMethods(['isAcquired', 'release'])->getMock(); + $lock->method('isAcquired')->willReturn(FALSE); + $lock->expects($this->never())->method('release'); + Civi::$lockManager = $this->getMockBuilder(stdClass::class)->addMethods(['acquire'])->getMock(); + Civi::$lockManager->expects($this->once())->method('acquire') + ->with('data.contribute.contribution.' . self::SIGNUP_CONTRIBUTION_ID)->willReturn($lock); + + try { + $this->deliver($this->refundEvent('refund.updated', 'COMPLETED', 500)); + $this->fail('Lock contention must leave the webhook for retry.'); + } + catch (CRM_Core_Payment_SquareRetryableException $e) { + $this->assertStringContainsString('Could not acquire lock', $e->getMessage()); + } + $this->assertSame([], $this->refunds()); + } + + public function testContributionLockCoversDuplicateCheckAndWrite(): void { + $held = FALSE; + $lock = $this->getMockBuilder(stdClass::class)->addMethods(['isAcquired', 'release'])->getMock(); + $lock->method('isAcquired')->willReturn(TRUE); + $lock->expects($this->once())->method('release')->willReturnCallback(function () use (&$held) { + $held = FALSE; + }); + Civi::$lockManager = $this->getMockBuilder(stdClass::class)->addMethods(['acquire'])->getMock(); + Civi::$lockManager->expects($this->once())->method('acquire') + ->with('data.contribute.contribution.' . self::SIGNUP_CONTRIBUTION_ID) + ->willReturnCallback(function () use ($lock, &$held) { + $held = TRUE; + return $lock; + }); + $reconciler = $this->getMockBuilder(CRM_Core_Payment_Square_FakeLedgerReconciler::class) + ->setConstructorArgs([$this->callMethod($this->processor, 'gateway'), $this->processor]) + ->onlyMethods(['findContributionPayment', 'recordRefundPayment'])->getMock(); + $reconciler->expects($this->once())->method('findContributionPayment') + ->with(self::SIGNUP_CONTRIBUTION_ID, self::REFUND_ID) + ->willReturnCallback(function () use (&$held) { + $this->assertTrue($held, 'The duplicate check must hold the contribution lock.'); + return NULL; + }); + $reconciler->expects($this->once())->method('recordRefundPayment') + ->willReturnCallback(function () use (&$held) { + $this->assertTrue($held, 'The refund write must still hold the contribution lock.'); + }); + + $event = $this->refundEvent('refund.updated', 'COMPLETED', 500); + $reconciler->syncRefundFromSquare($event['data']['object']['refund']); + + $this->assertFalse($held); + } + /** - * A refund of a payment no contribution here records is ignored. + * @dataProvider failingRefundOperationProvider + */ + public function testContributionLockReleasedOnFailure(string $operation): void { + $lock = $this->getMockBuilder(stdClass::class)->addMethods(['isAcquired', 'release'])->getMock(); + $lock->method('isAcquired')->willReturn(TRUE); + $lock->expects($this->once())->method('release'); + Civi::$lockManager = $this->getMockBuilder(stdClass::class)->addMethods(['acquire'])->getMock(); + Civi::$lockManager->expects($this->once())->method('acquire') + ->with('data.contribute.contribution.' . self::SIGNUP_CONTRIBUTION_ID)->willReturn($lock); + $reconciler = $this->getMockBuilder(CRM_Core_Payment_Square_FakeLedgerReconciler::class) + ->setConstructorArgs([$this->callMethod($this->processor, 'gateway'), $this->processor]) + ->onlyMethods([$operation])->getMock(); + $reconciler->expects($this->once())->method($operation)->willThrowException(new RuntimeException('Ledger failed.')); + + $event = $this->refundEvent('refund.updated', 'COMPLETED', 500); + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Ledger failed.'); + $reconciler->syncRefundFromSquare($event['data']['object']['refund']); + } + + public static function failingRefundOperationProvider(): array { + return [['findContributionPayment'], ['recordRefundPayment']]; + } + + /** + * A refund of a payment no contribution here records is ignored, once it is old. */ public function testRefundOfAnUnknownPaymentIsIgnored(): void { - $event = $this->refundEvent('refund.updated', 'COMPLETED', 1900); - $event['data']['object']['refund']['payment_id'] = 'SOMEONE-ELSES-PAYMENT'; + $event = $this->refundEvent('refund.updated', 'COMPLETED', 1900, 'SOMEONE-ELSES-PAYMENT', gmdate('Y-m-d\TH:i:s\Z', time() - 7200)); + + $this->deliver($event); + + $this->assertSame([], $this->refunds()); + } + /** + * A recent refund of a payment not recorded yet is retried, not dropped. + */ + public function testRefundOfAPaymentNotRecordedYetIsRetried(): void { + $event = $this->refundEvent('refund.updated', 'COMPLETED', 1900, self::SECOND['payment_id']); + + $this->expectException(CRM_Core_Payment_SquareRetryableException::class); $this->deliver($event); + } + /** + * Square does not deliver webhooks in order: the refund may come first. + */ + public function testRefundDeliveredBeforeItsPaymentIsRecordedOnRetry(): void { + $refund = $this->refundEvent('refund.updated', 'COMPLETED', 1900, self::SECOND['payment_id']); + try { + $this->deliver($refund); + $this->fail('The refund should have been left for a retry.'); + } + catch (CRM_Core_Payment_SquareRetryableException $e) { + // Left 'new' in the queue for the scheduled job. + } $this->assertSame([], $this->refunds()); + + $this->squareBills(self::SECOND); + $this->deliver($this->invoicePaymentMadeEvent(self::SECOND)); + // The scheduled job retries the refund. + $this->deliver($refund); + + $refunds = $this->refunds(); + $this->assertCount(1, $refunds); + $this->assertSame(self::REFUND_ID, reset($refunds)['trxn_id']); } /** @@ -167,11 +348,15 @@ private function originalPaymentId(): int { * @param string $type * @param string $status * @param int $amountCents + * @param string $paymentId + * The refunded Square payment; the first installment's by default. + * @param string|null $createdAt + * When Square created the refund; now by default. * * @return array */ - private function refundEvent(string $type, string $status, int $amountCents): array { - $now = gmdate('Y-m-d\TH:i:s\Z'); + private function refundEvent(string $type, string $status, int $amountCents, string $paymentId = self::FIRST['payment_id'], ?string $createdAt = NULL): array { + $now = $createdAt ?? gmdate('Y-m-d\TH:i:s\Z'); return [ 'type' => $type, 'event_id' => bin2hex(random_bytes(8)), @@ -180,7 +365,7 @@ private function refundEvent(string $type, string $status, int $amountCents): ar 'object' => [ 'refund' => [ 'id' => self::REFUND_ID, - 'payment_id' => self::FIRST['payment_id'], + 'payment_id' => $paymentId, 'status' => $status, 'amount_money' => ['amount' => $amountCents, 'currency' => 'USD'], 'created_at' => $now, diff --git a/tests/phpunit/CRM/Core/Payment/Square/RequestShapeTest.php b/tests/phpunit/CRM/Core/Payment/Square/RequestShapeTest.php index a2bac613..de30f0f8 100644 --- a/tests/phpunit/CRM/Core/Payment/Square/RequestShapeTest.php +++ b/tests/phpunit/CRM/Core/Payment/Square/RequestShapeTest.php @@ -2,7 +2,8 @@ require_once __DIR__ . '/SquareUnitTestCase.php'; -use Square\Types\Money; +use Civi\Payment\Exception\PaymentProcessorException; +use Square\SquareClient; use Square\Cards\Requests\CreateCardRequest; use Square\Cards\CardsClient; use Square\Payments\PaymentsClient; @@ -56,6 +57,23 @@ public function testOneTimePaymentRequestShape(): void { $this->assertSame('pay_1', $result['trxn_id']); } + public function testOneTimePaymentInACurrencyWithoutCentsIsNotMultiplied(): void { + $captured = NULL; + $paymentsMock = $this->createMock(PaymentsClient::class); + $paymentsMock->method('create')->willReturnCallback(function (CreatePaymentRequest $request) use (&$captured) { + $captured = $request; + return new CreatePaymentResponse(['payment' => new Payment(['id' => 'pay_jpy', 'status' => 'COMPLETED'])]); + }); + + $processor = $this->processorWithMockClient(['payments' => $paymentsMock]); + $params = ['square_payment_token' => 'cnon:yen', 'amount' => '100', 'currency' => 'JPY', 'invoiceID' => 'inv-jpy']; + $processor->doPayment($params); + + // Square amounts are in the currency's smallest unit: whole yen. + $this->assertSame(100, $captured->getAmountMoney()->getAmount()); + $this->assertSame('JPY', $captured->getAmountMoney()->getCurrency()); + } + public function testOneTimePaymentOmitsReferenceIdWhenNoInvoiceId(): void { $captured = NULL; $paymentsMock = $this->createMock(PaymentsClient::class); @@ -78,10 +96,15 @@ public function testOneTimePaymentFailsClosedWithoutACheckoutReference(): void { $processor = $this->processorWithMockClient(['payments' => $paymentsMock]); $params = ['token' => 'cnon:no-reference', 'amount' => '5.00']; - // A retry could not be recognized without one, so it is never charged. - $this->expectException(CRM_Core_Exception::class); - $this->expectExceptionMessage('without a CiviCRM invoice or contribution reference'); - $processor->doPayment($params); + // A retry could not be recognized without one, so it is never charged, + // and CiviCRM's checkout is told the payment failed. + try { + $processor->doPayment($params); + $this->fail('A payment without a checkout reference must not be taken.'); + } + catch (PaymentProcessorException $e) { + $this->assertStringContainsString('without a CiviCRM invoice or contribution reference', $e->getPrevious()->getMessage()); + } } public function testAuthorizedButUncapturedPaymentIsReportedPending(): void { @@ -100,30 +123,111 @@ public function testAuthorizedButUncapturedPaymentIsReportedPending(): void { } public function testRefundRequestShape(): void { - $captured = NULL; + $captured = []; + $processor = $this->refundingProcessor($captured, ['CAD', 0]); + $params = ['trxn_id' => 'pay_99', 'amount' => '5.00', 'currency' => 'USD']; + $processor->doRefund($params); + + $this->assertSame('pay_99', $captured[0]->getPaymentId()); + $this->assertSame(500, $captured[0]->getAmountMoney()->getAmount()); + // The recorded payment's own currency, whatever the caller passed. + $this->assertSame('CAD', $captured[0]->getAmountMoney()->getCurrency()); + $this->assertNotEmpty($captured[0]->getIdempotencyKey()); + $this->assertLessThanOrEqual(45, strlen($captured[0]->getIdempotencyKey())); + } + + public function testRefundInACurrencyWithoutCentsIsNotMultiplied(): void { + $captured = []; + $params = ['trxn_id' => 'pay_yen', 'amount' => '100']; + $this->refundingProcessor($captured, ['JPY', 0])->doRefund($params); + + $this->assertSame(100, $captured[0]->getAmountMoney()->getAmount()); + $this->assertSame('JPY', $captured[0]->getAmountMoney()->getCurrency()); + } + + public function testRefundOfAPaymentCiviCrmDoesNotKnowUsesTheGivenCurrency(): void { + $captured = []; + $params = ['trxn_id' => 'pay_99', 'amount' => '5.00', 'currencyID' => 'CAD']; + $this->refundingProcessor($captured, [NULL, 0])->doRefund($params); + + $this->assertSame('CAD', $captured[0]->getAmountMoney()->getCurrency()); + } + + public function testRefundIdempotencyKeyDistinguishesRepeatedRefundsOfTheSameAmount(): void { + $params = ['trxn_id' => 'pay_99', 'amount' => '5.00']; + $first = []; + $this->refundingProcessor($first, ['USD', 0])->doRefund($params); + // The first refund's outcome was lost, so CiviCRM recorded nothing. + $retry = []; + $this->refundingProcessor($retry, ['USD', 0])->doRefund($params); + // CiviCRM recorded the first refund. + $second = []; + $this->refundingProcessor($second, ['USD', 1])->doRefund($params); + + // The retry gets Square's original refund back, not a second refund... + $this->assertSame($first[0]->getIdempotencyKey(), $retry[0]->getIdempotencyKey()); + // ...but a further $5 refund of the payment is a new refund. + $this->assertNotSame($first[0]->getIdempotencyKey(), $second[0]->getIdempotencyKey()); + } + + /** + * A processor with a mocked Square, capturing refund requests. + * + * @param array $captured + * Receives each RefundPaymentRequest sent. + * @param array $refundContext + * What getRefundContext() returns: the recorded payment's currency + * (NULL if not recorded), and the refunds CiviCRM has recorded. + */ + private function refundingProcessor(array &$captured, array $refundContext): CRM_Core_Payment_Square { $refundsMock = $this->createMock(RefundsClient::class); $refundsMock->method('refundPayment')->willReturnCallback(function ($request) use (&$captured) { - $captured = $request; + $captured[] = $request; return new RefundPaymentResponse([ 'refund' => new PaymentRefund([ - 'id' => 'refund_1', + 'id' => 'refund_' . count($captured), 'status' => 'COMPLETED', - 'amountMoney' => new Money(['amount' => 500, 'currency' => 'USD']), + 'amountMoney' => $request->getAmountMoney(), ]), ]); }); + $client = new SquareClient(token: 'test-token', options: ['baseUrl' => 'https://example.invalid']); + $client->refunds = $refundsMock; + $config = $this->processorConfig(); - $processor = $this->processorWithMockClient(['refunds' => $refundsMock]); - $params = ['trxn_id' => 'pay_99', 'amount' => '5.00', 'currency' => 'USD']; - $processor->doRefund($params); + return new class($config, $client, $refundContext) extends CRM_Core_Payment_Square { - $this->assertSame('pay_99', $captured->getPaymentId()); - $this->assertSame(500, $captured->getAmountMoney()->getAmount()); - $this->assertNotEmpty($captured->getIdempotencyKey()); - $this->assertLessThanOrEqual(45, strlen($captured->getIdempotencyKey())); + /** + * @var \Square\SquareClient + */ + private SquareClient $mockClient; + + /** + * @var array + */ + private array $refundContext; + + public function __construct(array &$paymentProcessor, SquareClient $mockClient, array $refundContext) { + parent::__construct('live', $paymentProcessor); + $this->mockClient = $mockClient; + $this->refundContext = $refundContext; + } + + protected function buildSquareClient(): SquareClient { + return $this->mockClient; + } + + protected function getRefundContext(string $paymentTrxnId): array { + return $this->refundContext; + } + + }; } - public function testCreateCardOnFileRequestShapeWithBillingAddress(): void { + /** + * @dataProvider billingFieldsProvider + */ + public function testCreateCardOnFileRequestShapeWithBillingAddress(array $billingFields): void { $captured = NULL; $cardsMock = $this->createMock(CardsClient::class); $cardsMock->method('create')->willReturnCallback(function (CreateCardRequest $request) use (&$captured) { @@ -132,17 +236,9 @@ public function testCreateCardOnFileRequestShapeWithBillingAddress(): void { }); $processor = $this->processorWithMockClient(['cards' => $cardsMock]); - $cardId = $processor->createCardOnFile('cust_1', 'cnon:card-nonce', [ - 'billing_address' => [ - 'street_address' => '123 Main St', - 'city' => 'Crossville', - 'state' => 'TN', - 'postal_code' => '38555', - 'country' => 'United States', - ], - // No contactId (4th arg omitted) -> skips PaymentToken creation, which - // needs a real CiviCRM DB unavailable in this suite. - ]); + // No contactId (4th arg omitted) -> skips PaymentToken creation, which + // needs a real CiviCRM DB unavailable in this suite. + $cardId = $processor->createCardOnFile('cust_1', 'cnon:card-nonce', $billingFields); $this->assertSame('card_1', $cardId); $this->assertSame('cnon:card-nonce', $captured->getSourceId()); @@ -152,10 +248,59 @@ public function testCreateCardOnFileRequestShapeWithBillingAddress(): void { $this->assertSame('Crossville', $billingAddress->getLocality()); $this->assertSame('TN', $billingAddress->getAdministrativeDistrictLevel1()); $this->assertSame('38555', $billingAddress->getPostalCode()); - // mapCountryCode() normalizes "United States" -> "US". $this->assertSame('US', $billingAddress->getCountry()); } + public static function billingFieldsProvider(): array { + return [ + 'billing block fields, as submitted' => [ + [ + 'billing_street_address-5' => '123 Main St', + 'billing_city-5' => 'Crossville', + 'billing_state_province-5' => 'TN', + 'billing_postal_code-5' => '38555', + 'billing_country-5' => 'US', + ], + ], + 'state and country submitted by ID' => [ + [ + 'billing_street_address-5' => '123 Main St', + 'billing_city-5' => 'Crossville', + 'billing_state_province_id-5' => '1042', + 'billing_postal_code-5' => '38555', + 'billing_country_id-5' => '1228', + ], + ], + 'as mapped by CiviCRM checkout' => [ + [ + 'street_address' => '123 Main St', + 'city' => 'Crossville', + 'state_province' => 'TN', + 'postal_code' => '38555', + 'country' => 'us', + ], + ], + ]; + } + + public function testCreateCardOnFileNeverGuessesTheCountry(): void { + $captured = NULL; + $cardsMock = $this->createMock(CardsClient::class); + $cardsMock->method('create')->willReturnCallback(function (CreateCardRequest $request) use (&$captured) { + $captured = $request; + return new CreateCardResponse(['card' => new Card(['id' => 'card_3'])]); + }); + + $processor = $this->processorWithMockClient(['cards' => $cardsMock]); + $processor->createCardOnFile('cust_3', 'cnon:named-country', [ + 'billing_postal_code-5' => 'K1A 0B1', + 'billing_country-5' => 'Canada', + ]); + + $this->assertSame('K1A 0B1', $captured->getCard()->getBillingAddress()->getPostalCode()); + $this->assertNull($captured->getCard()->getBillingAddress()->getCountry(), 'Not an ISO code, so not sent — never defaulted to US.'); + } + public function testCreateCardOnFileOmitsBillingAddressWhenNotSupplied(): void { $captured = NULL; $cardsMock = $this->createMock(CardsClient::class); diff --git a/tests/phpunit/CRM/Core/Payment/Square/SquareLedgerTestCase.php b/tests/phpunit/CRM/Core/Payment/Square/SquareLedgerTestCase.php index 76dafe88..efb9c5f0 100644 --- a/tests/phpunit/CRM/Core/Payment/Square/SquareLedgerTestCase.php +++ b/tests/phpunit/CRM/Core/Payment/Square/SquareLedgerTestCase.php @@ -17,7 +17,10 @@ use Square\Types\GetOrderResponse; use Square\Orders\OrdersClient; use Square\Types\SearchInvoicesResponse; +use Square\Types\GetInvoiceResponse; use Square\Invoices\InvoicesClient; +use Square\Subscriptions\SubscriptionsClient; +use Square\Types\GetSubscriptionResponse; use Square\SquareClient; /** @@ -65,6 +68,13 @@ class CRM_Core_Payment_Square_FakeLedgerProcessor extends CRM_Core_Payment_Squar */ public array $createCalls = []; + /** + * Contacts this processor mapped Square customers to, by customer ID. + * + * @var array + */ + public array $customerContacts = []; + /** * Square card ID getRecurCardId() returns. * @@ -135,15 +145,6 @@ public function ensureSquareCustomer(array $params) { return 'CUSTOMER-1'; } - /** - * @param string $customerID - * - * @return string|null - */ - public function findSquareCustomerById($customerID) { - return $customerID; - } - /** * @param string $customerID * @param array $params @@ -264,6 +265,30 @@ protected function findRecurBySubscriptionId(string $subscriptionId): ?array { return NULL; } + /** + * @param int $recurId + * + * @return array|null + */ + protected function findRecurById(int $recurId): ?array { + $recur = $this->ledger->recurs[$recurId] ?? NULL; + if ($recur + && $recur['payment_processor_id'] === $this->gateway->processorId() + && (bool) $recur['is_test'] === $this->gateway->isTestMode()) { + return $recur; + } + return NULL; + } + + /** + * @param string $customerId + * + * @return int|null + */ + protected function findContactIdBySquareCustomer(string $customerId): ?int { + return $this->ledger->customerContacts[$customerId] ?? NULL; + } + /** * @param int $recurId * @@ -465,6 +490,37 @@ protected function findContributionPayment(int $contributionId, string $trxnId): return NULL; } + /** + * @param int $financialTrxnId + * @param float $fee + * @param float $totalAmount + */ + protected function updatePaymentFee(int $financialTrxnId, float $fee, float $totalAmount): void { + $this->ledger->payments[$financialTrxnId]['fee_amount'] = $fee; + } + + /** + * @param int $recurId + * @param array $values + */ + protected function updateRecur(int $recurId, array $values): void { + $this->ledger->recurs[$recurId] = $values + $this->ledger->recurs[$recurId]; + } + + /** + * @param string $refundId + * + * @return array|null + */ + protected function findRecordedRefund(string $refundId): ?array { + foreach ($this->ledger->payments as $id => $payment) { + if ($payment['trxn_id'] === $refundId && $payment['total_amount'] < 0) { + return ['id' => $id, 'contribution_id' => $payment['contribution_id']]; + } + } + return NULL; + } + /** * @param array $params */ @@ -557,6 +613,13 @@ abstract class CRM_Core_Payment_Square_SquareLedgerTestCase extends CRM_Core_Pay */ protected array $squareInvoices = []; + /** + * Subscriptions at (mocked) Square, by ID. + * + * @var \Square\Types\Subscription[] + */ + protected array $squareSubscriptions = []; + /** * Square orders returned by the mocked orders->get, by order ID. * @@ -602,14 +665,23 @@ protected function ledgerProcessor(array $configOverrides = []): CRM_Core_Paymen $this->invoiceSearches++; return new SearchInvoicesResponse(['invoices' => array_values($this->squareInvoices)]); }); + $invoices->method('get')->willReturnCallback(fn ($request) => new GetInvoiceResponse([ + 'invoice' => $this->squareInvoices[$request->getInvoiceId()] ?? NULL, + ])); $orders = $this->createMock(OrdersClient::class); $orders->method('get')->willReturnCallback(fn ($request) => new GetOrderResponse([ 'order' => $this->squareOrders[$request->getOrderId()] ?? NULL, ])); + $subscriptions = $this->createMock(SubscriptionsClient::class); + $subscriptions->method('get')->willReturnCallback(fn ($request) => new GetSubscriptionResponse([ + 'subscription' => $this->squareSubscriptions[$request->getSubscriptionId()] ?? NULL, + ])); + $client = new SquareClient(token: 'test-token', options: ['baseUrl' => 'https://example.invalid']); $client->invoices = $invoices; $client->orders = $orders; + $client->subscriptions = $subscriptions; $config = $this->processorConfig($configOverrides + ['id' => self::PROCESSOR_ID]); return new CRM_Core_Payment_Square_FakeLedgerProcessor($config, $client); } @@ -620,6 +692,7 @@ protected function ledgerProcessor(array $configOverrides = []): CRM_Core_Paymen * @param \CRM_Core_Payment_Square_FakeLedgerProcessor $processor */ protected function seedCheckout(CRM_Core_Payment_Square_FakeLedgerProcessor $processor): void { + $processor->customerContacts[self::CUSTOMER_ID] = 7; $processor->recurs[self::RECUR_ID] = [ 'id' => self::RECUR_ID, 'contact_id' => 7, @@ -697,14 +770,17 @@ protected function invoicePaymentMadeEvent(array $installment, int $amountCents } /** - * An invoice.payment_failed payload. + * An invoice.scheduled_charge_failed payload. + * + * Square's event for a card-on-file charge of a subscription invoice that + * failed; the invoice stays UNPAID. * * @param array $installment * * @return array */ - protected function invoicePaymentFailedEvent(array $installment): array { - return $this->invoiceEvent('invoice.payment_failed', $installment, 'UNPAID', 0); + protected function invoiceScheduledChargeFailedEvent(array $installment): array { + return $this->invoiceEvent('invoice.scheduled_charge_failed', $installment, 'UNPAID', 0); } /** diff --git a/tests/phpunit/CRM/Core/Payment/Square/SubscriptionRecoveryTest.php b/tests/phpunit/CRM/Core/Payment/Square/SubscriptionRecoveryTest.php new file mode 100644 index 00000000..3ac102da --- /dev/null +++ b/tests/phpunit/CRM/Core/Payment/Square/SubscriptionRecoveryTest.php @@ -0,0 +1,127 @@ +processor->recurs[self::RECUR_ID]['processor_id'] = NULL; + } + + public function testFirstInstallmentLinksTheSubscriptionAndCompletesTheCheckout(): void { + $this->squareHasSubscription(['contact_id' => '7', 'recur_id' => (string) self::RECUR_ID]); + + $this->payFirstInstallment(); + + $recur = $this->processor->recurs[self::RECUR_ID]; + $this->assertSame(self::SUBSCRIPTION_ID, $recur['processor_id']); + $this->assertSame(self::SUBSCRIPTION_ID, $recur['trxn_id']); + $this->assertCount(1, $this->seriesContributions()); + $this->assertSame('Completed', $this->processor->contributions[self::SIGNUP_CONTRIBUTION_ID]['status']); + $this->assertSame(self::FIRST['payment_id'], $this->processor->contributions[self::SIGNUP_CONTRIBUTION_ID]['trxn_id']); + } + + public function testSubscriptionWebhookLinksTheSubscription(): void { + $this->squareHasSubscription(['contact_id' => '7', 'recur_id' => (string) self::RECUR_ID]); + + $this->deliver([ + 'type' => 'subscription.created', + 'event_id' => 'EVENT-SUBSCRIPTION-CREATED', + 'data' => [ + 'type' => 'subscription', + 'id' => self::SUBSCRIPTION_ID, + 'object' => ['subscription' => ['id' => self::SUBSCRIPTION_ID]], + ], + ]); + + $this->assertSame(self::SUBSCRIPTION_ID, $this->processor->recurs[self::RECUR_ID]['processor_id']); + $this->assertSame(2, $this->processor->recurs[self::RECUR_ID]['contribution_status_id'], 'Still Pending until its first payment is recorded.'); + } + + /** + * A subscription is linked only if everything about it checks out. + * + * @dataProvider unconfirmedSubscriptionProvider + */ + public function testUnconfirmedSubscriptionIsNotLinked(callable $arrange): void { + $this->squareHasSubscription(['contact_id' => '7', 'recur_id' => (string) self::RECUR_ID]); + $arrange($this); + + try { + $this->payFirstInstallment(); + $this->fail('A recent event for an unlinked subscription should be left for a retry.'); + } + catch (CRM_Core_Payment_SquareRetryableException $e) { + // As for any subscription not linked yet. + } + + $this->assertNotSame(self::SUBSCRIPTION_ID, $this->processor->recurs[self::RECUR_ID]['processor_id'] ?? NULL); + $this->assertSame([], $this->processor->payments); + } + + public static function unconfirmedSubscriptionProvider(): array { + return [ + 'created outside CiviCRM, with no source' => [ + fn (self $test) => $test->squareHasSubscription(NULL), + ], + 'source names another contact' => [ + fn (self $test) => $test->squareHasSubscription(['contact_id' => '8', 'recur_id' => (string) self::RECUR_ID]), + ], + 'customer mapped to another contact' => [ + fn (self $test) => $test->processor->customerContacts[self::CUSTOMER_ID] = 8, + ], + 'customer not mapped at all' => [ + function (self $test) { + $test->processor->customerContacts = []; + }, + ], + 'recurring contribution already linked to another subscription' => [ + fn (self $test) => $test->processor->recurs[self::RECUR_ID]['processor_id'] = 'ANOTHER-SUBSCRIPTION', + ], + 'recurring contribution of another processor' => [ + fn (self $test) => $test->processor->recurs[self::RECUR_ID]['payment_processor_id'] = 43, + ], + 'subscription at another location' => [ + fn (self $test) => $test->squareHasSubscription(['contact_id' => '7', 'recur_id' => (string) self::RECUR_ID], ['locationId' => 'ANOTHER-LOCATION']), + ], + ]; + } + + /** + * Put the test subscription at (mocked) Square. + * + * @param array|null $source + * What doRecurPayment() puts in the subscription's source name; NULL + * for none. + * @param array $values + * Other subscription values to override. + */ + public function squareHasSubscription(?array $source, array $values = []): void { + $values += [ + 'id' => self::SUBSCRIPTION_ID, + 'status' => 'ACTIVE', + 'customerId' => self::CUSTOMER_ID, + // The test processor's location (see processorConfig()). + 'locationId' => 'location-id', + ]; + if ($source !== NULL) { + $values['source'] = new SubscriptionSource(['name' => json_encode($source)]); + } + $this->squareSubscriptions[self::SUBSCRIPTION_ID] = new Subscription($values); + } + +} diff --git a/tests/phpunit/CRM/Core/Payment/Square/SubscriptionSyncTest.php b/tests/phpunit/CRM/Core/Payment/Square/SubscriptionSyncTest.php new file mode 100644 index 00000000..571da604 --- /dev/null +++ b/tests/phpunit/CRM/Core/Payment/Square/SubscriptionSyncTest.php @@ -0,0 +1,133 @@ +payFirstInstallment(); + // As Square sends it when the subscription is cancelled in its + // dashboard: ACTIVE (or PENDING or PAUSED) until the end of the period + // already paid for. + $this->squareSubscriptions[self::SUBSCRIPTION_ID] = new Subscription([ + 'id' => self::SUBSCRIPTION_ID, + 'status' => $status, + 'canceledDate' => '2026-10-07', + 'chargedThroughDate' => '2026-10-07', + ]); + + $this->deliver($this->subscriptionUpdatedEvent()); + + $recur = $this->processor->recurs[self::RECUR_ID]; + $this->assertSame(3, $recur['contribution_status_id'], 'The series is Cancelled.'); + $this->assertSame('2026-10-07 00:00:00', $recur['cancel_date']); + } + + public static function statusesUntilCanceledDateProvider(): array { + return [ + 'ACTIVE' => ['ACTIVE'], + 'PENDING' => ['PENDING'], + 'PAUSED' => ['PAUSED'], + ]; + } + + public function testDeactivatedSubscriptionWithCanceledDateIsFailedNotCancelled(): void { + $this->payFirstInstallment(); + $this->squareSubscriptions[self::SUBSCRIPTION_ID] = new Subscription([ + 'id' => self::SUBSCRIPTION_ID, + 'status' => 'DEACTIVATED', + 'canceledDate' => '2026-10-07', + ]); + + $this->deliver($this->subscriptionUpdatedEvent()); + + $recur = $this->processor->recurs[self::RECUR_ID]; + $this->assertSame(4, $recur['contribution_status_id'], 'Square stopped billing a failing card: the series is Failed.'); + $this->assertEmpty($recur['cancel_date'] ?? NULL); + } + + public function testActiveSubscriptionWithoutCanceledDateIsNotCancelled(): void { + $this->payFirstInstallment(); + $statusBefore = $this->processor->recurs[self::RECUR_ID]['contribution_status_id']; + $this->squareSubscriptions[self::SUBSCRIPTION_ID] = new Subscription([ + 'id' => self::SUBSCRIPTION_ID, + 'status' => 'ACTIVE', + ]); + + $this->deliver($this->subscriptionUpdatedEvent()); + + $recur = $this->processor->recurs[self::RECUR_ID]; + $this->assertSame($statusBefore, $recur['contribution_status_id']); + $this->assertNotSame(3, $recur['contribution_status_id']); + $this->assertEmpty($recur['cancel_date'] ?? NULL); + } + + public function testCancellationArrivesAsSubscriptionUpdated(): void { + $this->payFirstInstallment(); + $this->squareSubscriptions[self::SUBSCRIPTION_ID] = new Subscription([ + 'id' => self::SUBSCRIPTION_ID, + 'status' => 'CANCELED', + 'canceledDate' => '2026-10-15', + ]); + + $this->deliver($this->subscriptionUpdatedEvent()); + + $recur = $this->processor->recurs[self::RECUR_ID]; + $this->assertSame(3, $recur['contribution_status_id'], 'The series is Cancelled.'); + $this->assertSame('2026-10-15 00:00:00', $recur['cancel_date']); + } + + public function testActiveSubscriptionDoesNotReopenASeriesCancelledInCiviCrm(): void { + $this->payFirstInstallment(); + // Cancelled in CiviCRM; Square keeps it ACTIVE until its canceled_date. + $this->processor->recurs[self::RECUR_ID]['contribution_status_id'] = 3; + $this->squareSubscriptions[self::SUBSCRIPTION_ID] = new Subscription([ + 'id' => self::SUBSCRIPTION_ID, + 'status' => 'ACTIVE', + 'canceledDate' => '2026-10-15', + ]); + + $this->deliver($this->subscriptionUpdatedEvent()); + + $this->assertSame(3, $this->processor->recurs[self::RECUR_ID]['contribution_status_id']); + } + + public function testRemovedEventTypesAreNotSubscribed(): void { + $supported = CRM_Core_Payment_SquareIPN::getSupportedEventTypes(); + + // Neither exists in Square's event catalog. + $this->assertNotContains('subscription.canceled', $supported); + $this->assertNotContains('invoice.payment_failed', $supported); + $this->assertContains('invoice.scheduled_charge_failed', $supported); + } + + /** + * A subscription.updated payload for the test series. + * + * @return array + */ + private function subscriptionUpdatedEvent(): array { + return [ + 'type' => 'subscription.updated', + 'event_id' => 'EVENT-SUBSCRIPTION-UPDATED', + 'data' => [ + 'type' => 'subscription', + 'id' => self::SUBSCRIPTION_ID, + 'object' => ['subscription' => ['id' => self::SUBSCRIPTION_ID]], + ], + ]; + } + +} diff --git a/tests/phpunit/CRM/Core/Payment/Square/SubscriptionsTest.php b/tests/phpunit/CRM/Core/Payment/Square/SubscriptionsTest.php index 949e7546..612a5259 100644 --- a/tests/phpunit/CRM/Core/Payment/Square/SubscriptionsTest.php +++ b/tests/phpunit/CRM/Core/Payment/Square/SubscriptionsTest.php @@ -114,6 +114,31 @@ public function testUnsupportedCadenceIsRefused(): void { $this->subscriptions()->getPlanVariationIdForParams($this->params(['frequency_interval' => 5])); } + /** + * @dataProvider cadenceProvider + */ + public function testEverySquareCadenceIsAvailable(string $unit, int $interval, string $cadence): void { + $this->assertSame($cadence, $this->callMethod($this->subscriptions(), 'resolveCadence', [$unit, $interval])); + } + + public static function cadenceProvider(): array { + return [ + ['day', 1, 'DAILY'], + ['week', 1, 'WEEKLY'], + ['week', 2, 'EVERY_TWO_WEEKS'], + ['day', 30, 'THIRTY_DAYS'], + ['day', 60, 'SIXTY_DAYS'], + ['day', 90, 'NINETY_DAYS'], + ['month', 1, 'MONTHLY'], + ['month', 2, 'EVERY_TWO_MONTHS'], + ['month', 3, 'QUARTERLY'], + ['month', 4, 'EVERY_FOUR_MONTHS'], + ['month', 6, 'EVERY_SIX_MONTHS'], + ['year', 1, 'ANNUAL'], + ['year', 2, 'EVERY_TWO_YEARS'], + ]; + } + /** * Changing the amount sends Square the subscription's current version. */ diff --git a/tests/phpunit/CRM/Core/Payment/SquareTest.php b/tests/phpunit/CRM/Core/Payment/SquareTest.php index 5152c968..65385a2f 100644 --- a/tests/phpunit/CRM/Core/Payment/SquareTest.php +++ b/tests/phpunit/CRM/Core/Payment/SquareTest.php @@ -1,5 +1,6 @@ assertNotSame($same, $sandbox->key('payment', 'invoice-123')); } - public function testRefundReturnsCiviRefundStatus(): void { + /** + * @dataProvider completedRefundStatusesProvider + */ + public function testRefundReturnsCiviRefundStatus(array $squareStatuses): void { + $processor = $this->refundingProcessor(...$squareStatuses); + $params = ['trxn_id' => 'payment-1', 'amount' => '12.34', 'currency' => 'USD']; + + $result = $processor->doRefund($params); + + // mjwshared's refund form records the refund only for 'Completed'. + $this->assertSame('Completed', $result['refund_status']); + $this->assertSame('refund-1', $result['refund_trxn_id']); + $this->assertSame(0, $result['fee_amount']); + $this->assertSame('2026-09-30 12:00:00', date('Y-m-d H:i:s', strtotime($result['trxn_date']))); + } + + public static function completedRefundStatusesProvider(): array { + return [ + 'completed' => [['COMPLETED']], + 'pending, as Square first reports a card refund, then completed' => [['PENDING', 'PENDING', 'COMPLETED']], + ]; + } + + public function testRefundStillPendingIsNotRecorded(): void { + $processor = $this->refundingProcessor('PENDING'); + $params = ['trxn_id' => 'payment-1', 'amount' => '12.34']; + + try { + $processor->doRefund($params); + $this->fail('A refund Square has not completed must not be reported Completed.'); + } + catch (PaymentProcessorException $e) { + $this->assertStringContainsString('refund-1 but has not completed it yet', $e->getMessage()); + } + // It was checked on, a few times, before giving up. + $this->assertSame(5, $processor->pauses); + } + + public function testRefundThatFailsWhilePendingIsAPaymentFailure(): void { + $processor = $this->refundingProcessor('PENDING', 'FAILED'); + $params = ['trxn_id' => 'payment-1', 'amount' => '12.34']; + + $this->expectException(PaymentProcessorException::class); + $this->expectExceptionMessage('Status: FAILED'); + $processor->doRefund($params); + } + + public function testRefundWhoseStatusCannotBeCheckedIsReportedPending(): void { + $processor = $this->refundingProcessor('PENDING'); + $processor->refundCheckFails = TRUE; + $params = ['trxn_id' => 'payment-1', 'amount' => '12.34']; + + $this->expectException(PaymentProcessorException::class); + $this->expectExceptionMessage('has not completed it yet'); + $processor->doRefund($params); + } + + /** + * @dataProvider refusedRefundStatusProvider + */ + public function testRefundSquareDidNotAcceptIsAPaymentFailure(string $squareStatus): void { + $processor = $this->refundingProcessor($squareStatus); + $params = ['trxn_id' => 'payment-1', 'amount' => '12.34']; + + $this->expectException(PaymentProcessorException::class); + $this->expectExceptionMessage("Status: {$squareStatus}"); + $processor->doRefund($params); + } + + public static function refusedRefundStatusProvider(): array { + return [['REJECTED'], ['FAILED']]; + } + + public function testBuildFormNeverPublishesTheAccessToken(): void { + $processor = $this->processor(['signature' => NULL]); + $form = new class() { + + /** + * @var array + */ + public array $assigned = []; + + public function elementExists($name) { + return TRUE; + } + + public function assign($name, $value) { + $this->assigned[$name] = $value; + } + + }; + + $processor->buildForm($form); + + $this->assertStringNotContainsString('access-token', $form->assigned['squareJSVarsJson']); + $this->assertSame('', json_decode($form->assigned['squareJSVarsJson'], TRUE)['locationId']); + } + + /** + * A processor whose Square refund comes back with the given statuses. + * + * @param string ...$squareStatuses + * As the refund is created, then as each later check finds it (the last + * one repeating). + */ + private function refundingProcessor(string ...$squareStatuses): CRM_Core_Payment_Square { $config = $this->processorConfig(); - $processor = new class('live', $config) extends CRM_Core_Payment_Square { + return new class('live', $config, $squareStatuses) extends CRM_Core_Payment_Square { + + /** + * @var string[] + */ + private array $squareStatuses; + + /** + * Number of pauses between checks on the refund. + * + * @var int + */ + public int $pauses = 0; + + /** + * Whether checking on the refund fails. + * + * @var bool + */ + public bool $refundCheckFails = FALSE; + + public function __construct($mode, array &$paymentProcessor, array $squareStatuses) { + parent::__construct($mode, $paymentProcessor); + $this->squareStatuses = $squareStatuses; + } + + protected function getRefundContext(string $paymentTrxnId): array { + return ['USD', 0]; + } protected function createRefund(RefundPaymentRequest $request) { - return new RefundPaymentResponse([ - 'refund' => new PaymentRefund([ - 'id' => 'refund-1', - 'locationId' => 'location-1', - 'status' => 'COMPLETED', - 'amountMoney' => new Money(['amount' => 1234, 'currency' => 'USD']), - ]), - ]); + return new RefundPaymentResponse(['refund' => $this->refund()]); } - }; - $params = ['trxn_id' => 'payment-1', 'amount' => '12.34', 'currency' => 'USD']; + protected function getRefund(string $refundId): ?PaymentRefund { + if ($this->refundCheckFails) { + throw new CRM_Core_Payment_SquareRetryableException('Square API request failed: timed out'); + } + if (count($this->squareStatuses) > 1) { + array_shift($this->squareStatuses); + } + return $this->refund(); + } - $result = $processor->doRefund($params); + protected function pause(int $microseconds): void { + $this->pauses++; + } - $this->assertSame('COMPLETED', $result['refund_status']); - $this->assertSame('refund-1', $result['refund_trxn_id']); + private function refund(): PaymentRefund { + return new PaymentRefund([ + 'id' => 'refund-1', + 'locationId' => 'location-1', + 'status' => $this->squareStatuses[0], + 'amountMoney' => new Money(['amount' => 1234, 'currency' => 'USD']), + 'createdAt' => '2026-09-30T12:00:00Z', + ]); + } + + }; } private function processorConfig(array $overrides = []): array { diff --git a/tests/phpunit/CRM/Square/CurrencyTest.php b/tests/phpunit/CRM/Square/CurrencyTest.php new file mode 100644 index 00000000..8623ccc2 --- /dev/null +++ b/tests/phpunit/CRM/Square/CurrencyTest.php @@ -0,0 +1,37 @@ +assertSame($minorUnits, CRM_Square_Currency::toMinorUnits($amount, $currency)); + $this->assertSame((float) $amount, CRM_Square_Currency::fromMinorUnits($minorUnits, $currency)); + } + + public static function amountProvider(): array { + return [ + 'US dollars, in cents' => ['12.34', 'USD', 1234], + 'lower-case code' => ['12.34', 'usd', 1234], + 'yen, which has no minor unit' => ['100', 'JPY', 100], + 'Kuwaiti dinar, in fils' => ['1.234', 'KWD', 1234], + ]; + } + + public function testAnUnknownCurrencyHasTwoDecimalPlaces(): void { + $this->assertSame(2, CRM_Square_Currency::decimals(NULL)); + $this->assertSame(2, CRM_Square_Currency::decimals('XYZ')); + } + + public function testRoundsToTheSmallestUnit(): void { + // 0.1 + 0.2 is not exactly 0.3 in floating point. + $this->assertSame(30, CRM_Square_Currency::toMinorUnits(0.1 + 0.2, 'USD')); + } + +} diff --git a/tests/phpunit/CRM/Square/CustomersTest.php b/tests/phpunit/CRM/Square/CustomersTest.php new file mode 100644 index 00000000..849ff0dc --- /dev/null +++ b/tests/phpunit/CRM/Square/CustomersTest.php @@ -0,0 +1,139 @@ +customers([12 => 'CUST-MAPPED']); + + $this->assertSame('CUST-MAPPED', $customers->ensureSquareCustomer(['contactID' => 12])); + $this->assertSame([], $this->created); + } + + public function testCustomerReferencingTheContactIsAdopted(): void { + $this->squareCustomers[] = ['CUST-REF', '12', 'pat@example.org']; + $customers = $this->customers([]); + + $this->assertSame('CUST-REF', $customers->ensureSquareCustomer(['contactID' => 12])); + $this->assertSame([12 => 'CUST-REF'], $customers->map); + $this->assertSame([], $this->created); + } + + public function testUnmappedCustomerWithTheContactsEmailIsAdopted(): void { + $this->squareCustomers[] = ['CUST-POS', NULL, 'pat@example.org']; + $customers = $this->customers([]); + + $this->assertSame('CUST-POS', $customers->ensureSquareCustomer(['contactID' => 12])); + $this->assertSame([], $this->created); + } + + /** + * A parent's email on two children's records must not block the second. + */ + public function testSharedEmailGetsANewCustomerInsteadOfFailing(): void { + $this->squareCustomers[] = ['CUST-SIBLING', '34', 'pat@example.org']; + $customers = $this->customers([34 => 'CUST-SIBLING']); + + $customerId = $customers->ensureSquareCustomer(['contactID' => 12]); + + $this->assertSame('CUST-NEW-1', $customerId); + $this->assertCount(1, $this->created); + $this->assertSame('12', $this->created[0]->getReferenceId()); + $this->assertSame('pat@example.org', $this->created[0]->getEmailAddress()); + $this->assertSame([34 => 'CUST-SIBLING', 12 => 'CUST-NEW-1'], $customers->map); + } + + /** + * Customers whose mapping lives in an array, and whose Square is mocked. + * + * @param array $map + * Square customer ID by contact ID. + * + * @return \CRM_Square_Customers + */ + private function customers(array $map): CRM_Square_Customers { + $client = new SquareClient(token: 'test-token', options: ['baseUrl' => 'https://example.invalid']); + $mock = $this->createMock(CustomersClient::class); + $mock->method('search')->willReturnCallback(function (SearchCustomersRequest $request) { + $filter = $request->getQuery()->getFilter(); + $matches = []; + foreach ($this->squareCustomers as [$id, $referenceId, $email]) { + if (($filter->getReferenceId() && $filter->getReferenceId()->getExact() === $referenceId) + || ($filter->getEmailAddress() && $filter->getEmailAddress()->getExact() === $email)) { + $matches[] = new Customer(['id' => $id]); + } + } + return new SearchCustomersResponse(['customers' => $matches]); + }); + $mock->method('create')->willReturnCallback(function (CreateCustomerRequest $request) { + $this->created[] = $request; + return new CreateCustomerResponse(['customer' => new Customer(['id' => 'CUST-NEW-' . count($this->created)])]); + }); + $client->customers = $mock; + $gateway = new CRM_Square_Gateway($this->processorConfig(), fn () => $client); + + return new class($gateway, $map) extends CRM_Square_Customers { + + /** + * Square customer ID by contact ID. + * + * @var array + */ + public array $map; + + public function __construct(CRM_Square_Gateway $gateway, array $map) { + parent::__construct($gateway); + $this->map = $map; + } + + public function getSquareCustomerId($contactId) { + return $this->map[(int) $contactId] ?? NULL; + } + + protected function getMappedContactId(string $customerId): ?int { + $contactId = array_search($customerId, $this->map, TRUE); + return $contactId === FALSE ? NULL : (int) $contactId; + } + + protected function saveSquareCustomerId($contactId, $customerId): ?string { + // As square_customer_map's two unique keys do. + if (!isset($this->map[(int) $contactId]) && $this->getMappedContactId($customerId) === NULL) { + $this->map[(int) $contactId] = $customerId; + } + return $this->getSquareCustomerId($contactId); + } + + protected function getContactDetails(int $contactID): ?array { + return ['first_name' => 'Pat', 'last_name' => 'Doe', 'email' => 'pat@example.org']; + } + + }; + } + +} diff --git a/tests/phpunit/CRM/Square/MergeHookTest.php b/tests/phpunit/CRM/Square/MergeHookTest.php new file mode 100644 index 00000000..74d575c9 --- /dev/null +++ b/tests/phpunit/CRM/Square/MergeHookTest.php @@ -0,0 +1,34 @@ +assertSame([ + 'SELECT 1', + // Where the kept contact already has a customer on the processor, the + // unique contact/processor key makes UPDATE IGNORE skip the row... + 'UPDATE IGNORE square_customer_map SET contact_id = 5 WHERE contact_id = 9', + // ...which is then dropped. + 'DELETE FROM square_customer_map WHERE contact_id = 9', + ], $sqls); + } + + public function testOtherMergeOperationsAreLeftAlone(): void { + $cidRefs = ['civicrm_email' => ['contact_id']]; + + square_civicrm_merge('cidRefs', $cidRefs); + + // A plain UPDATE from cidRefs would fail on the unique key. + $this->assertSame(['civicrm_email' => ['contact_id']], $cidRefs); + } + +} diff --git a/tests/phpunit/CRM/Square/UpgraderTest.php b/tests/phpunit/CRM/Square/UpgraderTest.php index fee0c761..83c08cc2 100644 --- a/tests/phpunit/CRM/Square/UpgraderTest.php +++ b/tests/phpunit/CRM/Square/UpgraderTest.php @@ -3,7 +3,10 @@ use PHPUnit\Framework\TestCase; /** - * Upgrade step 1001: one contact per Square customer, per payment processor. + * Upgrade steps 1001 and 1002. + * + * One contact per Square customer, per payment processor; and deleting a + * processor deletes its mappings. */ class CRM_Square_UpgraderTest extends TestCase { @@ -47,6 +50,14 @@ public function testUpgradeIsANoOpWhenTheKeyExists(): void { $this->assertFalse($upgrader->keyAdded); } + public function testProcessorDeletesCascadeToMappings(): void { + $upgrader = $this->upgrader(TRUE, []); + + $this->assertTrue($upgrader->upgrade_1002()); + + $this->assertTrue($upgrader->cascadeAdded); + } + /** * An upgrader whose square_customer_map is described by its arguments. * @@ -68,6 +79,11 @@ private function upgrader(bool $hasKey, array $conflicts): CRM_Square_Upgrader { */ public bool $conflictsChecked = FALSE; + /** + * @var bool + */ + public bool $cascadeAdded = FALSE; + /** * @var bool */ @@ -109,6 +125,13 @@ protected function addUniqueCustomerKey(): void { $this->keyAdded = TRUE; } + /** + * Record instead of altering the table. + */ + protected function cascadeProcessorDeletes(): void { + $this->cascadeAdded = TRUE; + } + }; } diff --git a/tests/phpunit/bootstrap.php b/tests/phpunit/bootstrap.php index eacd5f04..a925f0fc 100644 --- a/tests/phpunit/bootstrap.php +++ b/tests/phpunit/bootstrap.php @@ -79,18 +79,12 @@ public function __construct($message = '', $error_code = 0, $errorData = [], $pr abstract class CRM_Extension_Upgrader_Base { } } -if (!function_exists('_square_assert_php_version')) { - - /** - * Stand-in for square.php's PHP version check, which the upgrader calls. - */ - function _square_assert_php_version(): void { - } - -} if (!class_exists('Civi\\Payment\\Exception\\PaymentProcessorException')) { require_once __DIR__ . '/stubs/PaymentProcessorException.php'; } +// The extension's hook implementations (and, through square.civix.php, +// CRM_Square_ExtensionUtil), as CiviCRM loads them. +require_once $extensionRoot . '/square.php'; if (!class_exists('CRM_Square_ExtensionUtil')) { /** @@ -137,50 +131,25 @@ public static function ts($text, array $params = []): string { * @return string */ function ts($message, array $params = []) { + // Options such as 'domain' are not placeholders. + unset($params['domain'], $params['escape'], $params['plural'], $params['count']); foreach ($params as $key => $value) { - $message = str_replace("%{$key}", $value, $message); + $message = str_replace("%{$key}", (string) $value, $message); } return $message; } } -if (!class_exists('CRM_Contribute_PseudoConstant')) { - - /** - * Minimal stand-in for CiviCRM core's contribution-status lookup. - * - * Used by CRM_Core_Payment_Square::contributionStatusId(). Values match - * CiviCRM's own default 'contribution_status' option group so tests - * exercise the same IDs the production code assumes elsewhere. - */ - class CRM_Contribute_PseudoConstant { - - /** - * @return array - */ - public static function contributionStatus(): array { - return [ - 1 => 'Completed', - 2 => 'Pending', - 3 => 'Cancelled', - 4 => 'Failed', - 5 => 'In Progress', - 6 => 'Overdue', - 7 => 'Refunded', - ]; - } - - } -} if (!class_exists('CRM_Core_PseudoConstant')) { /** * Minimal stand-in for CiviCRM core's pseudoconstant lookup. * - * Used by CRM_Core_Payment_Square::pseudoConstantId() for - * contribution_status_id, payment_instrument_id, and financial_type_id. - * Values match CiviCRM's own default option groups, seeded on every - * fresh install. + * Used by CRM_Square_Status::pseudoConstantId() for contribution and + * recurring contribution statuses, payment instruments, and financial + * types. Values match the option groups CiviCRM 6.16 seeds on a fresh + * install — including that contribution_status has no In Progress (5) or + * Overdue (6), which only contribution_recur_status has. */ class CRM_Core_PseudoConstant { @@ -193,30 +162,175 @@ class CRM_Core_PseudoConstant { */ public static function getKey($baoName, $fieldName, $value) { $options = [ - 'contribution_status_id' => [ - 1 => 'Completed', - 2 => 'Pending', - 3 => 'Cancelled', - 4 => 'Failed', - 5 => 'In Progress', - 6 => 'Overdue', - 7 => 'Refunded', + 'CRM_Contribute_BAO_Contribution' => [ + 'contribution_status_id' => [ + 1 => 'Completed', + 2 => 'Pending', + 3 => 'Cancelled', + 4 => 'Failed', + 7 => 'Refunded', + 8 => 'Partially paid', + 9 => 'Pending refund', + 10 => 'Chargeback', + 11 => 'Template', + ], + 'payment_instrument_id' => [ + 1 => 'Credit Card', + 2 => 'Debit Card', + 3 => 'Cash', + 4 => 'Check', + 5 => 'EFT', + ], + 'financial_type_id' => [ + 1 => 'Donation', + 2 => 'Member Dues', + 3 => 'Campaign Contribution', + 4 => 'Event Fee', + ], ], - 'payment_instrument_id' => [ - 1 => 'Credit Card', - 2 => 'Debit Card', - 3 => 'Cash', - 4 => 'Check', - 5 => 'EFT', - ], - 'financial_type_id' => [ - 1 => 'Donation', - 2 => 'Member Dues', - 3 => 'Campaign Contribution', - 4 => 'Event Fee', + 'CRM_Contribute_BAO_ContributionRecur' => [ + 'contribution_status_id' => [ + 1 => 'Completed', + 2 => 'Pending', + 3 => 'Cancelled', + 4 => 'Failed', + 5 => 'In Progress', + 6 => 'Overdue', + 7 => 'Processing', + 8 => 'Failing', + ], ], ]; - return array_search($value, $options[$fieldName] ?? [], TRUE); + return array_search($value, $options[$baoName][$fieldName] ?? [], TRUE); + } + + /** + * @param int|false $id + * + * @return array|string|null + */ + public static function countryIsoCode($id = FALSE) { + $codes = [1228 => 'US', 1039 => 'CA']; + return $id ? ($codes[$id] ?? NULL) : $codes; + } + + /** + * @param int|false $id + * + * @return array|string|null + */ + public static function stateProvinceAbbreviation($id = FALSE) { + $abbreviations = [1042 => 'TN']; + return $id ? ($abbreviations[$id] ?? NULL) : $abbreviations; + } + + } +} +if (!class_exists('CRM_Core_Region')) { + + /** + * Minimal stand-in for CiviCRM core's page regions. + * + * Snippets added are kept in CRM_Core_Region::$added, by region name. + */ + class CRM_Core_Region { + + /** + * Snippets added to each region. + * + * @var array + */ + public static array $added = []; + + /** + * @var string + */ + private string $name; + + /** + * @param string $name + */ + private function __construct(string $name) { + $this->name = $name; + } + + /** + * @param string $name + * + * @return self + */ + public static function instance($name): self { + return new self($name); + } + + /** + * @param array $snippet + */ + public function add(array $snippet): void { + self::$added[$this->name][] = $snippet; + } + + } +} +if (!class_exists('CRM_Core_Resources')) { + + /** + * Minimal stand-in for CiviCRM core's resource manager. + * + * Settings added are kept in CRM_Core_Resources::$settings. + */ + class CRM_Core_Resources { + + /** + * Settings added, merged. + * + * @var array + */ + public static array $settings = []; + + /** + * @return self + */ + public static function singleton(): self { + return new self(); + } + + /** + * @param string $key + * @param string|null $file + * + * @return string + */ + public function getUrl($key, $file = NULL): string { + return "https://example.invalid/ext/{$key}/" . ($file ?? ''); + } + + /** + * @param array $settings + */ + public function addSetting(array $settings): self { + self::$settings = array_replace_recursive(self::$settings, $settings); + return $this; + } + + } +} +if (!class_exists('CRM_Utils_Rule')) { + + /** + * Minimal stand-in for CiviCRM core's validation and cleaning rules. + */ + class CRM_Utils_Rule { + + /** + * As core's, for the default separators: drop spaces and thousands commas. + * + * @param string|null $value + * + * @return string + */ + public static function cleanMoney($value): string { + return str_replace([' ', "\t", "\n", ','], '', (string) ($value ?? '')); } } @@ -226,7 +340,7 @@ public static function getKey($baoName, $fieldName, $value) { /** * Minimal stand-in for CiviCRM's Civi service locator. * - * Only settings() and log() are provided. Log calls are recorded in + * Settings, logging and an injectable lock manager are provided. Logs go to * Civi::$logged so tests can assert reconciliation errors were raised. */ class Civi { @@ -245,6 +359,23 @@ class Civi { */ public static array $settings = []; + /** + * Lock manager supplied by tests exercising contribution locks. + * + * @var object|null + */ + public static ?object $lockManager = NULL; + + /** + * @return object + */ + public static function lockManager() { + if (self::$lockManager === NULL) { + throw new LogicException('No test lock manager configured.'); + } + return self::$lockManager; + } + /** * @return object */ diff --git a/vendor/composer/autoload_psr4.php b/vendor/composer/autoload_psr4.php index 044a4a17..aedcc6d7 100644 --- a/vendor/composer/autoload_psr4.php +++ b/vendor/composer/autoload_psr4.php @@ -31,6 +31,4 @@ 'DeepCopy\\' => array($vendorDir . '/myclabs/deep-copy/src/DeepCopy'), 'Core\\' => array($vendorDir . '/apimatic/core/src'), 'CoreInterfaces\\' => array($vendorDir . '/apimatic/core-interfaces/src'), - 'CRM\\Tests\\' => array($baseDir . '/tests'), - 'CRM\\' => array($baseDir . '/CRM'), ); diff --git a/vendor/composer/autoload_static.php b/vendor/composer/autoload_static.php index 4d80ee8f..190066de 100644 --- a/vendor/composer/autoload_static.php +++ b/vendor/composer/autoload_static.php @@ -18,19 +18,19 @@ class ComposerStaticInit48c2b53831468ad8cc35159079e7e76d ); public static $prefixLengthsPsr4 = array ( - 'a' => + 'a' => array ( 'apimatic\\jsonmapper\\' => 20, ), - 'V' => + 'V' => array ( 'VariableAnalysis\\' => 17, ), - 'U' => + 'U' => array ( 'Unirest\\' => 8, ), - 'S' => + 'S' => array ( 'Symfony\\Polyfill\\Php80\\' => 23, 'Symfony\\Polyfill\\Mbstring\\' => 26, @@ -40,7 +40,7 @@ class ComposerStaticInit48c2b53831468ad8cc35159079e7e76d 'Square\\' => 7, 'SlevomatCodingStandard\\' => 23, ), - 'P' => + 'P' => array ( 'Psr\\Log\\' => 8, 'Psr\\Http\\Message\\' => 17, @@ -49,144 +49,134 @@ class ComposerStaticInit48c2b53831468ad8cc35159079e7e76d 'PHPStan\\PhpDocParser\\' => 21, 'PHPCSStandards\\Composer\\Plugin\\Installers\\PHPCodeSniffer\\' => 57, ), - 'G' => + 'G' => array ( 'GuzzleHttp\\Psr7\\' => 16, 'GuzzleHttp\\Promise\\' => 19, 'GuzzleHttp\\' => 11, ), - 'D' => + 'D' => array ( 'Drupal\\' => 7, 'DrupalPractice\\' => 15, 'Doctrine\\Instantiator\\' => 22, 'DeepCopy\\' => 9, ), - 'C' => + 'C' => array ( 'Core\\' => 5, 'CoreInterfaces\\' => 15, - 'CRM\\Tests\\' => 10, - 'CRM\\' => 4, ), ); public static $prefixDirsPsr4 = array ( - 'apimatic\\jsonmapper\\' => + 'apimatic\\jsonmapper\\' => array ( 0 => __DIR__ . '/..' . '/apimatic/jsonmapper/src', ), - 'VariableAnalysis\\' => + 'VariableAnalysis\\' => array ( 0 => __DIR__ . '/..' . '/sirbrillig/phpcs-variable-analysis/VariableAnalysis', ), - 'Unirest\\' => + 'Unirest\\' => array ( 0 => __DIR__ . '/..' . '/apimatic/unirest-php/src', ), - 'Symfony\\Polyfill\\Php80\\' => + 'Symfony\\Polyfill\\Php80\\' => array ( 0 => __DIR__ . '/..' . '/symfony/polyfill-php80', ), - 'Symfony\\Polyfill\\Mbstring\\' => + 'Symfony\\Polyfill\\Mbstring\\' => array ( 0 => __DIR__ . '/..' . '/symfony/polyfill-mbstring', ), - 'Symfony\\Polyfill\\Ctype\\' => + 'Symfony\\Polyfill\\Ctype\\' => array ( 0 => __DIR__ . '/..' . '/symfony/polyfill-ctype', ), - 'Symfony\\Component\\Yaml\\' => + 'Symfony\\Component\\Yaml\\' => array ( 0 => __DIR__ . '/..' . '/symfony/yaml', ), - 'Symfony\\Component\\HttpFoundation\\' => + 'Symfony\\Component\\HttpFoundation\\' => array ( 0 => __DIR__ . '/..' . '/symfony/http-foundation', ), - 'Square\\' => + 'Square\\' => array ( 0 => __DIR__ . '/..' . '/square/square/src', ), - 'SlevomatCodingStandard\\' => + 'SlevomatCodingStandard\\' => array ( 0 => __DIR__ . '/..' . '/slevomat/coding-standard/SlevomatCodingStandard', ), - 'Psr\\Log\\' => + 'Psr\\Log\\' => array ( 0 => __DIR__ . '/..' . '/psr/log/src', ), - 'Psr\\Http\\Message\\' => + 'Psr\\Http\\Message\\' => array ( 0 => __DIR__ . '/..' . '/psr/http-factory/src', 1 => __DIR__ . '/..' . '/psr/http-message/src', ), - 'Psr\\Http\\Client\\' => + 'Psr\\Http\\Client\\' => array ( 0 => __DIR__ . '/..' . '/psr/http-client/src', ), - 'PhpParser\\' => + 'PhpParser\\' => array ( 0 => __DIR__ . '/..' . '/nikic/php-parser/lib/PhpParser', ), - 'PHPStan\\PhpDocParser\\' => + 'PHPStan\\PhpDocParser\\' => array ( 0 => __DIR__ . '/..' . '/phpstan/phpdoc-parser/src', ), - 'PHPCSStandards\\Composer\\Plugin\\Installers\\PHPCodeSniffer\\' => + 'PHPCSStandards\\Composer\\Plugin\\Installers\\PHPCodeSniffer\\' => array ( 0 => __DIR__ . '/..' . '/dealerdirect/phpcodesniffer-composer-installer/src', ), - 'GuzzleHttp\\Psr7\\' => + 'GuzzleHttp\\Psr7\\' => array ( 0 => __DIR__ . '/..' . '/guzzlehttp/psr7/src', ), - 'GuzzleHttp\\Promise\\' => + 'GuzzleHttp\\Promise\\' => array ( 0 => __DIR__ . '/..' . '/guzzlehttp/promises/src', ), - 'GuzzleHttp\\' => + 'GuzzleHttp\\' => array ( 0 => __DIR__ . '/..' . '/guzzlehttp/guzzle/src', ), - 'Drupal\\' => + 'Drupal\\' => array ( 0 => __DIR__ . '/..' . '/drupal/coder/coder_sniffer/Drupal', ), - 'DrupalPractice\\' => + 'DrupalPractice\\' => array ( 0 => __DIR__ . '/..' . '/drupal/coder/coder_sniffer/DrupalPractice', ), - 'Doctrine\\Instantiator\\' => + 'Doctrine\\Instantiator\\' => array ( 0 => __DIR__ . '/..' . '/doctrine/instantiator/src/Doctrine/Instantiator', ), - 'DeepCopy\\' => + 'DeepCopy\\' => array ( 0 => __DIR__ . '/..' . '/myclabs/deep-copy/src/DeepCopy', ), - 'Core\\' => + 'Core\\' => array ( 0 => __DIR__ . '/..' . '/apimatic/core/src', ), - 'CoreInterfaces\\' => + 'CoreInterfaces\\' => array ( 0 => __DIR__ . '/..' . '/apimatic/core-interfaces/src', ), - 'CRM\\Tests\\' => - array ( - 0 => __DIR__ . '/../..' . '/tests', - ), - 'CRM\\' => - array ( - 0 => __DIR__ . '/../..' . '/CRM', - ), ); public static $prefixesPsr0 = array ( - 'R' => + 'R' => array ( - 'Rs\\Json' => + 'Rs\\Json' => array ( 0 => __DIR__ . '/..' . '/php-jsonpointer/php-jsonpointer/src', ),