diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 00000000..c57f86b8 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,53 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +jobs: + tests: + name: Tests (PHP ${{ matrix.php }}) + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + php: ['8.2', '8.3', '8.4'] + steps: + - uses: actions/checkout@v4 + - uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + coverage: none + - name: Validate composer.json and composer.lock + run: composer validate --strict + - name: Lint + run: find CRM settings managed tests square.php -name '*.php' -print0 | xargs -0 -n1 php -l + # PHPUnit is in the committed vendor/. Deprecations, notices and + # warnings fail the run (see tests/phpunit/phpunit.xml.dist). + - name: Unit tests + run: vendor/bin/phpunit --configuration tests/phpunit/phpunit.xml.dist + + standards: + name: Coding standard and static analysis + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: shivammathur/setup-php@v2 + with: + php-version: '8.2' + coverage: none + tools: phpstan:1.12.32 + - name: Coding standard + run: vendor/bin/phpcs --standard=phpcs.xml.dist CRM square.php settings managed tests + # CiviCRM core's classes are needed for analysis only; the release + # tarball includes the vendor/ packages its classes extend. + - name: Fetch CiviCRM 6.16.5 + run: curl -sSfL https://download.civicrm.org/civicrm-6.16.5-drupal.tar.gz | tar -xz -C "$RUNNER_TEMP" + - name: Static analysis + env: + CIVICRM_CORE: ${{ runner.temp }}/civicrm + run: phpstan analyse -c phpstan.neon.dist --no-progress --memory-limit=2G diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..adad761c --- /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 ef3db163..035bfd2e 100644 --- a/CRM/Core/Payment/Square.php +++ b/CRM/Core/Payment/Square.php @@ -1,43 +1,19 @@ [ - 'label' => 'Daily', - 'unit' => 'day', - 'step' => 1, - ], - 'WEEKLY' => [ - 'label' => 'Weekly', - 'unit' => 'week', - 'step' => 1, - ], - 'EVERY_TWO_WEEKS' => [ - 'label' => 'Every 2 Weeks', - 'unit' => 'week', - 'step' => 2, - ], - 'MONTHLY' => [ - 'label' => 'Monthly', - 'unit' => 'month', - 'step' => 1, - ], - 'EVERY_TWO_MONTHS' => [ - 'label' => 'Every 2 Months', - 'unit' => 'month', - 'step' => 2, - ], - 'QUARTERLY' => [ - 'label' => 'Quarterly', - 'unit' => 'month', - 'step' => 3, - ], - 'EVERY_SIX_MONTHS' => [ - 'label' => 'Every 6 Months', - 'unit' => 'month', - 'step' => 6, - ], - 'ANNUAL' => [ - 'label' => 'Annual', - 'unit' => 'year', - 'step' => 1, - ], - ]; - /** * Constructor. * @@ -167,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. @@ -203,6 +156,11 @@ public function buildForm(&$form) { // 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; } /** @@ -215,89 +173,92 @@ public function buildForm(&$form) { * @throws \CRM_Core_Exception */ protected function buildSquareClient(): SquareClient { - return new SquareClient( - token: $this->getAccessToken(), - options: ['baseUrl' => $this->getApiBaseUrl()], - ); + return $this->gateway()->createClient(); } /** - * Get the Square access token from processor config. + * Square API access for this processor. * - * @return string + * Its client comes from buildSquareClient(), so overriding that replaces + * the client every collaborator uses. * - * @throws \CRM_Core_Exception + * @return \CRM_Square_Gateway */ - protected function getAccessToken() { - - return trim($this->_paymentProcessor['password'] ?? ''); + protected function gateway(): CRM_Square_Gateway { + return new CRM_Square_Gateway($this->_paymentProcessor, fn () => $this->buildSquareClient()); } /** - * Get the Square Location ID from processor config. - * - * @return string + * Square customers and cards on file for this processor. * - * @throws \CRM_Core_Exception + * @return \CRM_Square_Customers */ - protected function getLocationId() { - $loc = trim($this->_paymentProcessor['signature'] ?? ''); - if (empty($loc)) { - throw new CRM_Core_Exception('Square location ID is not configured on this payment processor.'); - } - return $loc; + protected function customers(): CRM_Square_Customers { + return new CRM_Square_Customers($this->gateway()); } /** - * Base URL for Square API, depending on mode and config. + * Square subscription plans and subscriptions for this processor. * - * @return string + * @return \CRM_Square_Subscriptions */ - protected function getApiBaseUrl() { - // Allow overriding via processor config if provided. - if (!empty($this->_paymentProcessor['url_api'])) { - return rtrim($this->_paymentProcessor['url_api'], '/'); - } - - // Fallback: use sensible defaults based on test/live. - if ($this->isTestMode()) { - return 'https://connect.squareupsandbox.com'; - } + protected function subscriptions(): CRM_Square_Subscriptions { + return new CRM_Square_Subscriptions($this->gateway()); + } - return 'https://connect.squareup.com'; + /** + * Webhook-driven sync of Square activity into CiviCRM for this processor. + * + * @return \CRM_Square_Reconciler + */ + protected function reconciler(): CRM_Square_Reconciler { + return new CRM_Square_Reconciler($this->gateway()); } /** * Build a retry-stable idempotency key unique to each processor and environment. */ protected function idempotencyKey(string $operation, string $reference): string { - $processorId = (string) ($this->_paymentProcessor['id'] ?? '0'); - $environment = $this->isTestMode() ? 'test' : 'live'; - return substr('civi-' . $operation . '-' . hash('sha256', implode(':', [ - $processorId, - $environment, - $reference, - ])), 0, 45); + return $this->gateway()->idempotencyKey($operation, $reference); } /** - * Resolve a contribution status 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 (int) $id; + * Invoke the Square SDK client, translating its exceptions to CRM_Core_Exception. + * + * @param callable(\Square\SquareClient): mixed $call + * + * @return mixed + * Whatever $call returns (typically a Square SDK response object). + * + * @throws \CRM_Core_Exception + */ + protected function callSquare(callable $call) { + return $this->gateway()->call($call); + } + + /** + * Get the Square Location ID from processor config. + * + * @return string + * + * @throws \CRM_Core_Exception + */ + protected function getLocationId() { + return $this->gateway()->getLocationId(); + } + + /** + * ID of this payment processor (civicrm_payment_processor.id). + */ + protected function processorId(): int { + return $this->gateway()->processorId(); } /** - * 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 = []; @@ -315,725 +276,262 @@ public function checkConfig() { } /** - * Sync a Square payment (from webhook payload) into CiviCRM. + * Sync a Square payment (from a payment.updated webhook) into CiviCRM. * * @param array $payment * Payment object from Square webhooks. + * + * @see CRM_Square_Reconciler::syncPaymentFromSquare() */ public function syncPaymentFromSquare(array $payment) { - $paymentId = $payment['id'] ?? NULL; - CRM_Core_Payment_SquareDebugLogger::log("Square syncPaymentFromSquare(): called from SquareIPN for payment_id={$paymentId}, status=" . ($payment['status'] ?? 'UNKNOWN') . ', order_id=' . ($payment['order_id'] ?? 'null')); - if (!$paymentId) { - CRM_Core_Payment_SquareDebugLogger::log('Square syncPaymentFromSquare(): missing payment ID, skipping.'); - return; - } - - $status = $payment['status'] ?? 'UNKNOWN'; - $sourceType = $payment['source_type'] ?? NULL; - - // Determine amount/currency. - $money = $payment['amount_money'] ?? NULL; - $feeMoney = $payment['processing_fee'][0]['amount_money']['amount'] ?? NULL; - $amount = $money && isset($money['amount']) ? ($money['amount'] / 100) : NULL; - $feeAmount = $feeMoney !== NULL ? ($feeMoney / 100) : NULL; - $currency = $money['currency'] ?? 'USD'; - $orderID = $payment['order_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. - $existingQuery = Contribution::get(FALSE) - ->addSelect('id') - ->addWhere('is_test', 'IN', [TRUE, FALSE]); - if ($orderID !== NULL) { - $existingQuery->addClause('OR', ['invoice_number', '=', $orderID], ['trxn_id', '=', $paymentId]); - } - else { - $existingQuery->addWhere('trxn_id', '=', $paymentId); - } - $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}."); - 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; - $contactId = NULL; - - if ($referenceId && ctype_digit((string) $referenceId)) { - $refRecurContribution = ContributionRecur::get(FALSE) - ->addSelect('id', 'contact_id', 'is_test', 'financial_type_id') - ->addWhere('id', '=', (int) $referenceId) - ->addWhere('is_test', 'IN', [TRUE, FALSE]) - ->execute() - ->first(); - - if ($refRecurContribution) { - $contactId = (int) $refRecurContribution['contact_id']; - } - } - - if (!$contactId) { - $contactId = $this->findContactIdForPayment($payment); - } - - if (!$contactId) { - CRM_Core_Payment_SquareDebugLogger::log("Square syncPaymentFromSquare(): cannot resolve contact for payment {$paymentId}, skipping create."); - return; - } - - // Default financial type is Donation (ID=1) unless better mapping is added later. - $financialTypeId = 1; - - $applicationId = $payment['application_details']['application_id'] ?? ''; - $isTest = str_contains($applicationId, 'sandbox') ? 1 : 0; - if (!empty($refRecurContribution)) { - $isTest = $refRecurContribution['is_test'] ? 1 : 0; - $financialTypeId = $refRecurContribution['financial_type_id'] ?? $financialTypeId; - } - - $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('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}."); + $this->reconciler()->syncPaymentFromSquare($payment); } /** - * Sync a Square refund into CiviCRM. + * Sync a Square refund (refund.created / refund.updated) into CiviCRM. * * @param array $refund + * + * @see CRM_Square_Reconciler::syncRefundFromSquare() */ 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}."); - if (!$paymentId || !$refundId) { - CRM_Core_Payment_SquareDebugLogger::log('Square syncRefundFromSquare(): missing payment_id or refund_id, skipping.'); - return; - } - - // Find contribution by trxn_id. - $contribution = Contribution::get(FALSE) - ->addSelect('id') - ->addWhere('trxn_id', '=', $paymentId) - ->addWhere('is_test', 'IN', [TRUE, FALSE]) - ->execute() - ->first(); - - if (!$contribution) { - CRM_Core_Payment_SquareDebugLogger::log("Square syncRefundFromSquare(): no contribution found for payment {$paymentId}, skipping."); - return; - } - - CRM_Core_Payment_SquareDebugLogger::log("Square syncRefundFromSquare(): found contribution {$contribution['id']} for payment {$paymentId}, marking Refunded."); - - Contribution::update(FALSE) - ->addWhere('id', '=', $contribution['id']) - ->addValue('contribution_status_id', 'Refunded') - ->addValue('refund_trxn_id', $refundId) - ->execute(); - - CRM_Core_Payment_SquareDebugLogger::log("Square syncRefundFromSquare(): Updated contribution {$contribution['id']} as Refunded for refund {$refundId}."); + $this->reconciler()->syncRefundFromSquare($refund); } /** - * Sync a Square subscription update into CiviCRM. + * Sync a paid Square subscription invoice into CiviCRM. + * + * @param array $invoice * - * @param array $subscription + * @see CRM_Square_Reconciler::syncInvoiceFromSquare() */ - public function syncSubscriptionFromWebhook(array $subscription) { - $id = $subscription['id'] ?? NULL; - if (!$id) { - CRM_Core_Payment_SquareDebugLogger::log('Square syncSubscriptionFromWebhook(): missing subscription ID.'); - return; - } - - $status = $subscription['status'] ?? 'UNKNOWN'; - $amount = $this->extractSubscriptionAmount($subscription); - - $recur = ContributionRecur::get(FALSE) - ->addSelect('id', 'amount', 'contribution_status_id') - ->addWhere('processor_id', '=', $id) - ->addWhere('is_test', 'IN', [TRUE, FALSE]) - ->execute() - ->first(); - - if (!$recur) { - CRM_Core_Payment_SquareDebugLogger::log("Square syncSubscriptionFromWebhook(): no matching recur for {$id}"); - return; - } - - $updates = []; - $mappedStatus = $this->mapSquareSubscriptionStatusToCivi($status); + public function syncInvoiceFromSquare(array $invoice) { + $this->reconciler()->syncInvoiceFromSquare($invoice); + } - if ($mappedStatus !== NULL) { - $updates['contribution_status_id'] = $mappedStatus; - } - if ($amount !== NULL && (float) $amount !== (float) $recur['amount']) { - $updates['amount'] = (float) $amount; - } + /** + * Apply a Square subscription's current status and amount to its recurring contribution. + * + * @param string $squareSubscriptionId + * + * @see CRM_Square_Reconciler::syncSubscriptionFromSquare() + */ + public function syncSubscriptionFromSquare(string $squareSubscriptionId) { + $this->reconciler()->syncSubscriptionFromSquare($squareSubscriptionId); + } - if ($updates) { - $q = ContributionRecur::update(FALSE) - ->addWhere('id', '=', $recur['id']); - foreach ($updates as $field => $value) { - $q->addValue($field, $value); - } - $q->execute(); - } + /** + * Process Square invoice.payment_made webhook event. + * + * @param array $payload + * Full decoded JSON from Square webhook. + * + * @see CRM_Square_Reconciler::handleInvoicePaymentCreated() + */ + public function handleInvoicePaymentCreated(array $payload) { + $this->reconciler()->handleInvoicePaymentCreated($payload); } /** - * Sync a Square invoice (recurring payment) into CiviCRM. + * Sync a Square invoice.scheduled_charge_failed webhook event. * * @param array $invoice + * + * @see CRM_Square_Reconciler::syncInvoicePaymentFailedFromSquare() */ - 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(); + public function syncInvoicePaymentFailedFromSquare(array $invoice): void { + $this->reconciler()->syncInvoicePaymentFailedFromSquare($invoice); + } - if ($existing) { - return; - } + /** + * Ensure a Square customer exists for this contact, saving any submitted card. + * + * @param array $params + * Contribution params (includes contactID/contact_id). + * + * @return string + * Square customer ID. + * + * @see CRM_Square_Customers::ensureSquareCustomer() + */ + public function ensureSquareCustomer(array $params) { + return $this->customers()->ensureSquareCustomer($params); + } - $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(); + /** + * Attach a card to the Square customer using the tokenized card nonce. + * + * @param string $customerId + * @param string $cardNonce + * @param array $params + * @param int|null $contactId + * + * @return string + * Square card ID. + * + * @see CRM_Square_Customers::createCardOnFile() + */ + public function createCardOnFile($customerId, $cardNonce, array $params = [], $contactId = NULL) { + return $this->customers()->createCardOnFile($customerId, $cardNonce, $params, $contactId); } /** - * Sync a Square subscription with the corresponding CiviCRM recurring contribution. + * Legacy entry point for on-site CC payments. * - * This is used when Square sends a webhook (subscription.updated or subscription.canceled) - * AND also may be triggered manually by scheduled jobs. + * CiviCRM still calls doDirectPayment for front-end payments. * - * @param string $squareSubscriptionId - * The subscription ID from Square. + * @param array $params + * Contribution / event params. + * + * @return array * * @throws \CRM_Core_Exception */ - public function syncSubscriptionFromSquare(string $squareSubscriptionId) { - CRM_Core_Payment_SquareDebugLogger::log("Square syncSubscriptionFromSquare(): called from SquareIPN for subscription_id={$squareSubscriptionId}."); - if (empty($squareSubscriptionId)) { - throw new CRM_Core_Exception('Missing Square subscription ID for sync.'); - } - - // 1. Look up the subscription in Square - $response = $this->callSquare(fn (SquareClient $client) => $client->subscriptions->get( - new GetSubscriptionsRequest(['subscriptionId' => $squareSubscriptionId]) - )); - $sub = $response->getSubscription(); - - if (empty($sub)) { - throw new CRM_Core_Exception("Square subscription {$squareSubscriptionId} not found."); - } - - $status = $sub->getStatus() ?? 'UNKNOWN'; - // extractSubscriptionAmount() expects the REST JSON shape; jsonSerialize() - // gives us that from the SDK object without duplicating the extraction logic. - $amount = $this->extractSubscriptionAmount($sub->jsonSerialize()); - - // 2. Find local CiviCRM recurring contribution - $recur = ContributionRecur::get(FALSE) - ->addWhere('processor_id', '=', $squareSubscriptionId) - ->addWhere('is_test', 'IN', [TRUE, FALSE]) - ->addSelect('id', 'amount', 'currency', 'contribution_status_id') - ->execute() - ->first(); - - 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}"); - return; - } - - $recurId = (int) $recur['id']; - CRM_Core_Payment_SquareDebugLogger::log("Square syncSubscriptionFromSquare(): found contribution_recur {$recurId} for subscription {$squareSubscriptionId} (current status {$recur['contribution_status_id']}, square status {$status})."); - - // 3. Map Square → CiviCRM status - $mappedStatus = $this->mapSquareSubscriptionStatusToCivi($status); + public function doDirectPayment(&$params) { + return $this->doPayment($params); + } - // 4. Update recurring amount if changed - $updates = []; - if (!empty($amount) && (float) $amount !== (float) $recur['amount']) { - $updates['amount'] = (float) $amount; + /** + * Modern CiviCRM entry point for submitting payments (one-time or recurring). + * + * @param array $params + * Contribution or event payment parameters. + * @param string $component + * Component name (e.g. 'contribute' or 'event'). Default 'contribute'. + * + * @return array + * Updated $params array. + * + * @throws \CRM_Core_Exception + */ + public function doPayment(&$params, $component = 'contribute') { + $this->_component = $component; + try { + // Determine if this is a recurring payment. + if (!empty($params['is_recur']) || !empty($params['contributionRecurID'])) { + return $this->doRecurPayment($params); + } + return $this->doOneTimePayment($params); } - - // 5. Update contribution_status_id if needed - if ($mappedStatus !== NULL && $mappedStatus !== (int) $recur['contribution_status_id']) { - $updates['contribution_status_id'] = $mappedStatus; - CRM_Core_Payment_SquareDebugLogger::log("Square sync: Status change for subscription {$squareSubscriptionId} mapped to contribution_recur {$recurId} status {$mappedStatus}"); + catch (PaymentProcessorException $e) { + // Square declined the card: CiviCRM's checkout cleans up. + throw $e; } - - // 6. Apply updates - if (!empty($updates)) { - $q = ContributionRecur::update(FALSE) - ->addWhere('id', '=', $recurId); - foreach ($updates as $field => $value) { - $q->addValue($field, $value); + 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); } - $q->execute(); - - CRM_Core_Payment_SquareDebugLogger::log("Square sync: Updated recurring contribution {$recurId} from subscription {$squareSubscriptionId}"); + throw $e; } - else { - CRM_Core_Payment_SquareDebugLogger::log("Square syncSubscriptionFromSquare(): contribution_recur {$recurId} already up to date for subscription {$squareSubscriptionId}, no changes made."); + 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); } } /** - * Map Square subscription statuses to CiviCRM contribution_status_id. + * 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 string $squareStatus + * @param array $params * - * @return int|null + * @return string|null */ - 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. - switch ($squareStatus) { - case 'ACTIVE': - // In Progress. - return 5; - - case 'CANCELED': - case 'DEACTIVATED': - // Cancelled. - return 3; - - case 'SUSPENDED': - // Failed / On Hold. - return 4; - - 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; - } - - // If unknown, don't change local status. - return 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; } /** - * Extract override amount from Square subscription. + * Log, and describe to the payer, a charge Square may have made without confirming it. * - * @param array $subscription + * @param \Throwable $e + * @param string $reference + * What was being paid, for the log. * - * @return float|null + * @return \CRM_Core_Payment_SquareOutcomeUnknownException */ - protected function extractSubscriptionAmount(array $subscription) { - if (!empty($subscription['price_override_money']['amount'])) { - return ((float) $subscription['price_override_money']['amount']) / 100; - } - - // If no override, fall back to catalog plan pricing (unavailable via subscription API alone). - return NULL; + 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 + ); } /** - * 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) + * Handle one-time Square payments. * * @param array $params * - * @return int + * @return array + * + * @throws \CRM_Core_Exception */ - protected function getFinancialTypeId(array $params) { - // 1. Direct param from contribution form - if (!empty($params['financialTypeID'])) { - return (int) $params['financialTypeID']; + protected function doOneTimePayment(&$params) { + // 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 (!empty($params['financial_type_id'])) { - return (int) $params['financial_type_id']; + + if ((float) $amount === 0.0) { + // Nothing to charge: report it complete, as CRM_Core_Payment::doPayment() + // does for a zero amount, so the checkout completes the contribution. + $completedStatusId = CRM_Square_Status::contributionStatusId('Completed'); + $params['payment_status_id'] = $completedStatusId; + $params['payment_status'] = 'Completed'; + $params['contribution_status_id'] = $completedStatusId; + return $params; } - // 2. Check recurring template if recurID provided - if (!empty($params['contributionRecurID'])) { - $recur = ContributionRecur::get(FALSE) - ->addWhere('id', '=', (int) $params['contributionRecurID']) - ->addWhere('is_test', 'IN', [TRUE, FALSE]) - ->addSelect('financial_type_id') - ->execute() - ->first(); - - if (!empty($recur['financial_type_id'])) { - return (int) $recur['financial_type_id']; - } + // 2. Extract Web Payments SDK token. + $token = $this->getPaymentToken($params); + if (!$token) { + throw new \CRM_Core_Exception('Missing Square payment token.'); } - // 3. Fallback to Donation (ID=1) - return 1; - } + // Persist it back into $params so downstream code can see it. + $params['square_payment_token'] = $token; - /** - * Process Square invoice.payment_made webhook event. - * - * @param array $payload - * Full decoded JSON from Square webhook. - */ - public function handleInvoicePaymentCreated(array $payload) { - CRM_Core_Payment_SquareDebugLogger::log('Square handleInvoicePaymentCreated(): called from SquareIPN for invoice.payment_made.'); - if (empty($payload['data']['object']['invoice'])) { - CRM_Core_Payment_SquareDebugLogger::log('Square webhook: invoice.payment_made missing invoice object.'); - return; - } - - $invoice = $payload['data']['object']['invoice']; - $invoiceId = $invoice['id'] ?? NULL; - $subscriptionId = $invoice['subscription_id'] ?? NULL; - - if (!$invoiceId) { - CRM_Core_Payment_SquareDebugLogger::log('Square webhook: invoice missing ID.'); - return; - } - - // Fix 1: guard against non-subscription invoices (same as syncInvoiceFromSquare). - if (!$subscriptionId) { - CRM_Core_Payment_SquareDebugLogger::log("Square webhook: invoice {$invoiceId} has no subscription_id, skipping."); - return; - } - - // Load subscription payment info. - $total = $invoice['payment_requests'][0]['computed_amount_money']['amount'] ?? NULL; - $currency = $invoice['payment_requests'][0]['computed_amount_money']['currency'] ?? 'USD'; - - if ($total === NULL) { - CRM_Core_Payment_SquareDebugLogger::log("Square webhook: invoice {$invoiceId} missing payment amount."); - return; - } - - $amount = ((float) $total) / 100; - - // Fix 4: use the invoice updated_at as receive_date rather than defaulting to today. - $receiveDate = !empty($invoice['updated_at']) - ? date('Y-m-d H:i:s', strtotime($invoice['updated_at'])) - : date('Y-m-d H:i:s'); - - // Find matching Civi recurring record. - $recur = ContributionRecur::get(FALSE) - ->addWhere('processor_id', '=', $subscriptionId) - ->addWhere('is_test', 'IN', [TRUE, FALSE]) - ->addSelect('id', 'contact_id', 'is_test', 'payment_instrument_id') - ->execute() - ->first(); - - if (empty($recur)) { - CRM_Core_Payment_SquareDebugLogger::log("Square webhook: No matching contribution_recur for subscription {$subscriptionId}."); - return; - } - - $contactId = (int) $recur['contact_id']; - $recurId = (int) $recur['id']; - $paymentInstrumentId = $recur['payment_instrument_id'] ?? 1; - - // Check for duplicate contribution by invoice ID. - $existing = Contribution::get(FALSE) - ->addSelect('id', 'contribution_status_id', 'contribution_recur_id') - ->addWhere('invoice_id', '=', $invoiceId) - ->addWhere('is_test', 'IN', [TRUE, FALSE]) - ->execute() - ->first(); - - CRM_Core_Payment_SquareDebugLogger::log($existing - ? "Square webhook: found existing contribution {$existing['id']} (status {$existing['contribution_status_id']}) for invoice {$invoiceId}." - : "Square webhook: no existing contribution found for invoice {$invoiceId}, will create a new one."); - - // Check record exist and status completed and recurring is linked. - if (!empty($existing)) { - if ($existing['contribution_status_id'] == 1 && !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; - } - } - - // Determine financial type ID. - $financialTypeId = $this->getFinancialTypeId([ - 'contributionRecurID' => $recurId, - ]); - - // 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) - ->addValue('invoice_id', $invoiceId) - ->addValue('is_test', $recur['is_test']) - ->addValue('source', 'Square Recurring Payment') - ->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()); - } - CRM_Core_Payment_SquareDebugLogger::log("Square webhook: Created contribution for invoice {$invoiceId} (subscription {$subscriptionId})."); - } - - /** - * Handle a subscription cancellation event coming from Square. - * - * 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; - } - - $subscriptionId = $payload['data']['object']['subscription']['id']; - - // Find associated recurring contribution. - $recur = ContributionRecur::get(FALSE) - ->addWhere('processor_id', '=', $subscriptionId) - ->addWhere('is_test', 'IN', [TRUE, FALSE]) - ->addSelect('id') - ->execute() - ->first(); - - if (empty($recur)) { - CRM_Core_Payment_SquareDebugLogger::log("Square webhook: No matching contribution_recur found for cancelled subscription {$subscriptionId}."); - return; - } - - $recurId = (int) $recur['id']; - - // Update recurring record to Cancelled (3). - ContributionRecur::update(FALSE) - ->addWhere('id', '=', $recurId) - ->addValue('contribution_status_id', 3) - ->execute(); - - CRM_Core_Payment_SquareDebugLogger::log("Square webhook: Marked recurring contribution {$recurId} as Cancelled for subscription {$subscriptionId}."); - } - - /** - * Legacy entry point for on-site CC payments. - * - * CiviCRM still calls doDirectPayment for front-end payments. - * - * @param array $params - * Contribution / event params. - * - * @return array - * - * @throws \CRM_Core_Exception - */ - public function doDirectPayment(&$params) { - return $this->doPayment($params); - } - - /** - * Modern CiviCRM entry point for submitting payments (one-time or recurring). - * - * @param array $params - * Contribution or event payment parameters. - * @param string $component - * Component name (e.g. 'contribute' or 'event'). Default 'contribute'. - * - * @return array - * Updated $params array. - * - * @throws \CRM_Core_Exception - */ - 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); - } - return $this->doOneTimePayment($params); - } - - /** - * Setup a recurring payment (called by CiviCRM for initial setup). - * - * This is called when a recurring contribution is first created. - * It initializes the recurring payment but doesn't charge yet. - * - * @param array $params - * Recurring contribution parameters. - * - * @return array - * Updated params with subscription info. - * - * @throws \CRM_Core_Exception - */ - public function doSetupRecurring(&$params) { - // For Square, setup is handled in doRecurPayment() - // This method is called by CiviCRM but we delegate to doRecurPayment. - return $this->doRecurPayment($params); - } - - /** - * Handle one-time Square payments. - * - * @param array $params - * - * @return array - * - * @throws \CRM_Core_Exception - */ - protected function doOneTimePayment(&$params) { - // 1. 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; - - if (!$token) { - throw new \CRM_Core_Exception('Missing Square payment token.'); - } - - // 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'; + $amountMinorUnits = CRM_Square_Currency::toMinorUnits($amount, $currency); - // 3. Idempotency key. - $idempotencyKey = $this->idempotencyKey('payment', (string) ($params['invoiceID'] ?? $params['invoice_id'] ?? $params['contributionID'] ?? $params['contribution_id'] ?? 'unknown')); + // 3. Idempotency key, derived from the checkout's own reference so that a + // retried request for the same checkout can never charge twice. Every + // CiviCRM checkout supplies one; without it a retry could not be told + // apart from a new payment, so refuse rather than risk a second charge. + $paymentReference = $params['invoiceID'] ?? $params['invoice_id'] ?? $params['contributionID'] ?? $params['contribution_id'] ?? NULL; + if ($paymentReference === NULL || $paymentReference === '') { + throw new \CRM_Core_Exception('Cannot take a Square payment without a CiviCRM invoice or contribution reference.'); + } + $idempotencyKey = $this->idempotencyKey('payment', (string) $paymentReference); // 4. Build payload for CreatePayment. $requestValues = [ 'idempotencyKey' => $idempotencyKey, 'sourceId' => $token, - 'amountMoney' => new Money(['amount' => $amountCents, 'currency' => $currency]), + 'amountMoney' => new Money(['amount' => $amountMinorUnits, 'currency' => $currency]), 'locationId' => $this->getLocationId(), ]; // Add customer ID if available (optional for one-off payments) $contactId = $params['contactID'] ?? $params['contact_id'] ?? NULL; if ($contactId) { - $customerId = $this->getSquareCustomerId($contactId); + $customerId = $this->customers()->getSquareCustomerId($contactId); if ($customerId) { $requestValues['customerId'] = $customerId; } @@ -1044,32 +542,51 @@ 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. Set required CiviCRM transaction fields. - $params['trxn_id'] = $trxnId; - $params['payment_status_id'] = $this->contributionStatusId('Completed'); - $params['contribution_status_id'] = $this->contributionStatusId('Completed'); + // 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. + // 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; } /** - * Process a recurring payment. + * Set up a recurring payment as a Square subscription. * * - Expects a Web Payments SDK token in: * - $params['square_payment_token'] or * - $params['payment_token'] or * - $params['token'] - * - Creates a Square Payment via /v2/payments. - * - On success, sets trxn_id and returns $params. + * - Saves the card on file and creates a Square Subscription that starts + * immediately. Square itself charges the first installment, so no + * separate payment is made here, and the checkout's contribution is + * reported Pending: it is completed when Square confirms that charge + * (see recordSubscriptionInstallment()). * * @param array $params * Contribution / participant params. @@ -1081,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.'); } @@ -1106,149 +615,133 @@ public function doRecurPayment(&$params) { throw new CRM_Core_Exception('Missing contributionRecurID for Square recurring payments.'); } - // 3. Ensure customer exists / or create one - $customerId = $this->ensureSquareCustomer($params); - if ($this->findSquareCustomerById($customerId)) { - CRM_Core_Payment_SquareDebugLogger::log("Square doRecurPayment: Found existing Square customer ID {$customerId} for CiviCRM recur ID {$recurId}"); - $this->updateSquareCustomerDetails($customerId, $params); - } - else { - throw new CRM_Core_Exception("Failed to find or create Square customer for CiviCRM recur ID {$recurId}"); - } + // 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. Fetch the Square card ID via the PaymentToken that + // 4. Ensure the customer exists (saving the card), with current details. + $customers = $this->customers(); + $customerId = $customers->ensureSquareCustomer($params); + $customers->updateSquareCustomerDetails($customerId, $params); + + // 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 // did that, and always redeems a fresh nonce into a brand new token, // so this is always the right one for this specific recur ID. - $recurForToken = ContributionRecur::get(FALSE) - ->addWhere('id', '=', $recurId) - ->addSelect('payment_token_id') - ->execute() - ->first(); - $paymentToken = empty($recurForToken['payment_token_id']) ? NULL : PaymentToken::get(FALSE) - ->addWhere('id', '=', $recurForToken['payment_token_id']) - ->addSelect('token') - ->execute() - ->first(); - $cardId = $paymentToken['token'] ?? NULL; + $cardId = $this->getRecurCardId((int) $recurId); if (empty($cardId)) { throw new CRM_Core_Exception("Failed to attach a Square card on file for CiviCRM recur ID {$recurId}."); } 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->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'] ?? ''), '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); - // 8. Build subscription payload + // 7. Build subscription payload. startDate is deliberately omitted: + // Square then starts the subscription today (in the location's time + // zone) and immediately bills its first invoice to the card on file. + // That charge is the first installment. Previously this code set + // start_date to tomorrow AND made a separate immediate CreatePayment for + // today, which charged the donor twice once Square billed its own first + // invoice. $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 - $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)); } - $subscriptionId = $subscription->getId(); - CRM_Core_Payment_SquareDebugLogger::log('Square subscription created: ' . json_encode([ - 'subscription_id' => $subscriptionId, - '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()); - } + 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); + } + + // 10. The checkout's contribution stays Pending until Square confirms + // the first charge. No trxn_id is returned: the subscription ID + // identifies the recurring agreement (saved above as the recur's + // processor_id), not a payment, and webform_civicrm writes a returned + // trxn_id straight onto the Pending contribution. Its trxn_id becomes + // the Square payment ID when that payment is recorded. + $params['trxn_id'] = NULL; + $pendingStatusId = CRM_Square_Status::contributionStatusId('Pending'); + $params['payment_status_id'] = $pendingStatusId; + $params['payment_status'] = 'Pending'; + $params['contribution_status_id'] = $pendingStatusId; + $params['subscription_id'] = $subscriptionId; + + return $params; + } + + /** + * Square card ID saved as the recurring contribution's payment token. + * + * @param int $recurId + * + * @return string|null + */ + protected function getRecurCardId(int $recurId): ?string { + $recurForToken = ContributionRecur::get(FALSE) + ->addWhere('id', '=', $recurId) + ->addSelect('payment_token_id') + ->execute() + ->first(); + $paymentToken = empty($recurForToken['payment_token_id']) ? NULL : PaymentToken::get(FALSE) + ->addWhere('id', '=', $recurForToken['payment_token_id']) + ->addSelect('token') + ->execute() + ->first(); + return $paymentToken['token'] ?? NULL; + } - // 11. Update the recurring contribution record + /** + * Link a Square subscription to its recurring contribution. + * + * @param int $recurId + * @param string $subscriptionId + * + * @throws \CRM_Core_Exception + */ + protected function saveRecurSubscription(int $recurId, string $subscriptionId): void { ContributionRecur::update(FALSE) ->addWhere('id', '=', $recurId) ->addValue('processor_id', $subscriptionId) ->addValue('trxn_id', $subscriptionId) - // Pending. - ->addValue('contribution_status_id', 2) + ->addValue('contribution_status_id', CRM_Square_Status::recurStatusId('Pending')) ->execute(); - - // 12. Return CiviCRM-standard response - return [ - // Pending. - 'payment_status_id' => 2, - // Pending. - 'contribution_status_id' => 2, - 'trxn_id' => $subscriptionId, - 'subscription_id' => $subscriptionId, - ]; } /** @@ -1272,612 +765,181 @@ public function supportsRefund() { /** * Perform a refund via Square Refunds API. * - * @param array $params - * - * @return array - * - * @throws \CRM_Core_Exception - */ - 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.'); - } - - if (empty($params['amount'])) { - throw new CRM_Core_Exception('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.'); - } - - $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]), - ]); - - $response = $this->createRefund($refundRequest); - $refund = $response->getRefund(); - - if (empty($refund) || empty($refund->getId())) { - $msg = 'Square refund failed: unexpected response.'; - throw new CRM_Core_Exception($msg); - } - - $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); - } - - return [ - 'refund_status' => $status, - 'refund_trxn_id' => $refund->getId(), - ]; - } - - /** - * Call the Square Refunds API through a testable seam. - * - * @param \Square\Refunds\Requests\RefundPaymentRequest $request - * - * @return \Square\Types\RefundPaymentResponse - * - * @throws \CRM_Core_Exception - */ - protected function createRefund(RefundPaymentRequest $request) { - return $this->callSquare(fn (SquareClient $client) => $client->refunds->refundPayment($request)); - } - - /** - * Invoke the Square SDK client and translate its exceptions to CRM_Core_Exception. - * - * @param callable(\Square\SquareClient): mixed $call - * - * @return mixed - * Whatever $call returns (typically a Square SDK response object). - * - * @throws \CRM_Core_Exception - */ - protected function callSquare(callable $call) { - try { - return $call($this->buildSquareClient()); - } - catch (SquareApiException $e) { - throw $this->squareApiError($e); - } - catch (SquareException $e) { - throw new CRM_Core_Exception('Square API request failed: ' . $e->getMessage()); - } - } - - /** - * Convert a Square SDK API exception to the message shape callers expect. - * - * @param \Square\Exceptions\SquareApiException $e - * - * @return \CRM_Core_Exception - */ - protected function squareApiError(SquareApiException $e): CRM_Core_Exception { - $errorDetails = []; - foreach ($e->getErrors() as $err) { - $code = $err->getCode() ?: 'UNKNOWN'; - $detail = $err->getDetail() ?? ''; - $errorDetails[] = "{$code}: {$detail}"; - } - $msg = "Square API returned HTTP {$e->getStatusCode()}."; - if ($errorDetails) { - $msg .= ' ' . implode(' | ', $errorDetails); - } - return new CRM_Core_Exception($msg); - } - - /** - * 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->callSquare(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 - */ - protected function findSquareCustomerById($customerID) { - if (empty($customerID)) { - return NULL; - } - - $response = $this->callSquare(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. - * - * @param string $customerID - * Square customer ID. - * @param array $params - * CiviCRM payment parameters. - * - * @return void - * - * @throws CRM_Core_Exception - */ - protected function updateSquareCustomerDetails($customerID, $params) { - $firstName = $params['first_name'] ?? NULL; - $lastName = $params['last_name'] ?? NULL; - $email = $params['email'] ?? $params['email-5'] ?? NULL; - $contactID = $params['contactID'] ?? $params['contact_id'] ?? NULL; - - $requestValues = ['customerId' => $customerID]; - if (!empty($firstName)) { - $requestValues['givenName'] = $firstName; - } - if (!empty($lastName)) { - $requestValues['familyName'] = $lastName; - } - if (!empty($email)) { - $requestValues['emailAddress'] = $email; - } - if (!empty($contactID)) { - $requestValues['referenceId'] = (string) $contactID; - } - - $this->callSquare(fn (SquareClient $client) => $client->customers->update(new UpdateCustomerRequest($requestValues))); - } - - /** - * Ensure a Square customer exists for this contact. Also handles storing card_id if available. - * - * 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. + * 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 - * Contribution params (includes contactID/contact_id). - * - * @return string - * Square customer ID. + * trxn_id (the Square payment ID) and amount; currency is optional, and + * ignored in favour of the payment's own. * - * @throws CRM_Core_Exception - */ - public function ensureSquareCustomer(array $params) { - $contactID = $params['contactID'] ?? $params['contact_id'] ?? NULL; - 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->callSquare(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 => [(int) ($this->_paymentProcessor['id'] ?? 0), '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); - - // 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 (\Exception $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; - } - - // 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); - - 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 => [(int) ($this->_paymentProcessor['id'] ?? 0), 'Integer']] - ); - - 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.'); - } - - // 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); - } - return $squareCustomerByEmail; - } - - // 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)) { - 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->callSquare(fn (SquareClient $client) => $client->customers->create(new CreateCustomerRequest([ - 'givenName' => $firstName, - 'familyName' => $lastName, - 'emailAddress' => $email, - '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); - - // 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); - } - - return $customerId; - } - - /** - * Attach a card to the Square customer using the tokenized card nonce. - * - * @param string $customerId - * Square customer ID. - * @param string $cardNonce - * Token from Web Payments SDK. - * @param array $params - * Additional parameters, possibly including verification_token. - * @param int|null $contactId - * CiviCRM contact ID (optional, but required to record a PaymentToken). - * - * @return string - * Square card ID. + * @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 createCardOnFile($customerId, $cardNonce, array $params = [], $contactId = NULL) { - if (empty($cardNonce)) { - throw new CRM_Core_Exception('Missing Square card token for recurring payment.'); + public function doRefund(&$params) { + $trxnId = $params['trxn_id'] ?? $params['transaction_id'] ?? NULL; + if (empty($trxnId)) { + throw new PaymentProcessorException('Missing transaction ID for refund.'); } - $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'), - ]); + if (empty($params['amount'])) { + throw new PaymentProcessorException('Missing refund amount.'); } - $requestValues = [ - 'idempotencyKey' => uniqid('square_card_', TRUE), - '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']; + $rawAmount = (float) $params['amount']; + if ($rawAmount <= 0) { + throw new PaymentProcessorException('Refund amount must be greater than zero.'); } try { - $response = $this->buildSquareClient()->cards->create(new CreateCardRequest($requestValues)); + // 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.'); + } + + // 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 (SquareApiException $e) { - // Translate structured Square card errors into a human-friendly message. - throw new CRM_Core_Exception($this->translateSquareCardError($e->getErrors())); + catch (PaymentProcessorException $e) { + throw $e; } - catch (SquareException $e) { - throw new CRM_Core_Exception('Square API request failed: ' . $e->getMessage()); + catch (\Throwable $e) { + throw new PaymentProcessorException(E::ts('Square refund failed: %1', [1 => $e->getMessage()]), 0, [], $e); } - $card = $response->getCard(); - if (empty($card) || empty($card->getId())) { - throw new CRM_Core_Exception('Failed to create card on file with Square.'); + if (empty($refund) || empty($refund->getId())) { + throw new PaymentProcessorException('Square refund failed: unexpected response.'); } - $cardId = $card->getId(); - - // Record this card as a CiviCRM PaymentToken (instead of a custom - // field) so multiple cards per contact are properly distinguished, and - // link it to the recurring contribution it was created for, if any. - if (!empty($contactId)) { - $expiryDate = NULL; - if ($card->getExpYear() && $card->getExpMonth()) { - $expiryDate = date('Y-m-t', mktime(0, 0, 0, (int) $card->getExpMonth(), 1, (int) $card->getExpYear())); - } - - $tokenCreate = PaymentToken::create(FALSE) - ->addValue('contact_id', (int) $contactId) - ->addValue('payment_processor_id', (int) ($this->_paymentProcessor['id'] ?? 0)) - ->addValue('token', $cardId) - ->addValue('masked_account_number', $card->getLast4()); - if ($expiryDate) { - $tokenCreate->addValue('expiry_date', $expiryDate); - } - if (!empty($params['first_name'])) { - $tokenCreate->addValue('billing_first_name', $params['first_name']); - } - if (!empty($params['last_name'])) { - $tokenCreate->addValue('billing_last_name', $params['last_name']); - } - $email = $params['email'] ?? $params['email-5'] ?? NULL; - if (!empty($email)) { - $tokenCreate->addValue('email', $email); - } - $paymentToken = $tokenCreate->execute()->first(); - - if (!empty($paymentToken['id']) && !empty($params['contributionRecurID'])) { - ContributionRecur::update(FALSE) - ->addWhere('id', '=', (int) $params['contributionRecurID']) - ->addValue('payment_token_id', $paymentToken['id']) - ->execute(); - } + $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}"); } - return $cardId; + $createdAt = $refund->getCreatedAt(); + return [ + '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, + ]; } /** - * Map country to standardized 2-letter country code. + * 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 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', - ]; - - // Normalize input. - $normalizedCountry = strtoupper(trim($country)); - - // Return mapped country or default to US. - return $countryMap[$normalizedCountry] ?? 'US'; + 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]; } /** - * Translate Square card errors to human-friendly messages. + * Wait briefly for Square to complete a refund it accepted as PENDING. * - * @param \Square\Types\Error[] $errors - * Square card errors. + * 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. * - * @return string + * @param \Square\Types\PaymentRefund $refund + * + * @return \Square\Types\PaymentRefund + * The refund as Square last reported it. */ - protected function translateSquareCardError(array $errors) { - $messages = []; - - foreach ($errors as $err) { - $code = $err->getCode() ?? ''; - switch ($code) { - case 'CARD_DECLINED': - $messages[] = 'Your card was declined. Please use a different card.'; - break; - - case 'GENERIC_DECLINE': - $messages[] = 'The card was declined by the bank.'; - break; - - case 'INVALID_EXPIRATION': - $messages[] = 'The card expiration date is invalid.'; - break; - - case 'CVV_FAILURE': - $messages[] = 'The CVV security code is incorrect.'; - break; - - case 'ADDRESS_VERIFICATION_FAILURE': - $messages[] = 'The billing ZIP/postal code did not match the card.'; - break; - - case 'INSUFFICIENT_FUNDS': - $messages[] = 'The card has insufficient funds.'; - break; - - default: - if (!empty($err->getDetail())) { - $messages[] = $err->getDetail(); - } - else { - $messages[] = 'The card could not be processed.'; - } - break; + 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 implode(' ', $messages); + return $refund; } /** - * Get the plan variation ID for recurring-payment parameters. + * A refund as Square currently reports it. + * + * @param string $refundId + * + * @return \Square\Types\PaymentRefund|null + * + * @throws \CRM_Core_Exception */ - protected function getPlanVariationIdForParams(array $params): string { - $entity = $params['component'] ?? 'contribute'; - $amount = (float) ($params['amount'] ?? 0); - $currency = $params['currency'] ?? 'USD'; - $intervalUnit = $params['frequency_unit'] ?? ''; - $intervalStep = (int) ($params['frequency_interval'] ?? 1); - $installments = (int) ($params['installments'] ?? 0); - if (!$amount || !$intervalUnit) { - throw new CRM_Core_Exception('Amount and cadence are required for Square subscription.'); - } - - // A plan identifies a subscription purpose; a variation identifies its amount and cadence. - $planName = sprintf( - 'CiviCRM %s', - ucfirst($entity) - ); + protected function getRefund(string $refundId): ?PaymentRefund { + return $this->callSquare(fn (SquareClient $client) => $client->refunds->get(new GetRefundsRequest(['refundId' => $refundId])))->getRefund(); + } - $planId = $this->getOrCreateSubscriptionPlan($planName); - CRM_Core_Payment_SquareDebugLogger::log("Square plan ID for {$entity}: {$planId}"); - return $this->getOrCreatePlanVariation( - $planId, $amount, - $currency, $intervalUnit, - $intervalStep, $installments - ); + /** + * Wait, between checks on a refund. + * + * @param int $microseconds + */ + protected function pause(int $microseconds): void { + usleep($microseconds); } /** - * Determine the Square plan ID for this recurring payment. + * Call the Square Refunds API through a testable seam. * - * @param array $params + * @param \Square\Refunds\Requests\RefundPaymentRequest $request * - * @return string + * @return \Square\Types\RefundPaymentResponse * * @throws \CRM_Core_Exception */ - protected function getPlanIdForParams(array $params) { - $membershipTypeId = $params['membership_type_id'] ?? NULL; - - $planMap = Civi::settings()->get('org_uschess_square_plan_map') ?? []; - $planId = NULL; - - if ($membershipTypeId && isset($planMap[$membershipTypeId])) { - $planId = $planMap[$membershipTypeId]; - } - - if (!$planId) { - throw new CRM_Core_Exception("No Square plan mapping found for membership type ID {$membershipTypeId}."); - } - - return $planId; + protected function createRefund(RefundPaymentRequest $request) { + return $this->callSquare(fn (SquareClient $client) => $client->refunds->refundPayment($request)); } /** @@ -1914,138 +976,113 @@ public function doCancelRecurring(PropertyBag $propertyBag): array { 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.')]; } /** - * Cancel a Square subscription by its processor ID. + * Change the amount of a Square subscription. * - * Low-level helper used by doCancelRecurring() and by the civicrm_post hook. - * Makes the Square API call directly without PropertyBag logic. + * CiviCRM's contract for "change the amount of a recurring contribution" + * (CRM_Contribute_Form_UpdateSubscription): its existence enables that + * form's amount field. After this returns, CiviCRM saves the submitted + * amount and installments on the recurring contribution. * - * @param string $subscriptionId - * Square subscription ID (e.g. "SUB_xxx"). + * @param string $message + * Activity details for the change; unchanged here. + * @param array $params + * From the form: subscriptionId (the recur's processor_id), + * contributionRecurID, amount and installments. + * + * @return bool * * @throws \Civi\Payment\Exception\PaymentProcessorException */ - public function cancelSquareSubscription(string $subscriptionId): void { - if (empty($subscriptionId)) { - throw new PaymentProcessorException(E::ts('Cannot cancel Square subscription: empty subscription ID.')); + public function changeSubscriptionAmount(&$message = '', $params = []) { + $subscriptionId = $params['subscriptionId'] ?? NULL; + $recurId = (int) ($params['contributionRecurID'] ?? $params['id'] ?? 0); + // 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.')); } - $this->callSquare(fn (SquareClient $client) => $client->subscriptions->cancel( - new CancelSubscriptionsRequest(['subscriptionId' => $subscriptionId]) - )); - } - - /** - * Update subscription amount at Square. - * - * @param string $subscriptionId - * @param float $newAmount - * @param string $currency - * - * @throws \CRM_Core_Exception - */ - public function updateSubscriptionAmount($subscriptionId, $newAmount, $currency = 'USD') { - $amountCents = (int) round(((float) $newAmount) * 100); - - $this->callSquare(fn (SquareClient $client) => $client->subscriptions->update(new UpdateSubscriptionRequest([ - 'subscriptionId' => $subscriptionId, - 'subscription' => new Subscription([ - 'priceOverrideMoney' => new Money(['amount' => $amountCents, 'currency' => $currency]), - ]), - ]))); - } - - /** - * 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, - ]), - ]))); - } + $recur = $this->getRecurForAmountChange($recurId); + if (!$recur || $recur['processor_id'] !== $subscriptionId) { + throw new PaymentProcessorException(E::ts('This recurring contribution is not linked to that Square subscription.')); + } + // CiviCRM also saves the form's installments; Square cannot change the + // number of billing periods of an existing subscription. + if (isset($params['installments']) && (int) $params['installments'] !== (int) ($recur['installments'] ?? 0)) { + throw new PaymentProcessorException(E::ts('Square cannot change the number of installments of an existing subscription. Cancel it and create a new recurring contribution instead.')); + } + // CiviCRM only moves a single-line-item template contribution to the + // new amount, so later installments of a multi-item series would keep + // the old one — and never match what Square charges. + if ($recur['line_item_count'] > 1) { + throw new PaymentProcessorException(E::ts('The amount of a recurring contribution with more than one line item cannot be changed.')); + } - /** - * 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, - ]), - ]))); + try { + $this->subscriptions()->changeAmount($subscriptionId, (float) $amount, $recur['currency']); + } + catch (\Throwable $e) { + throw new PaymentProcessorException(E::ts('Failed to change the Square subscription amount: %1', [1 => $e->getMessage()]), 0, [], $e); + } + return TRUE; } /** - * Get the Square customer ID stored for a contact and processor. - * - * Live and sandbox accounts use distinct customer records. + * The recurring contribution changeSubscriptionAmount() is changing. * - * @param int $contactId + * @param int $recurId * - * @return string|null + * @return array|null + * processor_id, installments, currency, and line_item_count (of the + * template contribution later installments are copied from). NULL if + * the recurring contribution does not belong to this processor. */ - protected function getSquareCustomerId($contactId) { - $contactId = (int) $contactId; - $processorId = (int) ($this->_paymentProcessor['id'] ?? 0); - if ($contactId <= 0 || $processorId <= 0) { + protected function getRecurForAmountChange(int $recurId): ?array { + $recur = ContributionRecur::get(FALSE) + ->addSelect('processor_id', 'installments', 'currency') + ->addWhere('id', '=', $recurId) + ->addWhere('payment_processor_id', '=', $this->processorId()) + ->execute() + ->first(); + if (!$recur) { return NULL; } - - $customerId = CRM_Core_DAO::singleValueQuery( - 'SELECT square_customer_id FROM square_customer_map WHERE contact_id = %1 AND payment_processor_id = %2', - [1 => [$contactId, 'Integer'], 2 => [$processorId, 'Integer']] - ); - - return $customerId !== NULL ? (string) $customerId : NULL; + // Flattened: otherwise line_item is keyed by price set, one entry per set. + $template = CRM_Contribute_BAO_ContributionRecur::getTemplateContribution($recurId, [], TRUE); + $recur['line_item_count'] = count($template['line_item'] ?? []); + return $recur; } /** - * Save the Square customer ID for a contact and processor. + * Cancel a Square subscription by its processor ID. * - * See getSquareCustomerId(). + * Low-level helper used by doCancelRecurring(). Makes the Square API call + * directly without PropertyBag logic. * - * @param int $contactId - * @param string $customerId + * @param string $subscriptionId + * Square subscription ID (e.g. "SUB_xxx"). + * + * @throws \Civi\Payment\Exception\PaymentProcessorException */ - protected function saveSquareCustomerId($contactId, $customerId) { - $contactId = (int) $contactId; - $processorId = (int) ($this->_paymentProcessor['id'] ?? 0); - if ($contactId <= 0 || $processorId <= 0 || empty($customerId)) { - return; + public function cancelSquareSubscription(string $subscriptionId): void { + if (empty($subscriptionId)) { + throw new PaymentProcessorException(E::ts('Cannot cancel Square subscription: empty subscription ID.')); } - CRM_Core_DAO::executeQuery( - 'INSERT INTO square_customer_map (contact_id, payment_processor_id, square_customer_id) - VALUES (%1, %2, %3) - ON DUPLICATE KEY UPDATE square_customer_id = VALUES(square_customer_id)', - [1 => [$contactId, 'Integer'], 2 => [$processorId, 'Integer'], 3 => [$customerId, 'String']] - ); + $this->subscriptions()->cancel($subscriptionId); } /** @@ -2085,385 +1122,6 @@ protected function supportsCancelRecurringNotifyOptional() { return TRUE; } - /** - * Advertise the configuration fields used by this processor. - */ - public static function getPaymentProcessorSettings() { - return [ - 'user_name' => [ - 'label' => ts('Square Application ID'), - 'description' => ts('Found under Developer Dashboard → Your Application → Credentials.'), - 'type' => 'Text', - 'size' => CRM_Utils_Type::HUGE, - 'required' => TRUE, - ], - 'password' => [ - 'label' => ts('Square Access Token'), - 'description' => ts('The Square Access Token (sandbox or production).'), - 'type' => 'Password', - 'size' => CRM_Utils_Type::HUGE, - 'required' => TRUE, - ], - 'signature' => [ - 'label' => ts('Square Location ID'), - 'description' => ts('Found under Locations in your Square Dashboard.'), - 'type' => 'Text', - 'size' => CRM_Utils_Type::HUGE, - 'required' => TRUE, - ], - 'test_user_name' => [ - 'label' => ts('Square Sandbox Application ID'), - 'description' => ts('Found under Developer Dashboard → Your Application → Credentials.'), - 'type' => 'Text', - 'size' => CRM_Utils_Type::HUGE, - 'required' => TRUE, - ], - 'test_password' => [ - 'label' => ts('Square Sandbox Access Token'), - 'description' => ts('The Square Access Token (sandbox or production).'), - 'type' => 'Password', - 'size' => CRM_Utils_Type::HUGE, - 'required' => TRUE, - ], - 'test_signature' => [ - 'label' => ts('Square Sandbox Location ID'), - 'description' => ts('Found under Locations in your Square Dashboard.'), - 'type' => 'Text', - 'size' => CRM_Utils_Type::HUGE, - 'required' => TRUE, - ], - 'subject' => [ - 'label' => ts('Webhook Signature Key'), - 'description' => ts('The Webhook Signature Key used to validate events from Square.'), - 'type' => 'Text', - 'size' => CRM_Utils_Type::HUGE, - 'required' => TRUE, - ], - 'test_subject' => [ - 'label' => ts('Square Sandbox Webhook Signature Key'), - 'description' => ts('The Webhook Signature Key used to validate events from Square.'), - 'type' => 'Text', - 'size' => CRM_Utils_Type::HUGE, - 'required' => TRUE, - ], - 'is_test' => [ - 'label' => ts('Is Test Mode?'), - 'description' => ts('When enabled, uses Square Sandbox environment instead of Live.'), - 'type' => 'Checkbox', - 'required' => FALSE, - 'default' => 1, - ], - ]; - } - - /** - * Validate payment processor settings on save. - */ - public function validateForm($values, &$errors) { - if (($values['payment_processor_type_id:name'] ?? '') !== 'Square') { - 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.'); - } - } - - /** - * Get or create a subscription plan variation with cadence. - * - * @param string $planId - * @param float $amount - * @param string $currency - * @param string $intervalUnit - * Day, week, month, or year. - * @param int $intervalStep - * @param int|null $installments - * - * @return string Plan variation ID - * - * @throws CRM_Core_Exception - */ - protected function getOrCreatePlanVariation( - string $planId, - float $amount, - string $currency, - string $intervalUnit, - int $intervalStep = 1, - ?int $installments = NULL, - ): string { - 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}"; - $cache = Civi::settings()->get('org_square_plan_variation_cache') ?? []; - - if (!empty($cache[$cacheKey])) { - return $cache[$cacheKey]; - } - - $label = sprintf( - '%s %0.2f %s', - $cadence, - $amount, - $currency - ); - CRM_Core_Payment_SquareDebugLogger::log("Creating label Square plan variation: {$label}"); - $amountCents = (int) round($amount * 100); - - $phase = new SubscriptionPhase([ - 'ordinal' => 0, - // MONTHLY, ANNUAL. - 'cadence' => strtoupper($cadence), - 'periods' => $installments ?? 0, - 'pricing' => new SubscriptionPricing([ - 'type' => 'STATIC', - 'priceMoney' => new Money(['amount' => $amountCents, 'currency' => $currency]), - ]), - ]); - - $catalogObject = CatalogObject::subscriptionPlanVariation(new CatalogObjectSubscriptionPlanVariation([ - 'id' => '#var_' . md5($cacheKey), - 'subscriptionPlanVariationData' => new CatalogSubscriptionPlanVariation([ - 'name' => $label, - 'subscriptionPlanId' => $planId, - 'phases' => [$phase], - ]), - ])); - - $response = $this->callSquare(fn (SquareClient $client) => $client->catalog->batchUpsert(new BatchUpsertCatalogObjectsRequest([ - 'idempotencyKey' => uniqid('plan_var_', TRUE), - 'batches' => [new CatalogObjectBatch(['objects' => [$catalogObject]])], - ]))); - - $objects = $response->getObjects(); - $variationId = !empty($objects[0]) ? $objects[0]->getValue()->getId() : NULL; - CRM_Core_Payment_SquareDebugLogger::log("Created Square plan variation ID: {$variationId}"); - if (!$variationId) { - throw new CRM_Core_Exception('Failed to create Square plan variation.'); - } - - $cache[$cacheKey] = $variationId; - Civi::settings()->set('org_square_plan_variation_cache', $cache); - - return $variationId; - } - - /** - * Resolve Square cadence from interval unit + frequency. - * - * @param string $unit - * Day, week, month, or year. - * @param int $step - * - * @return string - * - * @throws CRM_Core_Exception - */ - protected function resolveCadence(string $unit, int $step): string { - - foreach (self::SQUARE_CADENCES as $cadence => $def) { - if ($def['unit'] === $unit && $def['step'] === $step) { - return $cadence; - } - } - - throw new CRM_Core_Exception( - "Unsupported Square cadence: every {$step} {$unit}(s)" - ); - } - - /** - * Get or create a Square Subscription Plan. - * - * @param string $name - * - * @return string Plan ID - * - * @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. - $cache = Civi::settings()->get('org_square_plan_cache') ?? []; - - if (!empty($cache[$name])) { - return $cache[$name]; - } - - $catalogObject = CatalogObject::subscriptionPlan(new CatalogObjectSubscriptionPlan([ - 'id' => '#plan_' . md5($name), - '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), - 'batches' => [new CatalogObjectBatch(['objects' => [$catalogObject]])], - ]))); - - $objects = $response->getObjects(); - $planId = !empty($objects[0]) ? $objects[0]->getValue()->getId() : NULL; - if (!$planId) { - throw new CRM_Core_Exception('Failed to create Square subscription plan.'); - } - - $cache[$name] = $planId; - Civi::settings()->set('org_square_plan_cache', $cache); - - return $planId; - } - - /** - * Map Square payment statuses to CiviCRM contribution status IDs. - * - * @param string $squareStatus - * Status from Square API (e.g., 'COMPLETED', 'PENDING', 'FAILED', 'CANCELED'). - * - * @return int|null - * CiviCRM contribution_status_id or NULL if unmapped. - */ - protected function mapPaymentStatus($squareStatus) { - $squareStatus = strtoupper(trim($squareStatus)); - - switch ($squareStatus) { - case 'COMPLETED': - case 'APPROVED': - // Completed. - return 1; - - case 'PENDING': - case 'PROCESSING': - // Pending. - return 2; - - case 'FAILED': - case 'DECLINED': - case 'CANCELED': - // Failed. - return 4; - - case 'REFUNDED': - // Refunded. - return 7; - - default: - return NULL; - } - } - - /** - * Map a Square source_type to a CiviCRM payment_instrument_id. - * - * Square source_type values: CARD, BANK_ACCOUNT, WALLET, CASH, EXTERNAL, - * BUY_NOW_PAY_LATER, SQUARE_ACCOUNT. - * - * CiviCRM defaults: 1=Credit Card, 2=Debit Card, 3=Cash, 4=Check, 5=EFT. - */ - protected function mapPaymentInstrument(?string $sourceType): int { - switch (strtoupper((string) $sourceType)) { - case 'CARD': - // Apple Pay / Google Pay / Cash App Pay tokenize as cards. - case 'WALLET': - case 'BUY_NOW_PAY_LATER': - case 'SQUARE_ACCOUNT': - // Credit Card. - return 1; - - case 'BANK_ACCOUNT': - // EFT. - return 5; - - case 'CASH': - // Cash. - return 3; - - default: - // Credit Card (Square's most common instrument) - return 1; - } - } - - /** - * 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. - * - * @param array $payment - * Payment object from Square API. - * - * @return int|null - * 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->buildSquareClient()->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 (\Exception $e) { - } - } - - // 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']; - } - } - - // 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']; - } - } - - return NULL; - } - /** * Get webhook signature key from processor config. * @@ -2476,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. * @@ -2512,49 +1160,6 @@ public function handleSubscriptionUpdated(array $payload) { $this->syncSubscriptionFromSquare($subscriptionId); } - /** - * Sync a Square subscription cancellation into CiviCRM. - * - * Called when Square sends subscription.canceled or subscription.deleted webhook. - * - * @param string $squareSubscriptionId - * The subscription ID from Square. - * - * @throws \CRM_Core_Exception - */ - 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 = ContributionRecur::get(FALSE) - ->addWhere('processor_id', '=', $squareSubscriptionId) - ->addWhere('is_test', 'IN', [TRUE, FALSE]) - ->addSelect('id', 'contribution_status_id') - ->execute() - ->first(); - - 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."); - - // Update the recurring contribution to Cancelled (status_id = 3) - ContributionRecur::update(FALSE) - ->addWhere('id', '=', $recurId) - // Cancelled. - ->addValue('contribution_status_id', 3) - ->execute(); - - CRM_Core_Payment_SquareDebugLogger::log("Square syncSubscriptionCancellationFromSquare(): Updated recurring contribution {$recurId} to Cancelled for subscription {$squareSubscriptionId}."); - } - /** * Override CRM_Core_Payment function. * @@ -2589,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()); @@ -2646,7 +1253,7 @@ protected function validateWebhookSignature(string $rawData, array $headers): bo $provided = $normalised['x-square-hmacsha256-signature'] ?? NULL; if (!$provided) { - Civi::log()->error('Square IPN: X-Square-Signature header missing.'); + Civi::log()->error('Square IPN: X-Square-Hmacsha256-Signature header missing.'); return FALSE; } diff --git a/CRM/Core/Payment/SquareIPN.php b/CRM/Core/Payment/SquareIPN.php index 013760a5..666add3f 100644 --- a/CRM/Core/Payment/SquareIPN.php +++ b/CRM/Core/Payment/SquareIPN.php @@ -1,7 +1,5 @@ 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. + $lock = $this->acquireDedupeLock("worker.square.webhook.{$processorId}.{$eventId}"); + if (!$lock) { + 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(); + try { + // Deduplicate across every queue state. A replay is never reprocessed + // here: a row still in 'new' is retried by the scheduled job, and an + // 'error' row needs someone to look at it first. + if ($this->findQueuedEvent($processorId, (string) $eventId)) { + CRM_Core_Payment_SquareDebugLogger::log("Square IPN: duplicate event '{$eventId}' already queued, skipping."); + return TRUE; + } + + // Recorded in the default status 'new', so that if this request dies + // while processing it below, the scheduled job still retries it. A + // cron run picking it up concurrently is harmless: recording is + // idempotent and serialized by CRM_Core_Payment_Square's locks. + $newWebhookEvent = $this->createQueueRecord([ + 'payment_processor_id' => $processorId, + 'trigger' => $eventType, + 'identifier' => $identifier, + 'event_id' => (string) $eventId, + 'data' => $this->getData(), + ]); + } + finally { + $lock->release(); + } return $this->processQueuedWebhookEvent($newWebhookEvent); } @@ -169,12 +202,22 @@ public function onReceiveWebhook(array $payload): bool { /** * 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 immediately from onReceiveWebhook(), and later by the scheduled + * job (via CRM_Core_Payment_Square::processWebhookEvent()) for any row + * left in status 'new'. + * + * Outcomes: + * - 'success': processed. + * - 'new': a CRM_Core_Payment_SquareRetryableException was thrown (Square + * API unavailable, or a related record not there yet because webhooks + * arrived out of order) — left for the job to retry, for up to + * RETRY_WINDOW_SECONDS after the event was first received. + * - 'error': anything else, including a retryable failure that outlived + * the retry window. Never retried automatically. * * @param array $webhookEvent * - * @return bool TRUE on success. + * @return bool TRUE unless the event failed permanently. */ public function processQueuedWebhookEvent(array $webhookEvent): bool { $payload = $webhookEvent['data']; @@ -190,35 +233,117 @@ public function processQueuedWebhookEvent(array $webhookEvent): bool { $this->setInputParameters($payload, $eventType); - $ok = FALSE; + $status = 'error'; $message = ''; try { $this->processWebhookEvent($payload, $eventType); - $ok = TRUE; + $status = 'success'; $message = 'Processed successfully'; } - catch (Exception $e) { + catch (CRM_Core_Payment_SquareRetryableException $e) { + if ($this->isWithinRetryWindow($webhookEvent)) { + $status = 'new'; + $message = 'Will retry: ' . $e->getMessage(); + Civi::log()->warning("Square IPN: processQueuedWebhookEvent transient failure, will retry. EventID: {$this->event_id}: " . $e->getMessage()); + } + else { + $message = 'Gave up retrying: ' . $e->getMessage(); + Civi::log()->error("Square IPN: processQueuedWebhookEvent still failing after the retry window, giving up. EventID: {$this->event_id}: " . $e->getMessage()); + } + } + catch (\Throwable $e) { + // Catches Error/TypeError too, not just Exception — the scheduled job + // does not catch anything itself, so an escaping error would abort it + // and leave this and every later row stuck in 'processing'. $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('message', preg_replace('/^(.{250}).*/su', '$1 ...', $message)); - if ($ok) { - $update->addValue('processed_date', 'now'); + $values = [ + 'status' => $status, + 'message' => preg_replace('/^(.{250}).*/su', '$1 ...', $message), + ]; + if ($status === 'success') { + $values['processed_date'] = 'now'; } - $update->execute(); + $this->updateQueueRecord((int) $webhookEvent['id'], $values); - return $ok; + return $status !== 'error'; } /** - * Build a queue identifier for related webhook events. + * Take the lock guarding one event's deduplication. + * + * @param string $name + * + * @return \CRM_Core_Lock|null + * NULL if another request holds it. + */ + protected function acquireDedupeLock(string $name) { + $lock = new CRM_Core_Lock($name, 30); + return $lock->acquire() ? $lock : NULL; + } + + /** + * Find an event already recorded in the webhook queue. + * + * @param int $processorId + * @param string $eventId + * + * @return array|null + */ + protected function findQueuedEvent(int $processorId, string $eventId): ?array { + return PaymentprocessorWebhook::get(FALSE) + ->addSelect('id') + ->addWhere('payment_processor_id', '=', $processorId) + ->addWhere('event_id', '=', $eventId) + ->execute() + ->first(); + } + + /** + * Record an event in the webhook queue, in its default status 'new'. * - * Related invoice events share an identifier and are processed serially. + * @param array $values + * + * @return array + * The queue record. + */ + protected function createQueueRecord(array $values): array { + return PaymentprocessorWebhook::create(FALSE) + ->setValues($values) + ->execute() + ->first(); + } + + /** + * Update a webhook queue record. + * + * @param int $id + * @param array $values + */ + protected function updateQueueRecord(int $id, array $values): void { + PaymentprocessorWebhook::update(FALSE) + ->addWhere('id', '=', $id) + ->setValues($values) + ->execute(); + } + + /** + * Whether a queued event is still young enough to be retried. + * + * @param array $webhookEvent + * + * @return bool + */ + protected function isWithinRetryWindow(array $webhookEvent): bool { + $created = empty($webhookEvent['created_date']) ? FALSE : strtotime($webhookEvent['created_date']); + return $created === FALSE || (time() - $created) < self::RETRY_WINDOW_SECONDS; + } + + /** + * Build a queue identifier for related webhook events. * * @return string */ @@ -287,24 +412,23 @@ 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': - $invoice = $obj['invoice'] ?? []; - if (!empty($invoice)) { - $this->handleInvoiceCreated($invoice); - } + // Nothing to record. Square publishes invoice.created while the + // invoice is still a DRAFT it has not tried to charge, so it is never + // evidence of payment — and it must not create a contribution + // either: the first invoice of a subscription belongs to the Pending + // contribution CiviCRM created at checkout. The installment is + // recorded once Square confirms the charge, via invoice.payment_made + // or payment.updated (see + // 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; case 'invoice.payment_made': @@ -312,10 +436,10 @@ 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->handleInvoicePaymentFailed($invoice); + $this->_paymentProcessor->syncInvoicePaymentFailedFromSquare($invoice); } break; @@ -328,10 +452,11 @@ public function processWebhookEvent(array $payload, string $eventType): bool { break; case 'refund.created': + case 'refund.updated': $refund = $obj['refund'] ?? []; if (!empty($refund)) { $this->_paymentProcessor->syncRefundFromSquare($refund); - CRM_Core_Payment_SquareDebugLogger::log("Square IPN: refund.created synced for payment {$this->payment_id}"); + CRM_Core_Payment_SquareDebugLogger::log("Square IPN: {$eventType} synced for payment {$this->payment_id}"); } break; @@ -343,145 +468,6 @@ public function processWebhookEvent(array $payload, string $eventType): bool { return TRUE; } - /** - * Handle invoice.created — create a Pending contribution for an upcoming invoice. - * - * Square invoice payload path: - * data.object.invoice.{id, subscription_id, status, - * payment_requests[0].computed_amount_money.{amount(cents), currency}} - * - * @param array $invoice - * Invoice object from Square webhook payload. - */ - protected function handleInvoiceCreated(array $invoice): void { - $invoiceId = $invoice['id'] ?? NULL; - $subscriptionId = $invoice['subscription_id'] ?? NULL; - $status = strtoupper($invoice['status'] ?? ''); - - if (!$invoiceId || !$subscriptionId) { - CRM_Core_Payment_SquareDebugLogger::log('Square IPN: invoice.created missing invoice ID or subscription_id.'); - return; - } - - // Skip invoices that are already paid — invoice.payment_made handles those. - if (in_array($status, ['PAID', 'PAYMENT_PENDING'], TRUE)) { - CRM_Core_Payment_SquareDebugLogger::log("Square IPN: invoice.created skipped (status={$status})."); - return; - } - - $recur = ContributionRecur::get(FALSE) - ->addWhere('processor_id', '=', $subscriptionId) - ->addWhere('is_test', 'IN', [TRUE, FALSE]) - ->execute() - ->first(); - - if (!$recur) { - CRM_Core_Payment_SquareDebugLogger::log("Square IPN: invoice.created — no recur found 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 ? (((float) $money['amount']) / 100) : 0.0; - $currency = $money['currency'] ?? $recur['currency'] ?? 'USD'; - $orderID = $invoice['order_id'] ?? NULL; - 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) - // Pending. - ->addValue('contribution_status_id', 2) - ->addValue('invoice_id', $invoiceId) - ->addValue('invoice_number', $orderID) - ->addValue('is_test', $recur['is_test']) - ->addValue('source', 'Square Invoice (Webhook)') - ->execute(); - - CRM_Core_Payment_SquareDebugLogger::log("Square IPN: Created Pending contribution for invoice {$invoiceId}."); - } - - /** - * Handle invoice.payment_failed — mark existing contribution as Failed or create a new Failed one. - * - * @param array $invoice - * Invoice object from Square webhook payload. - */ - protected function handleInvoicePaymentFailed(array $invoice): void { - $invoiceId = $invoice['id'] ?? NULL; - $subscriptionId = $invoice['subscription_id'] ?? NULL; - - if (!$invoiceId) { - CRM_Core_Payment_SquareDebugLogger::log('Square IPN: invoice.payment_failed missing invoice ID.'); - return; - } - - // If a contribution already exists for this invoice, mark it Failed. - $contribution = Contribution::get(FALSE) - ->addSelect('id') - ->addWhere('invoice_id', '=', $invoiceId) - ->execute() - ->first(); - - if (!empty($contribution)) { - Contribution::update(FALSE) - ->addWhere('id', '=', $contribution['id']) - // Failed. - ->addValue('contribution_status_id', 4) - ->execute(); - CRM_Core_Payment_SquareDebugLogger::log("Square IPN: Marked contribution {$contribution['id']} as Failed for invoice {$invoiceId}."); - return; - } - - // No existing contribution — create a Failed one from the recurring record. - if (!$subscriptionId) { - CRM_Core_Payment_SquareDebugLogger::log("Square IPN: invoice.payment_failed — no contribution and no subscription_id for invoice {$invoiceId}."); - return; - } - - $recur = ContributionRecur::get(FALSE) - ->addWhere('processor_id', '=', $subscriptionId) - ->addWhere('is_test', 'IN', [TRUE, FALSE]) - ->addSelect('id', 'contact_id', 'financial_type_id', 'currency') - ->execute() - ->first(); - - if (!$recur) { - CRM_Core_Payment_SquareDebugLogger::log("Square IPN: invoice.payment_failed — no recur for subscription {$subscriptionId}."); - return; - } - - $money = $invoice['payment_requests'][0]['computed_amount_money'] ?? NULL; - $amount = $money ? (((float) $money['amount']) / 100) : 0.0; - $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) - // Failed. - ->addValue('contribution_status_id', 4) - ->addValue('invoice_id', $invoiceId) - ->addValue('source', 'Square Invoice Failed (Webhook)') - ->execute(); - - CRM_Core_Payment_SquareDebugLogger::log("Square IPN: Created Failed contribution for invoice {$invoiceId}."); - } - /** * Set the raw IPN data. * 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 new file mode 100644 index 00000000..cc44a316 --- /dev/null +++ b/CRM/Square/Customers.php @@ -0,0 +1,537 @@ +gateway = $gateway; + } + + /** + * Update a Square customer's details from CiviCRM payment parameters. + * + * @param string $customerID + * Square customer ID. + * @param array $params + * CiviCRM payment parameters. + * + * @return void + * + * @throws CRM_Core_Exception + */ + public function updateSquareCustomerDetails($customerID, $params) { + $firstName = $params['first_name'] ?? NULL; + $lastName = $params['last_name'] ?? NULL; + $email = $params['email'] ?? $params['email-5'] ?? NULL; + $contactID = $params['contactID'] ?? $params['contact_id'] ?? NULL; + + $requestValues = ['customerId' => $customerID]; + if (!empty($firstName)) { + $requestValues['givenName'] = $firstName; + } + if (!empty($lastName)) { + $requestValues['familyName'] = $lastName; + } + if (!empty($email)) { + $requestValues['emailAddress'] = $email; + } + if (!empty($contactID)) { + $requestValues['referenceId'] = (string) $contactID; + } + + $this->gateway->call(fn (SquareClient $client) => $client->customers->update(new UpdateCustomerRequest($requestValues))); + } + + /** + * Ensure a Square customer exists for this contact, saving any submitted card. + * + * 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, and the card + * token as square_payment_token). + * + * @return string + * Square customer ID. + * + * @throws CRM_Core_Exception + */ + public function ensureSquareCustomer(array $params) { + $contactID = (int) ($params['contactID'] ?? $params['contact_id'] ?? 0); + if (!$contactID) { + throw new CRM_Core_Exception('Missing contactID in params for Square recurring payment.'); + } + + $customerId = $this->getSquareCustomerId($contactID) + ?? $this->adoptSquareCustomer($contactID) + ?? $this->createSquareCustomer($contactID); + CRM_Core_Payment_SquareDebugLogger::log("Square customer for contact {$contactID}: {$customerId}"); + + // 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; + } + + /** + * 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; + } + + /** + * 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]), + ]))); + } + + foreach (array_unique($candidates) as $candidateId) { + $mappedContactId = $this->getMappedContactId($candidateId); + if ($mappedContactId !== NULL && $mappedContactId !== $contactID) { + continue; + } + $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 NULL; + } + + /** + * 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."); + } + + $createResponse = $this->gateway->call(fn (SquareClient $client) => $client->customers->create(new CreateCustomerRequest([ + '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.'); + } + + // 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; + } + + /** + * 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; + } + + /** + * 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, + ]; + } + + /** + * Attach a card to the Square customer using the tokenized card nonce. + * + * @param string $customerId + * Square customer ID. + * @param string $cardNonce + * Token from Web Payments SDK. + * @param array $params + * Payment params: billing address fields, names, email, and + * contributionRecurID. + * @param int|null $contactId + * CiviCRM contact ID (optional, but required to record a PaymentToken). + * + * @return string + * Square card ID. + * + * @throws \CRM_Core_Exception + */ + public function createCardOnFile($customerId, $cardNonce, array $params = [], $contactId = NULL) { + if (empty($cardNonce)) { + throw new CRM_Core_Exception('Missing Square card token for recurring payment.'); + } + + $cardValues = ['customerId' => $customerId]; + $billingAddress = $this->billingAddress($params); + if ($billingAddress) { + $cardValues['billingAddress'] = $billingAddress; + } + + $requestValues = [ + // 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->gateway->idempotencyKey('card', $cardNonce), + 'sourceId' => $cardNonce, + 'card' => new Card($cardValues), + ]; + + // 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)); + } + catch (SquareApiException $e) { + // Keep the friendly message and the gateway's payment-failure type so + // recurring checkout runs CiviCRM's cleanup when the card is declined. + throw $this->gateway->apiError($e, $this->translateSquareCardError($e->getErrors())); + } + catch (SquareException $e) { + throw new CRM_Core_Exception('Square API request failed: ' . $e->getMessage()); + } + + $card = $response->getCard(); + if (empty($card) || empty($card->getId())) { + throw new CRM_Core_Exception('Failed to create card on file with Square.'); + } + + $cardId = $card->getId(); + + // Record this card as a CiviCRM PaymentToken (instead of a custom + // field) so multiple cards per contact are properly distinguished, and + // link it to the recurring contribution it was created for, if any. + if (!empty($contactId)) { + $expiryDate = NULL; + if ($card->getExpYear() && $card->getExpMonth()) { + $expiryDate = date('Y-m-t', mktime(0, 0, 0, (int) $card->getExpMonth(), 1, (int) $card->getExpYear())); + } + + $tokenCreate = PaymentToken::create(FALSE) + ->addValue('contact_id', (int) $contactId) + ->addValue('payment_processor_id', $this->gateway->processorId()) + ->addValue('token', $cardId) + ->addValue('masked_account_number', $card->getLast4()); + if ($expiryDate) { + $tokenCreate->addValue('expiry_date', $expiryDate); + } + if (!empty($params['first_name'])) { + $tokenCreate->addValue('billing_first_name', $params['first_name']); + } + if (!empty($params['last_name'])) { + $tokenCreate->addValue('billing_last_name', $params['last_name']); + } + $email = $params['email'] ?? $params['email-5'] ?? NULL; + if (!empty($email)) { + $tokenCreate->addValue('email', $email); + } + $paymentToken = $tokenCreate->execute()->first(); + + if (!empty($paymentToken['id']) && !empty($params['contributionRecurID'])) { + ContributionRecur::update(FALSE) + ->addWhere('id', '=', (int) $params['contributionRecurID']) + ->addValue('payment_token_id', $paymentToken['id']) + ->execute(); + } + } + + return $cardId; + } + + /** + * 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 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; + }; + + $street = $value('street_address'); + $city = $value('city'); + $postalCode = $value('postal_code'); + if ($street === NULL && $city === NULL && $postalCode === NULL) { + return NULL; + } + + $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)); + } + + /** + * Translate Square card errors to human-friendly messages. + * + * @param \Square\Types\Error[] $errors + * Square card errors. + * + * @return string + */ + protected function translateSquareCardError(array $errors) { + $messages = []; + + foreach ($errors as $err) { + $code = $err->getCode() ?? ''; + switch ($code) { + case 'CARD_DECLINED': + $messages[] = 'Your card was declined. Please use a different card.'; + break; + + case 'GENERIC_DECLINE': + $messages[] = 'The card was declined by the bank.'; + break; + + case 'INVALID_EXPIRATION': + $messages[] = 'The card expiration date is invalid.'; + break; + + case 'CVV_FAILURE': + $messages[] = 'The CVV security code is incorrect.'; + break; + + case 'ADDRESS_VERIFICATION_FAILURE': + $messages[] = 'The billing ZIP/postal code did not match the card.'; + break; + + case 'INSUFFICIENT_FUNDS': + $messages[] = 'The card has insufficient funds.'; + break; + + default: + if (!empty($err->getDetail())) { + $messages[] = $err->getDetail(); + } + else { + $messages[] = 'The card could not be processed.'; + } + break; + } + } + + return implode(' ', $messages); + } + + /** + * Get the Square customer ID stored for a contact and processor. + * + * Live and sandbox accounts use distinct customer records. + * + * @param int $contactId + * + * @return string|null + */ + public function getSquareCustomerId($contactId) { + $contactId = (int) $contactId; + $processorId = $this->gateway->processorId(); + if ($contactId <= 0 || $processorId <= 0) { + return NULL; + } + + $customerId = CRM_Core_DAO::singleValueQuery( + 'SELECT square_customer_id FROM square_customer_map WHERE contact_id = %1 AND payment_processor_id = %2', + [1 => [$contactId, 'Integer'], 2 => [$processorId, 'Integer']] + ); + + 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. + * + * See getSquareCustomerId(). + * + * @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): ?string { + $contactId = (int) $contactId; + $processorId = $this->gateway->processorId(); + if ($contactId <= 0 || $processorId <= 0 || empty($customerId)) { + return NULL; + } + + // An existing mapping is never re-pointed (e.g. by two concurrent + // checkouts for the same contact): the insert is a no-op if the contact + // already has a customer, or the customer already has a contact + // (square_customer_map's two unique keys), and the conflict is logged. + CRM_Core_DAO::executeQuery( + 'INSERT INTO square_customer_map (contact_id, payment_processor_id, square_customer_id) + VALUES (%1, %2, %3) + ON DUPLICATE KEY UPDATE square_customer_id = square_customer_id', + [1 => [$contactId, 'Integer'], 2 => [$processorId, 'Integer'], 3 => [$customerId, 'String']] + ); + $mappedCustomerId = $this->getSquareCustomerId($contactId); + if ($mappedCustomerId === NULL) { + 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('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 new file mode 100644 index 00000000..26868ae7 --- /dev/null +++ b/CRM/Square/Gateway.php @@ -0,0 +1,206 @@ +paymentProcessor = $paymentProcessor; + $this->clientFactory = $clientFactory ?? fn () => $this->createClient(); + } + + /** + * ID of this payment processor (civicrm_payment_processor.id). + */ + public function processorId(): int { + return (int) ($this->paymentProcessor['id'] ?? 0); + } + + /** + * Whether this processor is in test/sandbox mode. + */ + public function isTestMode(): bool { + return !empty($this->paymentProcessor['is_test']); + } + + /** + * The Square SDK client for this processor. + */ + public function client(): SquareClient { + return ($this->clientFactory)(); + } + + /** + * Build a Square SDK client from this processor's credentials. + * + * @return \Square\SquareClient + */ + public function createClient(): SquareClient { + return new SquareClient( + token: $this->getAccessToken(), + options: ['baseUrl' => $this->getApiBaseUrl()], + ); + } + + /** + * Get the Square Location ID from processor config. + * + * @return string + * + * @throws \CRM_Core_Exception + */ + public function getLocationId(): string { + $loc = trim($this->paymentProcessor['signature'] ?? ''); + if (empty($loc)) { + throw new CRM_Core_Exception('Square location ID is not configured on this payment processor.'); + } + return $loc; + } + + /** + * Get the Square access token from processor config. + * + * @return string + * + * @throws \CRM_Core_Exception + */ + protected function getAccessToken() { + + return trim($this->paymentProcessor['password'] ?? ''); + } + + /** + * Base URL for Square API, depending on mode and config. + * + * @return string + */ + protected function getApiBaseUrl() { + // Allow overriding via processor config if provided. + if (!empty($this->paymentProcessor['url_api'])) { + return rtrim($this->paymentProcessor['url_api'], '/'); + } + + // Fallback: use sensible defaults based on test/live. + if ($this->isTestMode()) { + return 'https://connect.squareupsandbox.com'; + } + + return 'https://connect.squareup.com'; + } + + /** + * Build a retry-stable idempotency key unique to each processor and environment. + */ + public function idempotencyKey(string $operation, string $reference): string { + $processorId = (string) ($this->paymentProcessor['id'] ?? '0'); + $environment = $this->isTestMode() ? 'test' : 'live'; + return substr('civi-' . $operation . '-' . hash('sha256', implode(':', [ + $processorId, + $environment, + $reference, + ])), 0, 45); + } + + /** + * Invoke the Square SDK client and translate its exceptions to CRM_Core_Exception. + * + * @param callable(\Square\SquareClient): mixed $call + * + * @return mixed + * Whatever $call returns (typically a Square SDK response object). + * + * @throws \CRM_Core_Exception + */ + public function call(callable $call) { + try { + return $call($this->client()); + } + catch (SquareApiException $e) { + throw $this->apiError($e); + } + catch (SquareException $e) { + // 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); + } + } + + /** + * 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. Payment-method rejections use + * PaymentProcessorException so CiviCRM checkout runs its failed-payment + * cleanup. Other failures do not establish that a payment was declined. + * + * @param \Square\Exceptions\SquareApiException $e + * @param string|null $message + * Optional user-facing message, e.g. for a card-on-file rejection. + * + * @return \CRM_Core_Exception + */ + public function apiError(SquareApiException $e, ?string $message = NULL): CRM_Core_Exception { + $errorDetails = []; + $isPaymentMethodError = FALSE; + foreach ($e->getErrors() as $err) { + $isPaymentMethodError = $isPaymentMethodError || $err->getCategory() === 'PAYMENT_METHOD_ERROR'; + $code = $err->getCode() ?: 'UNKNOWN'; + $detail = $err->getDetail() ?? ''; + $errorDetails[] = "{$code}: {$detail}"; + } + $statusCode = $e->getStatusCode(); + $msg = "Square API returned HTTP {$statusCode}."; + if ($errorDetails) { + $msg .= ' ' . implode(' | ', $errorDetails); + } + if ($statusCode >= 500 || $statusCode === 429) { + $exceptionClass = CRM_Core_Payment_SquareRetryableException::class; + } + elseif ($statusCode >= 400 && $isPaymentMethodError) { + $exceptionClass = PaymentProcessorException::class; + } + else { + $exceptionClass = CRM_Core_Exception::class; + } + return new $exceptionClass($message ?? $msg, 0, [], $e); + } + +} diff --git a/CRM/Square/Reconciler.php b/CRM/Square/Reconciler.php new file mode 100644 index 00000000..aabbd697 --- /dev/null +++ b/CRM/Square/Reconciler.php @@ -0,0 +1,1749 @@ +gateway = $gateway; + } + + /** + * How long, in seconds, after Square created a payment or invoice its webhook may be deferred. + * + * Webhooks routinely arrive before the request that caused them has + * finished saving: Square charges a new subscription's first invoice + * within seconds of doRecurPayment() creating it, and a one-time payment's + * webhook can beat CiviCRM's own checkout to recording it. While an event + * is younger than this, "the matching CiviCRM record is not there yet" is + * treated as a retryable race rather than a reason to create a new + * contribution. Well past this age the race is over, so the event is + * handled on its own merits. + */ + 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. + * + * In order: + * 1. Already recorded as a payment by this processor: nothing to do. + * 2. A one-time payment CiviCRM itself initiated: matched by trxn_id, or + * by invoice_id == reference_id (doOneTimePayment() sends CiviCRM's + * invoiceID as Square's reference_id), and reconciled. + * 3. A Square subscription installment. Square's payment carries neither + * subscription_id nor reference_id — only order_id — so the invoice + * that owns that order is looked up at Square, and the installment is + * recorded against the subscription's recurring contribution exactly + * as for invoice.payment_made (see recordSubscriptionInstallment()). + * 4. Anything else is a payment taken outside CiviCRM, imported as a new + * contribution — unless it may still turn out to be one of the above + * whose CiviCRM records are not visible yet, in which case it is + * retried rather than imported as a duplicate. + * + * @param array $payment + * Payment object from Square webhooks. + * + * @throws \CRM_Core_Exception + */ + public function syncPaymentFromSquare(array $payment) { + $paymentId = $payment['id'] ?? NULL; + $status = strtoupper((string) ($payment['status'] ?? 'UNKNOWN')); + CRM_Core_Payment_SquareDebugLogger::log("Square syncPaymentFromSquare(): called from SquareIPN for payment_id={$paymentId}, status={$status}, order_id=" . ($payment['order_id'] ?? 'null')); + if (!$paymentId) { + CRM_Core_Payment_SquareDebugLogger::log('Square syncPaymentFromSquare(): missing payment ID, skipping.'); + return; + } + + $lock = $this->acquireSquareLock('payment.' . $paymentId); + try { + $recorded = $this->findRecordedPayment($paymentId); + if ($recorded) { + CRM_Core_Payment_SquareDebugLogger::log("Square syncPaymentFromSquare(): payment {$paymentId} is already recorded."); + $this->recordProcessingFee($recorded, $payment); + return; + } + + $existing = $this->findContributionForSquarePayment($paymentId, $payment['reference_id'] ?? NULL); + if ($existing) { + $this->reconcileExistingContributionPayment($existing, $payment); + return; + } + + if ($status !== 'COMPLETED') { + CRM_Core_Payment_SquareDebugLogger::log("Square syncPaymentFromSquare(): payment {$paymentId} matches no contribution and is {$status}; nothing is recorded until Square reports it COMPLETED."); + return; + } + + $invoice = $this->findInvoiceForPayment($payment); + if (!empty($invoice['subscription_id'])) { + $recur = $this->findOrLinkRecur($invoice['subscription_id']); + if (!$recur) { + $this->handleUnknownSubscription($invoice['subscription_id'], $payment['created_at'] ?? NULL, "payment {$paymentId}"); + return; + } + $this->recordSubscriptionInstallment($recur, $this->installmentFromPayment($payment, $invoice)); + return; + } + + if (!$invoice && $this->mayBeAwaitingCiviRecord($payment)) { + throw new CRM_Core_Payment_SquareRetryableException("Square payment {$paymentId} matches no CiviCRM contribution or Square subscription invoice yet; retrying in case it belongs to a checkout or subscription that is still being saved."); + } + + $this->createContributionFromSquarePayment($payment); + } + finally { + $lock->release(); + } + } + + /** + * Record Square's processing fee for an already-recorded payment, if not yet known. + * + * 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. 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(). + * @param array $payment + * Payment object from Square webhooks. + * + * @throws \CRM_Core_Exception + */ + protected function recordProcessingFee(array $recorded, array $payment): void { + $fee = $this->sumProcessingFees($payment['processing_fee'] ?? []); + if (empty($fee) || empty($recorded['contribution_id'])) { + return; + } + $contributionId = (int) $recorded['contribution_id']; + 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']}."); + } + + /** + * Whether an unmatched payment may belong to a CiviCRM record not visible yet. + * + * A reference_id is only ever sent by CiviCRM's own checkout (see + * doOneTimePayment()), and a card-on-file charge for a Square customer is + * how Square bills subscription invoices. Either, while still recent, + * means "not found" is more likely a race than an external payment. + * + * @param array $payment + * + * @return bool + */ + protected function mayBeAwaitingCiviRecord(array $payment): bool { + if (!$this->isWithinWebhookGrace($payment['created_at'] ?? NULL)) { + return FALSE; + } + $isCardOnFileCharge = !empty($payment['customer_id']) + && strtoupper((string) ($payment['card_details']['entry_method'] ?? '')) === 'ON_FILE'; + return !empty($payment['reference_id']) || $isCardOnFileCharge; + } + + /** + * Reconcile a Square payment against an existing one-time contribution. + * + * Amount/currency mismatches are never silently corrected — they are + * raised 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, as returned by findContributionForSquarePayment(). + * @param array $payment + * Payment object from Square webhooks. + * + * @throws \CRM_Core_Exception + */ + protected function reconcileExistingContributionPayment(array $existing, array $payment): void { + $contributionId = (int) $existing['id']; + $paymentId = (string) $payment['id']; + $status = strtoupper((string) ($payment['status'] ?? 'UNKNOWN')); + + if ($existing['status'] === 'Completed') { + CRM_Core_Payment_SquareDebugLogger::log("Square syncPaymentFromSquare(): contribution {$contributionId} already Completed for payment {$paymentId}, skipping."); + return; + } + if ($existing['status'] === 'Pending' && CRM_Square_Status::mapPaymentStatus($status) === CRM_Square_Status::contributionStatusId('Failed')) { + $this->updateContribution($contributionId, ['contribution_status_id' => CRM_Square_Status::contributionStatusId('Failed')]); + CRM_Core_Payment_SquareDebugLogger::log("Square syncPaymentFromSquare(): payment {$paymentId} is {$status}; marked contribution {$contributionId} Failed."); + return; + } + if ($status !== 'COMPLETED') { + CRM_Core_Payment_SquareDebugLogger::log("Square syncPaymentFromSquare(): payment {$paymentId} status '{$status}' does not indicate completion, leaving contribution {$contributionId} unchanged."); + return; + } + + // Matched only by invoice_id means the checkout has not saved this + // payment's trxn_id yet: it is normally about to record the payment + // itself, and recording it here too would be a second payment on the + // same contribution. Leave it to the checkout unless it never does. + $claimedByPayment = in_array($paymentId, explode(',', (string) ($existing['trxn_id'] ?? '')), TRUE); + if (!$claimedByPayment && $this->isWithinWebhookGrace($payment['created_at'] ?? NULL)) { + throw new CRM_Core_Payment_SquareRetryableException("Contribution {$contributionId} is still Pending while CiviCRM's checkout records Square payment {$paymentId}; retrying later."); + } + + $this->assertAmountMatches((float) $existing['total_amount'], (string) $existing['currency'], $this->installmentFromPayment($payment, []), "contribution {$contributionId}"); + $this->recordContributionPayment($contributionId, [ + 'total_amount' => (float) $existing['total_amount'], + 'trxn_id' => $paymentId, + 'trxn_date' => $this->squareTimestampToCivi($payment['created_at'] ?? NULL), + 'payment_instrument_id' => CRM_Square_Status::mapPaymentInstrument($payment['source_type'] ?? NULL), + 'fee_amount' => $this->sumProcessingFees($payment['processing_fee'] ?? []), + ], FALSE); + CRM_Core_Payment_SquareDebugLogger::log("Square syncPaymentFromSquare(): completed contribution {$contributionId} for payment {$paymentId} via Payment.create."); + } + + /** + * 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. + * + * @throws \CRM_Core_Exception + */ + 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 + // billed its own first installment used the recurring contribution ID + // as their reference_id. + $contactId = NULL; + $refRecurContribution = NULL; + if ($referenceId && ctype_digit((string) $referenceId)) { + $refRecurContribution = ContributionRecur::get(FALSE) + ->addSelect('id', 'contact_id', 'financial_type_id') + ->addWhere('id', '=', (int) $referenceId) + ->addWhere('payment_processor_id', '=', $this->gateway->processorId()) + ->addWhere('is_test', '=', $this->gateway->isTestMode()) + ->execute() + ->first(); + if ($refRecurContribution) { + $contactId = (int) $refRecurContribution['contact_id']; + } + } + + if (!$contactId) { + $contactId = $this->findContactIdForPayment($payment); + } + + if (!$contactId) { + CRM_Core_Payment_SquareDebugLogger::log("Square syncPaymentFromSquare(): cannot resolve contact for payment {$paymentId}, skipping create."); + return; + } + + // No better mapping available (no recur template) — fall back to the + // 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']) ? 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 + // populated correctly — never write a "Completed" status directly onto + // the contribution row. + $values = [ + 'contact_id' => $contactId, + 'financial_type_id' => $financialTypeId, + 'total_amount' => $amount, + 'currency' => $money['currency'] ?? 'USD', + 'contribution_status_id' => CRM_Square_Status::contributionStatusId('Pending'), + 'trxn_id' => $paymentId, + 'is_test' => $this->gateway->isTestMode(), + 'source' => 'Square Payment (Webhook)', + ]; + if ($orderID !== NULL) { + $values['invoice_number'] = $orderID; + } + $newContributionId = $this->createContribution($values); + + $this->recordContributionPayment($newContributionId, [ + 'total_amount' => $amount, + 'trxn_id' => $paymentId, + 'trxn_date' => $this->squareTimestampToCivi($payment['created_at'] ?? NULL), + 'payment_instrument_id' => CRM_Square_Status::mapPaymentInstrument($payment['source_type'] ?? NULL), + 'fee_amount' => $this->sumProcessingFees($payment['processing_fee'] ?? []), + ], FALSE); + CRM_Core_Payment_SquareDebugLogger::log("Square syncPaymentFromSquare(): Created and completed contribution {$newContributionId} for payment {$paymentId}, contact {$contactId}."); + } + + /** + * Find the Square invoice a payment paid, if any. + * + * Square payment objects do not reference the invoice (or subscription) + * they pay, only the invoice's order. Square's order does not reference + * its invoice either, so the customer's invoices at the payment's + * location are searched, newest first, for the one owning that order. + * + * @param array $payment + * Payment object from Square webhooks. + * + * @return array|null + * The invoice (REST JSON shape), or NULL if the payment paid no invoice. + * + * @throws \CRM_Core_Exception + */ + protected function findInvoiceForPayment(array $payment): ?array { + $orderId = $payment['order_id'] ?? NULL; + $customerId = $payment['customer_id'] ?? NULL; + if (empty($orderId) || empty($customerId)) { + // Subscription invoices are always billed to a Square customer. + return NULL; + } + $locationId = $payment['location_id'] ?? $this->gateway->getLocationId(); + + $cursor = NULL; + // A subscription's invoice is created moments before Square charges it, + // so it is among the customer's newest; stop after a few pages. + for ($page = 0; $page < 3; $page++) { + $request = new SearchInvoicesRequest([ + 'query' => new InvoiceQuery([ + 'filter' => new InvoiceFilter([ + 'locationIds' => [$locationId], + 'customerIds' => [$customerId], + ]), + 'sort' => new InvoiceSort(['field' => 'INVOICE_SORT_DATE', 'order' => 'DESC']), + ]), + 'limit' => 100, + 'cursor' => $cursor, + ]); + $response = $this->gateway->call(fn (SquareClient $client) => $client->invoices->search($request)); + foreach ($response->getInvoices() ?? [] as $invoice) { + if ($invoice->getOrderId() === $orderId) { + return $invoice->jsonSerialize(); + } + } + $cursor = $response->getCursor(); + if (empty($cursor)) { + break; + } + } + return NULL; + } + + /** + * Describe a paid Square payment as a subscription installment. + * + * @param array $payment + * Payment object from Square webhooks. + * @param array $invoice + * The Square invoice it paid, if known. + * + * @return array + * See recordSubscriptionInstallment(). + */ + protected function installmentFromPayment(array $payment, array $invoice): array { + $money = $payment['amount_money'] ?? []; + return [ + 'payment_id' => (string) $payment['id'], + 'invoice_id' => $invoice['id'] ?? 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), + 'payment_instrument_id' => CRM_Square_Status::mapPaymentInstrument($payment['source_type'] ?? NULL), + ]; + } + + /** + * Describe a paid Square subscription invoice as an installment. + * + * The invoice does not carry the ID of the payment that paid it, so it is + * read from the tender on the invoice's order — never invented, since the + * Square payment ID is what every later event (payment.updated, + * refund.*) identifies the payment by. + * + * @param array $invoice + * Invoice object from Square webhooks. + * + * @return array + * See recordSubscriptionInstallment(). + * + * @throws \CRM_Core_Exception + */ + protected function installmentFromInvoice(array $invoice): array { + $invoiceId = $invoice['id']; + $orderId = $invoice['order_id'] ?? NULL; + if (empty($orderId)) { + throw new CRM_Core_Exception("Square invoice {$invoiceId} has no order_id, so the payment that paid it cannot be identified."); + } + + $tenders = array_values(array_filter( + $this->getSquareOrderTenders($orderId), + fn (array $tender) => !empty($tender['payment_id']) + )); + if (!$tenders) { + throw new CRM_Core_Payment_SquareRetryableException("Square order {$orderId} of paid invoice {$invoiceId} does not show its payment yet."); + } + if (count($tenders) > 1) { + $message = "Square invoice {$invoiceId} was paid with " . count($tenders) . ' separate payments; recording split payments is not supported and needs manual reconciliation.'; + Civi::log()->error('Square: ' . $message); + throw new CRM_Core_Exception($message); + } + + $tender = $tenders[0]; + $money = $tender['amount_money'] ?? []; + return [ + 'payment_id' => (string) $tender['payment_id'], + 'invoice_id' => $invoiceId, + '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']) ? 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), + ]; + } + + /** + * Fetch the tenders (payments) recorded on a Square order. + * + * @param string $orderId + * + * @return array + * Tenders in REST JSON shape. + * + * @throws \CRM_Core_Exception + */ + protected function getSquareOrderTenders(string $orderId): array { + $order = $this->gateway->call(fn (SquareClient $client) => $client->orders->get( + new GetOrdersRequest(['orderId' => $orderId]) + ))->getOrder(); + if (empty($order)) { + throw new CRM_Core_Payment_SquareRetryableException("Square order {$orderId} was not found."); + } + return $order->jsonSerialize()['tenders'] ?? []; + } + + /** + * Record a subscription installment that Square has confirmed as paid. + * + * The first installment completes the Pending contribution CiviCRM created + * at checkout (see findSignupContribution()); later installments are + * cloned from the series with Contribution.repeattransaction. Either way + * the payment itself is recorded with Payment.create, never by writing a + * status onto the contribution. + * + * The Square payment ID is the idempotency key: it becomes both the + * contribution's trxn_id (unique in civicrm_contribution) and the + * payment's trxn_id, so a replayed or concurrent webhook for the same + * payment — whether it arrives as invoice.payment_made or payment.updated + * — records nothing further. Installments of one series are recorded + * one at a time (under a lock on the series), so two payments can never + * both claim the checkout's contribution. + * + * @param array $recur + * Recurring contribution, as returned by findRecurBySubscriptionId(). + * @param array $installment + * The payment: payment_id, invoice_id (Square invoice, if known), + * amount, currency, fee_amount, trxn_date, payment_instrument_id. + * + * @throws \CRM_Core_Exception + */ + protected function recordSubscriptionInstallment(array $recur, array $installment): void { + $lock = $this->acquireSquareLock('recur.' . $recur['id']); + try { + $this->recordSubscriptionInstallmentLocked($recur, $installment); + } + finally { + $lock->release(); + } + } + + /** + * Body of recordSubscriptionInstallment(), run under its lock. + * + * @param array $recur + * @param array $installment + * + * @throws \CRM_Core_Exception + */ + private function recordSubscriptionInstallmentLocked(array $recur, array $installment): void { + $paymentId = $installment['payment_id']; + $recurId = (int) $recur['id']; + + if ($this->findRecordedPayment($paymentId)) { + CRM_Core_Payment_SquareDebugLogger::log("Square recordSubscriptionInstallment(): payment {$paymentId} is already recorded, nothing to do."); + return; + } + + $contributions = $this->getRecurContributions($recurId); + $contribution = $this->findInstallmentContribution($contributions, $recur, $installment); + + if ($contribution === NULL) { + // A second or later installment: nothing in CiviCRM represents it yet. + $this->assertAmountMatches((float) $recur['amount'], (string) $recur['currency'], $installment, "recurring contribution {$recurId}"); + $contribution = $this->repeatRecurContribution($recur, [ + 'contribution_status' => 'Pending', + 'trxn_id' => $paymentId, + 'invoice_id' => $installment['invoice_id'], + 'receive_date' => $installment['trxn_date'], + ]); + CRM_Core_Payment_SquareDebugLogger::log("Square recordSubscriptionInstallment(): created contribution {$contribution['id']} for payment {$paymentId} of recurring contribution {$recurId}."); + } + elseif ($contribution['status'] === 'Failed') { + // Square collected an installment whose earlier attempt failed: + // reopen that contribution (CiviCRM allows Failed -> Pending) rather + // than record the payment on another one. + $this->updateContribution((int) $contribution['id'], ['contribution_status_id' => CRM_Square_Status::contributionStatusId('Pending')]); + $contribution['status'] = 'Pending'; + } + elseif ($contribution['status'] === 'Completed') { + CRM_Core_Payment_SquareDebugLogger::log("Square recordSubscriptionInstallment(): contribution {$contribution['id']} for payment {$paymentId} is already Completed, nothing to do."); + return; + } + elseif ($contribution['status'] !== 'Pending') { + $message = "Contribution {$contribution['id']} for Square payment {$paymentId} is {$contribution['status']}; the payment was not recorded and needs manual reconciliation."; + Civi::log()->error('Square: ' . $message); + throw new CRM_Core_Exception($message); + } + + $this->assertAmountMatches((float) $contribution['total_amount'], (string) $contribution['currency'], $installment, "contribution {$contribution['id']}"); + + // Claim the contribution for this payment before recording it. Payment + // .create appends its trxn_id to the contribution's rather than + // replacing it, and the unique trxn_id also stops any other contribution + // being created for the same payment. + if (($contribution['trxn_id'] ?? '') !== $paymentId) { + $this->updateContribution((int) $contribution['id'], ['trxn_id' => $paymentId]); + } + + // The checkout's contribution (always the series' oldest) is receipted + // once: not if the checkout already sent a receipt (webform_civicrm does, + // which sets receipt_date), otherwise as the recurring contribution's + // receipt setting says — as CiviCRM does when a contribution page + // completes the first payment itself. Later installments are not + // receipted, as before. + $isCheckoutContribution = !empty($contributions) && (int) $contribution['id'] === (int) $contributions[0]['id']; + $sendReceipt = $isCheckoutContribution && !empty($recur['is_email_receipt']) && empty($contribution['receipt_date']); + + // Payment.create completes the contribution (preserving its line items + // and financial allocations) and moves the recurring contribution from + // Pending to In Progress via updateOnNewPayment(). + $this->recordContributionPayment((int) $contribution['id'], [ + 'total_amount' => (float) $contribution['total_amount'], + 'trxn_id' => $paymentId, + 'trxn_date' => $installment['trxn_date'], + 'payment_instrument_id' => $installment['payment_instrument_id'], + 'fee_amount' => $installment['fee_amount'], + ], $sendReceipt); + CRM_Core_Payment_SquareDebugLogger::log("Square recordSubscriptionInstallment(): recorded payment {$paymentId} on contribution {$contribution['id']} of recurring contribution {$recurId}."); + } + + /** + * Find the contribution a subscription installment belongs to, if one exists. + * + * @param array $contributions + * The series' contributions, as returned by getRecurContributions(). + * @param array $recur + * Recurring contribution, as returned by findRecurBySubscriptionId(). + * @param array $installment + * See recordSubscriptionInstallment(). + * + * @return array|null + * NULL when the installment needs a new contribution. + */ + protected function findInstallmentContribution(array $contributions, array $recur, array $installment): ?array { + // Already claimed by this payment (e.g. a retry after a failure between + // claiming and recording it). + foreach ($contributions as $contribution) { + if (in_array($installment['payment_id'], explode(',', (string) ($contribution['trxn_id'] ?? '')), TRUE)) { + return $contribution; + } + } + // 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']) { + return $contribution; + } + } + } + return $this->findSignupContribution($contributions, $recur); + } + + /** + * The Pending contribution CiviCRM created at checkout, while the first installment is unpaid. + * + * CiviCRM's checkout (contribution page or webform_civicrm) creates the + * series' first contribution itself, Pending, before doRecurPayment() + * creates the Square subscription — and Square then bills that first + * installment as the subscription's first invoice. That invoice must + * complete this contribution, not a new one. + * + * It can only be the first installment while nothing in the series has + * been paid, and only if the contribution is not already claimed by a + * different Square payment: its trxn_id is empty, or is the subscription + * ID that versions of doRecurPayment() before this fix returned as the + * checkout's trxn_id. + * + * @param array $contributions + * The series' contributions, oldest first, as returned by + * getRecurContributions(). + * @param array $recur + * Recurring contribution, as returned by findRecurBySubscriptionId(). + * + * @return array|null + */ + protected function findSignupContribution(array $contributions, array $recur): ?array { + foreach ($contributions as $contribution) { + if (!in_array($contribution['status'], ['Pending', 'Failed', 'Cancelled'], TRUE)) { + return NULL; + } + } + foreach ($contributions as $contribution) { + $trxnId = (string) ($contribution['trxn_id'] ?? ''); + if ($contribution['status'] === 'Pending' && ($trxnId === '' || $trxnId === (string) $recur['processor_id'])) { + return $contribution; + } + } + return NULL; + } + + /** + * Refuse to record a payment whose amount or currency differs from CiviCRM's. + * + * CiviCRM's amount (and the line items and financial allocations behind + * it) is never rewritten to match what Square reports. + * + * @param float $expectedAmount + * @param string $expectedCurrency + * @param array $installment + * See recordSubscriptionInstallment(). + * @param string $expectedBy + * What $expectedAmount belongs to, for the error message. + * + * @throws \CRM_Core_Exception + */ + protected function assertAmountMatches(float $expectedAmount, string $expectedCurrency, array $installment, string $expectedBy): void { + $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( + 'Square payment %s was for %s %s but CiviCRM %s is for %0.2f %s; the payment was not recorded and needs manual reconciliation.', + $installment['payment_id'], + $installment['amount'] === NULL ? 'an unknown amount' : sprintf('%0.2f', $installment['amount']), + $installment['currency'] ?? '', + $expectedBy, + $expectedAmount, + $expectedCurrency + ); + Civi::log()->error('Square: ' . $message); + throw new CRM_Core_Exception($message); + } + + /** + * Handle an event for a Square subscription no recurring contribution here is linked to. + * + * Square bills a new subscription's first invoice within seconds of + * doRecurPayment() creating it — possibly before the checkout has saved + * the subscription ID on the recurring contribution — so a recent event + * is retried. An older one belongs to a subscription this processor does + * not manage (e.g. one created in the Square Dashboard) and is ignored. + * + * @param string $subscriptionId + * @param string|null $createdAt + * When Square created the payment or invoice (ISO 8601). + * @param string $context + * What the event is about, for messages. + * + * @throws \CRM_Core_Payment_SquareRetryableException + */ + protected function handleUnknownSubscription(string $subscriptionId, ?string $createdAt, string $context): void { + if ($this->isWithinWebhookGrace($createdAt)) { + throw new CRM_Core_Payment_SquareRetryableException("No recurring contribution on payment processor {$this->gateway->processorId()} is linked to Square subscription {$subscriptionId} ({$context}) yet; retrying in case checkout is still saving it."); + } + CRM_Core_Payment_SquareDebugLogger::log("Square: subscription {$subscriptionId} ({$context}) is not linked to a recurring contribution on payment processor {$this->gateway->processorId()}; ignoring."); + } + + /** + * Whether a Square timestamp is recent enough that its webhook may be deferred. + * + * @param string|null $createdAt + * ISO 8601 timestamp from Square. + * + * @return bool + */ + protected function isWithinWebhookGrace(?string $createdAt): bool { + $created = empty($createdAt) ? FALSE : strtotime($createdAt); + return $created !== FALSE && (time() - $created) < self::WEBHOOK_GRACE_SECONDS; + } + + /** + * Convert a Square ISO 8601 timestamp to a CiviCRM (site-local) datetime. + * + * @param string|null $timestamp + * + * @return string + */ + protected function squareTimestampToCivi(?string $timestamp): string { + $time = empty($timestamp) ? FALSE : strtotime($timestamp); + return date('Y-m-d H:i:s', $time === FALSE ? time() : $time); + } + + /** + * Total a Square payment's processing fees, in major currency units. + * + * @param array $processingFees + * The payment's processing_fee list. + * + * @return float|null + * NULL when Square has not reported any fee yet. + */ + protected function sumProcessingFees(array $processingFees): ?float { + $minorUnits = NULL; + $currency = NULL; + foreach ($processingFees as $fee) { + if (isset($fee['amount_money']['amount'])) { + $minorUnits = ($minorUnits ?? 0) + (int) $fee['amount_money']['amount']; + $currency = $currency ?? ($fee['amount_money']['currency'] ?? NULL); + } + } + return $minorUnits === NULL ? NULL : CRM_Square_Currency::fromMinorUnits($minorUnits, $currency); + } + + /** + * Take a lock that serializes webhook processing for one object. + * + * Square delivers invoice.payment_made and payment.updated for the same + * installment almost simultaneously, processed in separate requests. + * Locks are always taken in the order payment, then recur, so they + * cannot deadlock. + * + * @param string $key + * E.g. 'payment.' . $squarePaymentId, 'recur.' . $recurId. + * + * @return \CRM_Core_Lock + * Must be released by the caller. + * + * @throws \CRM_Core_Payment_SquareRetryableException + */ + protected function acquireSquareLock(string $key) { + $lock = new CRM_Core_Lock("worker.square.{$this->gateway->processorId()}.{$key}", 30); + if (!$lock->acquire()) { + throw new CRM_Core_Payment_SquareRetryableException("Another request is still processing Square {$key}."); + } + return $lock; + } + + /** + * Find the recurring contribution linked to a Square subscription on this processor. + * + * Scoped to this payment processor (and so to its live/test mode): a + * webhook for one Square processor never touches another's records. + * + * @param string $subscriptionId + * + * @return array|null + */ + protected function findRecurBySubscriptionId(string $subscriptionId): ?array { + return ContributionRecur::get(FALSE) + ->addSelect('id', 'contact_id', 'amount', 'currency', 'processor_id', 'contribution_status_id', 'is_email_receipt', 'is_test') + ->addWhere('processor_id', '=', $subscriptionId) + ->addWhere('payment_processor_id', '=', $this->gateway->processorId()) + ->addWhere('is_test', '=', $this->gateway->isTestMode()) + ->execute() + ->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. + * + * @param int $recurId + * + * @return array + * Rows as returned by normalizeContribution(). + */ + protected function getRecurContributions(int $recurId): array { + $contributions = []; + $rows = Contribution::get(FALSE) + ->addSelect('id', 'contribution_status_id:name', 'total_amount', 'currency', 'trxn_id', 'invoice_id', 'receipt_date') + ->addWhere('contribution_recur_id', '=', $recurId) + ->addWhere('is_test', '=', $this->gateway->isTestMode()) + ->addWhere('is_template', '=', FALSE) + ->addOrderBy('id', 'ASC') + ->execute(); + foreach ($rows as $row) { + $contributions[] = $this->normalizeContribution($row); + } + return $contributions; + } + + /** + * Find a one-time contribution for a Square payment. + * + * @param string $paymentId + * Square payment ID, matched against trxn_id. + * @param string|null $referenceId + * Square reference_id, matched against invoice_id (see doOneTimePayment()). + * + * @return array|null + * As returned by normalizeContribution(). + */ + protected function findContributionForSquarePayment(string $paymentId, ?string $referenceId): ?array { + $query = Contribution::get(FALSE) + ->addSelect('id', 'contribution_status_id:name', 'total_amount', 'currency', 'trxn_id', 'invoice_id', 'receipt_date') + ->addWhere('is_test', '=', $this->gateway->isTestMode()) + // Installments of a recurring series are reconciled by + // recordSubscriptionInstallment() instead. + ->addWhere('contribution_recur_id', 'IS EMPTY'); + if ($referenceId !== NULL && $referenceId !== '') { + $query->addClause('OR', ['trxn_id', '=', $paymentId], ['invoice_id', '=', $referenceId]); + } + else { + $query->addWhere('trxn_id', '=', $paymentId); + } + $row = $query->execute()->first(); + return $row ? $this->normalizeContribution($row) : NULL; + } + + /** + * Find a payment this processor has recorded with the given transaction ID. + * + * @param string $trxnId + * Square payment (or refund) ID. + * + * @return array|null + * With 'id' (financial_trxn ID), 'contribution_id' and 'total_amount'. + */ + protected function findRecordedPayment(string $trxnId): ?array { + return Payment::get(FALSE) + ->addSelect('id', 'contribution_id', 'total_amount') + ->addWhere('trxn_id', '=', $trxnId) + ->addWhere('payment_processor_id', '=', $this->gateway->processorId()) + ->execute() + ->first(); + } + + /** + * 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') + ->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(); + return !empty($contribution['id']) ? (int) $contribution['id'] : NULL; + } + + /** + * Find a payment (or refund) recorded on a contribution, by transaction ID. + * + * @param int $contributionId + * @param string $trxnId + * + * @return array|null + * With 'id' (financial_trxn ID), 'total_amount' and + * 'payment_processor_id'. + */ + protected function findContributionPayment(int $contributionId, string $trxnId): ?array { + $payments = civicrm_api3('Payment', 'get', [ + 'entity_id' => $contributionId, + 'trxn_id' => $trxnId, + 'options' => ['limit' => 1, 'sort' => 'id DESC'], + ])['values'] ?? []; + return $payments ? reset($payments) : NULL; + } + + /** + * Record a refund as a negative payment. + * + * @param array $params + * API3 Payment.create params — cancelled_payment_id is only accepted by + * the API3 action; API4 Payment::create does not declare it. + * + * @throws \CRM_Core_Exception + */ + protected function recordRefundPayment(array $params): void { + civicrm_api3('Payment', 'create', $params); + } + + /** + * Record a payment on a contribution via CiviCRM's Payment.create. + * + * This creates the FinancialTrxn/EntityFinancialTrxn ledger rows and, once + * the contribution is paid in full, completes it + * (CRM_Contribute_BAO_Contribution::completeOrder()) as for any other + * payment processor. + * + * @param int $contributionId + * @param array $values + * Keys total_amount, trxn_id, trxn_date, and optionally + * payment_instrument_id and fee_amount. + * @param bool $sendReceipt + * Whether completing the contribution emails the contact a receipt. + * + * @throws \CRM_Core_Exception + */ + protected function recordContributionPayment(int $contributionId, array $values, bool $sendReceipt): void { + $create = Payment::create(FALSE) + // Payment.create would otherwise always send one. + ->setNotificationForCompleteOrder($sendReceipt) + ->addValue('contribution_id', $contributionId) + ->addValue('total_amount', $values['total_amount']) + ->addValue('trxn_id', $values['trxn_id']) + // Payment.create's own 'now' default is not applied. + ->addValue('trxn_date', $values['trxn_date'] ?? date('Y-m-d H:i:s')) + ->addValue('payment_processor_id', $this->gateway->processorId()); + if (!empty($values['payment_instrument_id'])) { + $create->addValue('payment_instrument_id', $values['payment_instrument_id']); + } + if (isset($values['fee_amount'])) { + $create->addValue('fee_amount', $values['fee_amount']); + } + + // API4 actions are never wrapped in a transaction, and Payment.create + // saves the payment before completing the contribution. Without this, a + // failure while completing it would leave a recorded payment on a + // still-Pending contribution — which every retry would then skip as + // "already recorded". + $transaction = new CRM_Core_Transaction(); + try { + $create->execute(); + } + catch (\Throwable $e) { + $transaction->rollback(); + throw $e; + } + $transaction->commit(); + } + + /** + * Create the next contribution of a recurring series. + * + * Uses Contribution.repeattransaction so the new contribution copies the + * series' financial type, line items and financial allocations. + * + * @param array $recur + * Recurring contribution, as returned by findRecurBySubscriptionId(). + * @param array $values + * Keys contribution_status (a status name), and optionally trxn_id, + * invoice_id and receive_date. + * + * @return array + * The new contribution, as returned by normalizeContribution(). + * + * @throws \CRM_Core_Exception + */ + protected function repeatRecurContribution(array $recur, array $values): array { + $params = [ + 'contribution_recur_id' => (int) $recur['id'], + 'contribution_status_id' => $values['contribution_status'], + ]; + foreach (['trxn_id', 'receive_date'] as $field) { + if (!empty($values[$field])) { + $params[$field] = $values[$field]; + } + } + $contributionId = (int) civicrm_api3('Contribution', 'repeattransaction', $params)['id']; + + 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.scheduled_charge_failed) find this contribution. + $this->updateContribution($contributionId, ['invoice_id' => $values['invoice_id']]); + } + + $row = Contribution::get(FALSE) + ->addSelect('id', 'contribution_status_id:name', 'total_amount', 'currency', 'trxn_id', 'invoice_id', 'receipt_date') + ->addWhere('id', '=', $contributionId) + ->addWhere('is_test', 'IN', [TRUE, FALSE]) + ->execute() + ->single(); + return $this->normalizeContribution($row); + } + + /** + * The fee already recorded on a contribution. + * + * @param int $contributionId + * + * @return float + */ + protected function getContributionFeeAmount(int $contributionId): float { + $contribution = Contribution::get(FALSE) + ->addSelect('fee_amount') + ->addWhere('id', '=', $contributionId) + ->addWhere('is_test', 'IN', [TRUE, FALSE]) + ->execute() + ->first(); + return (float) ($contribution['fee_amount'] ?? 0); + } + + /** + * Update fields on a contribution. + * + * @param int $contributionId + * @param array $values + * + * @throws \CRM_Core_Exception + */ + protected function updateContribution(int $contributionId, array $values): void { + Contribution::update(FALSE) + ->addWhere('id', '=', $contributionId) + ->setValues($values) + ->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. + * + * @param array $values + * + * @return int + * The new contribution's ID. + * + * @throws \CRM_Core_Exception + */ + protected function createContribution(array $values): int { + return (int) Contribution::create(FALSE) + ->setValues($values) + ->execute() + ->first()['id']; + } + + /** + * Normalize an API4 contribution row for the reconciliation logic above. + * + * @param array $row + * + * @return array + * id, status (name), total_amount, currency, trxn_id, invoice_id, + * receipt_date. + */ + protected function normalizeContribution(array $row): array { + return [ + 'id' => (int) $row['id'], + 'status' => $row['contribution_status_id:name'], + 'total_amount' => (float) $row['total_amount'], + 'currency' => $row['currency'], + 'trxn_id' => $row['trxn_id'] ?? NULL, + 'invoice_id' => $row['invoice_id'] ?? NULL, + 'receipt_date' => $row['receipt_date'] ?? NULL, + ]; + } + + /** + * Sync a Square refund into CiviCRM. + * + * Recorded as a negative payment linked to the refunded payment, as + * CiviCRM's own Payment.cancel does, so partial refunds are represented + * and CRM_Financial_BAO_Payment::create() sets the contribution status. + * + * @param array $refund + * Refund object from a refund.created or refund.updated webhook. + */ + public function syncRefundFromSquare(array $refund) { + $paymentId = $refund['payment_id'] ?? NULL; + $refundId = $refund['id'] ?? NULL; + $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, ['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. + 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'])) ? 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; + } + + $this->recordSquareRefund($refund, $refundAmount); + } + + /** + * Record a completed Square refund, once. Body of syncRefundFromSquare(). + * + * @param array $refund + * Refund object from a refund.created or refund.updated webhook. + * @param float $refundAmount + * + * @throws \CRM_Core_Exception + */ + private function recordSquareRefund(array $refund, float $refundAmount): void { + $paymentId = $refund['payment_id']; + $refundId = $refund['id']; + + // The refunded payment, as recorded by this processor. + $original = $this->findRecordedPayment($paymentId); + if (!$original) { + // Payments recorded before payments carried a processor are found by + // the contribution's own trxn_id — but only if the payment really has + // no processor: one recorded by another processor is not this one's + // to refund. + $contributionId = $this->findContributionIdByTrxnId($paymentId); + $original = $contributionId ? $this->findContributionPayment($contributionId, $paymentId) : NULL; + if ($original) { + $original['contribution_id'] = $contributionId; + } + 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']; + + // 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. + $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']}." : '.')); + } + finally { + $lock->release(); + } + } + + /** + * Sync a paid Square subscription invoice 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. + * + * @param array $invoice + */ + public function syncInvoiceFromSquare(array $invoice) { + $this->handleInvoicePaymentCreated(['data' => ['object' => ['invoice' => $invoice]]]); + } + + /** + * Sync a Square subscription with the corresponding CiviCRM recurring contribution. + * + * 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. + * + * @throws \CRM_Core_Exception + */ + public function syncSubscriptionFromSquare(string $squareSubscriptionId) { + CRM_Core_Payment_SquareDebugLogger::log("Square syncSubscriptionFromSquare(): called from SquareIPN for subscription_id={$squareSubscriptionId}."); + if (empty($squareSubscriptionId)) { + throw new CRM_Core_Exception('Missing Square subscription ID for sync.'); + } + + // 1. Look up the subscription in Square + $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->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}"); + return; + } + + // 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()), $sub->getCanceledDate()); + } + + /** + * Apply a Square subscription's status and amount to its recurring contribution. + * + * @param array $recur + * Recurring contribution, as returned by findRecurBySubscriptionId(). + * @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, ?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})."); + + $updates = []; + if (!empty($amount) && (float) $amount !== (float) $recur['amount']) { + $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."); + } + } + + if (empty($updates)) { + CRM_Core_Payment_SquareDebugLogger::log("Square: contribution_recur {$recurId} already up to date."); + return; + } + + $this->updateRecur($recurId, $updates); + CRM_Core_Payment_SquareDebugLogger::log("Square sync: Updated recurring contribution {$recurId}: " . json_encode($updates)); + } + + /** + * Whether a status Square reports for a subscription may be applied to its recurring contribution. + * + * Pending and In Progress say whether the series has been paid for, which + * CiviCRM records itself: Payment.create moves a recurring contribution + * from Pending to In Progress when its first payment is recorded (see + * recordSubscriptionInstallment()). A Square subscription's status says + * nothing about payment — it is ACTIVE from the moment billing starts, + * PENDING before its start date — and its webhooks can arrive after the + * payment's. So Square never moves a recur back to Pending, nor to In + * Progress before its first payment is recorded — or after it was + * Cancelled or Completed (Square keeps reporting a cancelled subscription + * ACTIVE until its cancellation date). Cancelled, Completed and Failed + * always apply. + * + * @param int $currentStatusId + * @param int $newStatusId + * + * @return bool + */ + protected function isRecurStatusChangeAllowed(int $currentStatusId, int $newStatusId): bool { + $pending = CRM_Square_Status::recurStatusId('Pending'); + if ($newStatusId === $pending) { + return FALSE; + } + if ($newStatusId === CRM_Square_Status::recurStatusId('In Progress')) { + return !in_array($currentStatusId, [ + $pending, + CRM_Square_Status::recurStatusId('Cancelled'), + CRM_Square_Status::recurStatusId('Completed'), + ], TRUE); + } + return TRUE; + } + + /** + * Extract override amount from Square subscription. + * + * @param array $subscription + * + * @return float|null + */ + protected function extractSubscriptionAmount(array $subscription) { + if (!empty($subscription['price_override_money']['amount'])) { + 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). + return NULL; + } + + /** + * Process Square invoice.payment_made webhook event. + * + * The preferred way a subscription installment is recorded: unlike a + * payment.updated payload, the invoice names its subscription. The + * installment itself is recorded by recordSubscriptionInstallment(), + * which payment.updated uses too, so whichever arrives first records it + * and the other is a no-op. + * + * @param array $payload + * Full decoded JSON from Square webhook. + * + * @throws \CRM_Core_Exception + */ + public function handleInvoicePaymentCreated(array $payload) { + CRM_Core_Payment_SquareDebugLogger::log('Square handleInvoicePaymentCreated(): called from SquareIPN for invoice.payment_made.'); + $invoice = $payload['data']['object']['invoice'] ?? NULL; + $invoiceId = $invoice['id'] ?? NULL; + if (!$invoiceId) { + CRM_Core_Payment_SquareDebugLogger::log('Square webhook: invoice.payment_made missing invoice object or ID.'); + return; + } + + $subscriptionId = $invoice['subscription_id'] ?? NULL; + if (!$subscriptionId) { + CRM_Core_Payment_SquareDebugLogger::log("Square webhook: invoice {$invoiceId} has no subscription_id, skipping."); + return; + } + + $invoiceStatus = strtoupper((string) ($invoice['status'] ?? '')); + if ($invoiceStatus !== 'PAID') { + CRM_Core_Payment_SquareDebugLogger::log("Square webhook: invoice {$invoiceId} is {$invoiceStatus}; nothing is recorded until it is paid in full."); + return; + } + + $recur = $this->findOrLinkRecur($subscriptionId); + if (!$recur) { + $this->handleUnknownSubscription($subscriptionId, $invoice['updated_at'] ?? $invoice['created_at'] ?? NULL, "invoice {$invoiceId}"); + return; + } + + $this->recordSubscriptionInstallment($recur, $this->installmentFromInvoice($invoice)); + } + + /** + * Sync a Square invoice.scheduled_charge_failed webhook event. + * + * @param array $invoice + * Invoice object from the webhook payload. + * + * @throws \CRM_Core_Exception + */ + 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.scheduled_charge_failed missing invoice ID or subscription_id, skipping.'); + return; + } + + $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']); + try { + $contributions = $this->getRecurContributions((int) $recur['id']); + + foreach ($contributions as $contribution) { + if (($contribution['invoice_id'] ?? NULL) === $invoiceId) { + if ($contribution['status'] === 'Pending') { + $this->updateContribution($contribution['id'], ['contribution_status_id' => CRM_Square_Status::contributionStatusId('Failed')]); + CRM_Core_Payment_SquareDebugLogger::log("Square: Marked contribution {$contribution['id']} as Failed for invoice {$invoiceId}."); + } + return; + } + } + + $signup = $this->findSignupContribution($contributions, $recur); + if ($signup) { + // Square could not charge the first installment. It keeps the + // invoice open for the customer to pay, so the checkout's + // contribution stays Pending — and is completed if Square collects + // it later — rather than gaining a separate Failed duplicate. + Civi::log()->warning("Square: the first payment of recurring contribution {$recur['id']} (Square invoice {$invoiceId}) failed; contribution {$signup['id']} remains Pending."); + return; + } + + $failed = $this->repeatRecurContribution($recur, [ + 'contribution_status' => 'Failed', + 'invoice_id' => $invoiceId, + 'receive_date' => $this->squareTimestampToCivi($invoice['updated_at'] ?? NULL), + ]); + CRM_Core_Payment_SquareDebugLogger::log("Square: Created Failed contribution {$failed['id']} for invoice {$invoiceId}."); + } + finally { + $lock->release(); + } + } + + /** + * Find the contact a Square payment made outside CiviCRM belongs to. + * + * 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. + * + * @return int|null + * CiviCRM contact ID or NULL if not found. + */ + protected function findContactIdForPayment(array $payment) { + $customerId = $payment['customer_id'] ?? NULL; + if ($customerId) { + $contactId = $this->findContactIdBySquareCustomer((string) $customerId); + if ($contactId) { + return $contactId; + } + } + + $receiptEmail = trim((string) ($payment['buyer_email_address'] ?? '')); + if ($receiptEmail !== '') { + $contactIds = $this->findContactIdsByEmail($receiptEmail); + if (count($contactIds) === 1) { + return $contactIds[0]; + } + if (count($contactIds) > 1) { + CRM_Core_Payment_SquareDebugLogger::log('Square findContactIdForPayment(): ' . count($contactIds) . " contacts share the email of payment {$payment['id']}; not choosing one."); + } + } + + return NULL; + } + + /** + * The contact this processor has mapped a Square customer to. + * + * @param string $customerId + * + * @return int|null + */ + 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; + } + + /** + * 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')); + } + + /** + * 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 new file mode 100644 index 00000000..a4456a13 --- /dev/null +++ b/CRM/Square/Status.php @@ -0,0 +1,165 @@ +gateway = $gateway; + } + + /** + * 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' => [ + 'label' => 'Daily', + 'unit' => 'day', + 'step' => 1, + ], + 'WEEKLY' => [ + 'label' => 'Weekly', + 'unit' => 'week', + 'step' => 1, + ], + 'EVERY_TWO_WEEKS' => [ + 'label' => 'Every 2 Weeks', + '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', + 'step' => 1, + ], + 'EVERY_TWO_MONTHS' => [ + 'label' => 'Every 2 Months', + 'unit' => 'month', + 'step' => 2, + ], + 'QUARTERLY' => [ + 'label' => 'Quarterly', + 'unit' => 'month', + 'step' => 3, + ], + 'EVERY_FOUR_MONTHS' => [ + 'label' => 'Every 4 Months', + 'unit' => 'month', + 'step' => 4, + ], + 'EVERY_SIX_MONTHS' => [ + 'label' => 'Every 6 Months', + 'unit' => 'month', + 'step' => 6, + ], + 'ANNUAL' => [ + 'label' => 'Annual', + 'unit' => 'year', + 'step' => 1, + ], + 'EVERY_TWO_YEARS' => [ + 'label' => 'Every 2 Years', + 'unit' => 'year', + 'step' => 2, + ], + ]; + + /** + * Get the plan variation ID for recurring-payment parameters. + */ + public function getPlanVariationIdForParams(array $params): string { + $entity = $params['component'] ?? 'contribute'; + $amount = (float) ($params['amount'] ?? 0); + $currency = $params['currency'] ?? 'USD'; + $intervalUnit = $params['frequency_unit'] ?? ''; + $intervalStep = (int) ($params['frequency_interval'] ?? 1); + $installments = (int) ($params['installments'] ?? 0); + if (!$amount || !$intervalUnit) { + throw new CRM_Core_Exception('Amount and cadence are required for Square subscription.'); + } + + // A plan identifies a subscription purpose; a variation identifies its amount and cadence. + $planName = sprintf( + 'CiviCRM %s', + ucfirst($entity) + ); + + $planId = $this->getOrCreateSubscriptionPlan($planName); + CRM_Core_Payment_SquareDebugLogger::log("Square plan ID for {$entity}: {$planId}"); + return $this->getOrCreatePlanVariation( + $planId, $amount, + $currency, $intervalUnit, + $intervalStep, $installments + ); + } + + /** + * Get or create a subscription plan variation with cadence. + * + * @param string $planId + * @param float $amount + * @param string $currency + * @param string $intervalUnit + * Day, week, month, or year. + * @param int $intervalStep + * @param int|null $installments + * + * @return string Plan variation ID + * + * @throws CRM_Core_Exception + */ + protected function getOrCreatePlanVariation( + string $planId, + float $amount, + string $currency, + string $intervalUnit, + int $intervalStep = 1, + ?int $installments = NULL, + ): string { + 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}"); + // 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, and a finite plan must + // never reuse an open-ended one's. + $cacheKey = implode('_', [ + $this->gateway->processorId(), + $this->gateway->isTestMode() ? 'test' : 'live', + $this->gateway->getLocationId(), + $planId, + $cadence, + $amount, + $currency, + $installments ?: 'indefinite', + ]); + $cache = Civi::settings()->get('org_square_plan_variation_cache') ?? []; + + if (!empty($cache[$cacheKey])) { + return $cache[$cacheKey]; + } + + $label = sprintf( + '%s %0.2f %s', + $cadence, + $amount, + $currency + ); + CRM_Core_Payment_SquareDebugLogger::log("Creating label Square plan variation: {$label}"); + $amountMinorUnits = CRM_Square_Currency::toMinorUnits($amount, $currency); + + $phaseValues = [ + 'ordinal' => 0, + // MONTHLY, ANNUAL. + 'cadence' => strtoupper($cadence), + 'pricing' => new SubscriptionPricing([ + 'type' => 'STATIC', + 'priceMoney' => new Money(['amount' => $amountMinorUnits, '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. Square bills the first period itself (see doRecurPayment()), so + // periods equals CiviCRM's installments. + if (!empty($installments)) { + $phaseValues['periods'] = $installments; + } + $phase = new SubscriptionPhase($phaseValues); + + $catalogObject = CatalogObject::subscriptionPlanVariation(new CatalogObjectSubscriptionPlanVariation([ + 'id' => '#var_' . md5($cacheKey), + 'subscriptionPlanVariationData' => new CatalogSubscriptionPlanVariation([ + 'name' => $label, + 'subscriptionPlanId' => $planId, + 'phases' => [$phase], + ]), + ])); + + $response = $this->gateway->call(fn (SquareClient $client) => $client->catalog->batchUpsert(new BatchUpsertCatalogObjectsRequest([ + 'idempotencyKey' => $this->gateway->idempotencyKey('plan-variation', $cacheKey), + 'batches' => [new CatalogObjectBatch(['objects' => [$catalogObject]])], + ]))); + + $objects = $response->getObjects(); + $variationId = !empty($objects[0]) ? $objects[0]->getValue()->getId() : NULL; + CRM_Core_Payment_SquareDebugLogger::log("Created Square plan variation ID: {$variationId}"); + if (!$variationId) { + throw new CRM_Core_Exception('Failed to create Square plan variation.'); + } + + $cache[$cacheKey] = $variationId; + Civi::settings()->set('org_square_plan_variation_cache', $cache); + + return $variationId; + } + + /** + * Resolve Square cadence from interval unit + frequency. + * + * @param string $unit + * Day, week, month, or year. + * @param int $step + * + * @return string + * + * @throws CRM_Core_Exception + */ + protected function resolveCadence(string $unit, int $step): string { + + foreach (self::SQUARE_CADENCES as $cadence => $def) { + if ($def['unit'] === $unit && $def['step'] === $step) { + return $cadence; + } + } + + throw new CRM_Core_Exception( + "Unsupported Square cadence: every {$step} {$unit}(s)" + ); + } + + /** + * Get or create a Square Subscription Plan. + * + * @param string $name + * + * @return string Plan ID + * + * @throws CRM_Core_Exception + */ + protected function getOrCreateSubscriptionPlan(string $name): string { + // Scope the cache by processor + environment + location, same reasoning + // as getOrCreatePlanVariation(). + $cacheKey = implode('_', [ + $this->gateway->processorId(), + $this->gateway->isTestMode() ? 'test' : 'live', + $this->gateway->getLocationId(), + $name, + ]); + $cache = Civi::settings()->get('org_square_plan_cache') ?? []; + + if (!empty($cache[$cacheKey])) { + return $cache[$cacheKey]; + } + + $catalogObject = CatalogObject::subscriptionPlan(new CatalogObjectSubscriptionPlan([ + 'id' => '#plan_' . md5($cacheKey), + 'subscriptionPlanData' => new CatalogSubscriptionPlan([ + 'name' => $name, + ]), + ])); + + $response = $this->gateway->call(fn (SquareClient $client) => $client->catalog->batchUpsert(new BatchUpsertCatalogObjectsRequest([ + 'idempotencyKey' => $this->gateway->idempotencyKey('plan', $cacheKey), + 'batches' => [new CatalogObjectBatch(['objects' => [$catalogObject]])], + ]))); + + $objects = $response->getObjects(); + $planId = !empty($objects[0]) ? $objects[0]->getValue()->getId() : NULL; + if (!$planId) { + throw new CRM_Core_Exception('Failed to create Square subscription plan.'); + } + + $cache[$cacheKey] = $planId; + Civi::settings()->set('org_square_plan_cache', $cache); + + return $planId; + } + + /** + * Cancel a Square subscription. + * + * @param string $subscriptionId + * Square subscription ID. + * + * @throws \CRM_Core_Exception + */ + public function cancel(string $subscriptionId): void { + $this->gateway->call(fn (SquareClient $client) => $client->subscriptions->cancel( + new CancelSubscriptionsRequest(['subscriptionId' => $subscriptionId]) + )); + } + + /** + * Change the amount every future installment of a subscription charges. + * + * Sets the subscription's price override, which replaces the STATIC price + * of the plan variation it was created with (see getOrCreatePlanVariation()). + * Square requires the subscription's current version on every update, to + * reject concurrent changes, so it is read immediately before. + * + * @param string $subscriptionId + * Square subscription ID. + * @param float $amount + * New installment amount, in major currency units. + * @param string $currency + * + * @throws \CRM_Core_Exception + */ + public function changeAmount(string $subscriptionId, float $amount, string $currency): void { + $subscription = $this->gateway->call(fn (SquareClient $client) => $client->subscriptions->get( + new GetSubscriptionsRequest(['subscriptionId' => $subscriptionId]) + ))->getSubscription(); + if (empty($subscription)) { + throw new CRM_Core_Exception("Square subscription {$subscriptionId} not found."); + } + + $values = [ + 'priceOverrideMoney' => new Money([ + 'amount' => CRM_Square_Currency::toMinorUnits($amount, $currency), + 'currency' => $currency, + ]), + ]; + if ($subscription->getVersion() !== NULL) { + $values['version'] = $subscription->getVersion(); + } + $this->gateway->call(fn (SquareClient $client) => $client->subscriptions->update(new UpdateSubscriptionRequest([ + 'subscriptionId' => $subscriptionId, + 'subscription' => new Subscription($values), + ]))); + } + +} diff --git a/CRM/Square/Upgrader.php b/CRM/Square/Upgrader.php index 86601168..70549ab3 100644 --- a/CRM/Square/Upgrader.php +++ b/CRM/Square/Upgrader.php @@ -13,7 +13,8 @@ class CRM_Square_Upgrader extends CRM_Extension_Upgrader_Base { * Runs on fresh installs only. */ public function install(): void { - $this->createSquareCustomerMapTable(); + _square_assert_php_version(); + $this->createSquareCustomerMapTable(TRUE); } /** @@ -25,11 +26,131 @@ public function install(): void { * now-superseded custom field group. */ public function upgrade_1000(): bool { - $this->createSquareCustomerMapTable(); + _square_assert_php_version(); + // Without the unique customer key: upgrade_1001 adds it once it has + // checked the backfilled mappings for conflicts. + $this->createSquareCustomerMapTable(FALSE); $this->backfillSquareCustomerMapFromCustomField(); return TRUE; } + /** + * Map each Square customer to at most one contact per payment processor. + * + * Adds a unique (payment_processor_id, square_customer_id) key, so that + * one Square customer (and its cards) can never be shared by two CiviCRM + * contacts. Existing mappings that already break that rule are never + * resolved automatically — which contact a customer belongs to is a + * decision for a person — so the upgrade stops and lists them. + * + * @throws \CRM_Core_Exception + * If existing mappings conflict. + */ + public function upgrade_1001(): bool { + _square_assert_php_version(); + if ($this->hasUniqueCustomerKey()) { + return TRUE; + } + $conflicts = $this->findConflictingCustomerMappings(); + if ($conflicts) { + throw new CRM_Core_Exception(self::describeCustomerMappingConflicts($conflicts)); + } + $this->addUniqueCustomerKey(); + 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. + * + * @param array $conflicts + * Rows with payment_processor_id, square_customer_id and contact_ids + * (comma-separated). + * + * @return string + */ + public static function describeCustomerMappingConflicts(array $conflicts): string { + $lines = []; + foreach ($conflicts as $conflict) { + $lines[] = sprintf( + 'payment processor %d, Square customer %s: contacts %s', + $conflict['payment_processor_id'], + $conflict['square_customer_id'], + str_replace(',', ', ', (string) $conflict['contact_ids']) + ); + } + return 'Square extension upgrade stopped: ' . count($conflicts) . ' Square customer(s) are mapped to more than one ' + . 'CiviCRM contact on the same payment processor, so each customer cannot be limited to one contact. For each, ' + . 'decide which contact the Square customer belongs to (e.g. by its email or reference ID in the Square ' + . 'Dashboard), delete the other contacts\' rows from square_customer_map, then run the upgrade again. ' + . implode('; ', $lines) . '.'; + } + + /** + * Whether square_customer_map already has its unique customer key. + */ + protected function hasUniqueCustomerKey(): bool { + return CRM_Core_BAO_SchemaHandler::checkIfIndexExists('square_customer_map', 'UI_processor_customer'); + } + + /** + * Square customers mapped to more than one contact on the same processor. + * + * @return array + * Rows with payment_processor_id, square_customer_id and contact_ids. + */ + protected function findConflictingCustomerMappings(): array { + $dao = CRM_Core_DAO::executeQuery( + 'SELECT payment_processor_id, square_customer_id, GROUP_CONCAT(contact_id ORDER BY contact_id) AS contact_ids + FROM square_customer_map + GROUP BY payment_processor_id, square_customer_id + HAVING COUNT(*) > 1 + ORDER BY payment_processor_id, square_customer_id' + ); + $conflicts = []; + while ($dao->fetch()) { + $conflicts[] = [ + 'payment_processor_id' => (int) $dao->payment_processor_id, + 'square_customer_id' => $dao->square_customer_id, + 'contact_ids' => $dao->contact_ids, + ]; + } + return $conflicts; + } + + /** + * Add the unique (payment_processor_id, square_customer_id) key. + */ + protected function addUniqueCustomerKey(): void { + CRM_Core_DAO::executeQuery( + 'ALTER TABLE `square_customer_map` ADD UNIQUE KEY `UI_processor_customer` (`payment_processor_id`, `square_customer_id`)' + ); + } + /** * Runs on uninstall. Drops the table this extension owns. */ @@ -41,8 +162,15 @@ public function uninstall(): void { * Create the square_customer_map table, if it doesn't already exist. * * Maps (contact_id, payment_processor_id) -> square_customer_id. + * + * @param bool $uniqueCustomer + * Whether to include the unique (payment_processor_id, + * square_customer_id) key (see upgrade_1001()). */ - protected function createSquareCustomerMapTable(): void { + protected function createSquareCustomerMapTable(bool $uniqueCustomer): void { + $uniqueCustomerKey = $uniqueCustomer + ? 'UNIQUE KEY `UI_processor_customer` (`payment_processor_id`, `square_customer_id`),' + : ''; CRM_Core_DAO::executeQuery(<<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 8c0cba79..7df655f5 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ Square payment processor extension for CiviCRM. - **Version:** 1.2.0 (beta) - **CiviCRM compatibility:** 6.16+ - **License:** AGPL-3.0-or-later -- **Square API version:** 2025-01-15 +- **Square API version:** 2025-10-16 (sent by the bundled `square/square` 43.2 SDK) - **Requires:** `mjwshared`, `civi_contribute` (see `info.xml`) --- @@ -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 updates 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,13 +58,20 @@ 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 | -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. An initial charge is made immediately at subscription creation; subsequent charges are handled by Square and reported back via webhooks. +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. --- @@ -70,24 +80,26 @@ Recurring payments use the Square Catalog API to create subscription plans and p Configure the Square webhook endpoint as `https://your-site.org/civicrm/payment/ipn/{processor_id}`. It validates the `X-Square-Hmacsha256-Signature` header before the event is queued. The queue -record is processed immediately after it is accepted. Failed records remain in -the CiviCRM webhook queue for the **Process Pending Webhooks** scheduled job -to retry. +record is processed immediately after it is accepted. A record that fails +transiently (Square unavailable, or a related CiviCRM record not saved yet +because webhooks arrived out of order) is left in status `new` for the +**Process Payment Processor Webhooks** scheduled job to retry, for up to 72 +hours; any other failure is marked `error`. See +[docs/WEBHOOKS.md](docs/WEBHOOKS.md). ### Handled events | Event | Action | |---|---| | `subscription.created` | Syncs subscription status to `ContributionRecur` | -| `subscription.updated` | Syncs subscription status/amount to `ContributionRecur` | -| `subscription.canceled` | Marks `ContributionRecur` as Cancelled | -| `invoice.created` | Creates a Pending contribution for the upcoming invoice | -| `invoice.payment_made` | Reconciles the paid invoice | -| `invoice.payment_failed` | Reconciles the failed invoice | -| `payment.updated` | Reconciles an existing contribution | -| `refund.created` | Reconciles a refund | - -Webhook deduplication uses CiviCRM's `civicrm_paymentprocessor_webhook` queue +| `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.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 tokens, card nonces, or unredacted Square responses. @@ -113,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. + --- --- @@ -131,14 +148,17 @@ nothing ambiguous remains. - CiviCRM native contribution pages and event registration forms - Drupal Webform (webform_civicrm module) billing blocks, including AJAX reloads -- Backend contribution/event forms + +Back-office (staff-entered) card payments are not supported. Key globals: - `CRM.squarePayment` — Square's namespaced integration state - `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. --- @@ -161,9 +181,9 @@ The card element mounts into `#square-card-container`. Tokenization happens on f | Table | Owner | Purpose | |---|---|---| -| `square_customer_map` | This extension (`CRM_Square_Upgrader`) | Maps `(contact_id, payment_processor_id)` → Square customer ID. Created on install; dropped on uninstall. | +| `square_customer_map` | This extension (`CRM_Square_Upgrader`) | Maps `(contact_id, payment_processor_id)` → Square customer ID; each customer maps to one contact per processor. Created on install; dropped on uninstall. | | `civicrm_payment_token` | CiviCRM core | Stores Square card-on-file references (one row per card), linked from `civicrm_contribution_recur.payment_token_id`. Not owned by this extension — never dropped on uninstall. | -| `civicrm_paymentprocessor_webhook` | CiviCRM core | Webhook queue; retains deduplication, status and retry information. Not owned by this extension. | +| `civicrm_paymentprocessor_webhook` | mjwshared extension | Webhook queue; retains deduplication, status and retry information. Not owned by this extension. | --- @@ -172,18 +192,26 @@ The card element mounts into `#square-card-container`. Tokenization happens on f ``` CRM/ Core/Payment/ - Square.php Payment processor class (payments, subscriptions, refunds, webhooks) - SquareIPN.php Webhook event router and processor + 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/ - Form/Settings.php Administer > System Settings > Square Settings (debug logging toggle) + Gateway.php Square API access (client, errors, idempotency keys) + Customers.php Square customers and cards on file + 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 + 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 @@ -208,8 +236,9 @@ the following: `{processor_id}` with the CiviCRM payment processor ID. 4. Subscribe to the events in [Webhook Events](#webhook-events). Events not listed there are acknowledged but intentionally ignored. -5. Verify that CiviCRM's **Process Pending Webhooks** scheduled job is enabled. - It retries queued records whose first processing attempt failed. +5. Verify that mjwshared's **Process Payment Processor Webhooks** scheduled job + is enabled. It retries queued records left in status `new` by a transient + failure. 6. Complete a test one-time contribution and, if recurring payments are in scope, a test recurring contribution. Confirm the contribution, payment token, recurring contribution, and webhook records in CiviCRM. 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 0f80af7b..76d22977 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -4,21 +4,54 @@ | Component | Responsibility | |---|---| -| `CRM/Core/Payment/Square.php` | Payment processor: browser assets, payments, refunds, subscriptions, and notification entry point. | +| `CRM/Core/Payment/Square.php` | CiviCRM's payment-processor adapter (`CRM_Core_Payment`): billing block, checkout payments, refunds, recurring setup, amount changes, cancellation, and the webhook entry point. Delegates to the classes below. | +| `CRM/Square/Gateway.php` | Square API access for one processor: SDK client, credentials and environment, idempotency keys, and translation of SDK errors (transient ones as `CRM_Core_Payment_SquareRetryableException`). | +| `CRM/Square/Customers.php` | Square customers and cards on file: `square_customer_map` and PaymentToken records. | +| `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. @@ -30,7 +63,10 @@ the CiviCRM recurring contribution. | Square customer mapping | `square_customer_map` | This extension | | Card-on-file reference | `civicrm_payment_token` | CiviCRM core | | Recurring contribution | `civicrm_contribution_recur` | CiviCRM core | -| Webhook state | `civicrm_paymentprocessor_webhook` | CiviCRM core | +| Webhook state | `civicrm_paymentprocessor_webhook` | mjwshared extension | Customer mappings use `(contact_id, payment_processor_id)`, separating -sandbox, production, and different Square merchant accounts. +sandbox, production, and different Square merchant accounts. Each Square +customer maps to at most one contact per processor (`UI_processor_customer`, +added by upgrade 1001, which stops and lists any existing conflicts rather +than resolving them). diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index abfac0ae..6f733256 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -25,5 +25,22 @@ shared between sandbox and production. credentials only after the sandbox flow succeeds. Recurring contributions create or reuse Square Catalog plans and variations. -The initial charge occurs at setup; later subscription activity is reconciled -from Square webhook events. +Square charges every installment, including the first, and reports it by +webhook: the checkout's contribution stays Pending until Square's first charge +is confirmed, so the webhook subscription (see [WEBHOOKS.md](WEBHOOKS.md)) must +be in place before recurring payments are taken. See +[WEBHOOKS.md](WEBHOOKS.md#recurring-installments) for how installments are +recorded and receipted. + +Staff (and donors, on self-service links) can change a recurring +contribution's amount from CiviCRM; the change is sent to the Square +subscription, applying from its next installment. Changing the number of +installments is refused, since Square cannot change it on an existing +subscription, as is changing the amount of a recurring contribution with +more than one line item. + +Upgrading to this version adds a unique key so that each Square customer maps +to one CiviCRM contact per payment processor. If existing mappings already +share a customer between contacts, the upgrade stops and lists them: decide +which contact each customer belongs to, delete the other rows from +`square_customer_map`, and run the upgrade again. diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 4507d65a..65a4dbdc 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -5,8 +5,71 @@ Run the following from the extension root: ```bash vendor/bin/phpcs --standard=phpcs.xml.dist CRM square.php settings managed tests vendor/bin/phpunit --configuration tests/phpunit/phpunit.xml.dist +CIVICRM_CORE=/path/to/civicrm phpstan analyse -c phpstan.neon.dist ``` +PHPUnit treats deprecations, notices and warnings as failures. The suite +runs without a CiviCRM database: `tests/phpunit/bootstrap.php` loads real +CiviCRM first if `CIVICRM_BOOTSTRAP_FILE` is set, then defines minimal +stand-ins for whatever is missing. CiviCRM data access is confined to small +protected methods (e.g. `CRM_Square_Reconciler`'s find/record methods, and +`CRM_Core_Payment_SquareIPN`'s queue methods), which tests replace with +in-memory fakes (`SquareLedgerTestCase.php`) that mimic the core behaviour +the logic relies on. Square is mocked at the SDK client. + +Static analysis needs a CiviCRM 6.16 source tree in `CIVICRM_CORE` (an +extracted release tarball works); PHPStan 1.12 at level 5. Findings that +predate it are listed in `phpstan-baseline.neon`, so only new ones fail. + +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. + +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 configuration. It intentionally permits CiviCRM's `CRM_*` class names, diff --git a/docs/OVERVIEW.html b/docs/OVERVIEW.html index 46b24f0c..87c028e7 100644 --- a/docs/OVERVIEW.html +++ b/docs/OVERVIEW.html @@ -340,7 +340,7 @@

Square Payment Processor

Overview

What this extension does

-

org.uschess.square registers Square as a CiviCRM payment processor type — the same role Stripe or PayPal extensions play — so contribution pages, event registration, and back-office forms can charge a Square-issued card without CiviCRM ever seeing the card number.

+

org.uschess.square registers Square as a CiviCRM payment processor type — the same role Stripe or PayPal extensions play — so contribution pages, event registration, and Drupal webforms can charge a Square-issued card without CiviCRM ever seeing the card number.

It depends on two core CiviCRM extensions, mjwshared and civi_contribute, and is built against CiviCRM 6.16 or later. Composer dependencies ship committed in vendor/, so installing it is a normal extension enable — no build step. It is maintained by US Chess Federation and developed by Skvare, distributed under AGPL-3.0-or-later.

Why it exists: US Chess needed dues, tournament entry, and donation payments to run through Square rather than the processors CiviCRM ships with out of the box, with the same card-on-file and recurring-billing experience members already expect from CiviCRM's native processors.
@@ -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 and amount updates 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, Webform, and backend 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. @@ -493,19 +493,18 @@

Who owns what data

Webhook events

What Square tells CiviCRM, and when

-

Square posts to https://your-site.org/civicrm/payment/ipn/{processor_id}. The X-Square-Hmacsha256-Signature header is validated before anything is queued; a failed record stays in the queue for the Process Pending Webhooks scheduled job to retry.

+

Square posts to https://your-site.org/civicrm/payment/ipn/{processor_id}. The X-Square-Hmacsha256-Signature header is validated before anything is queued; a record that fails transiently stays in the queue (status new) for mjwshared's Process Payment Processor Webhooks scheduled job to retry.

- - - - - - - + + + + + +
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
@@ -565,7 +564,7 @@

Sandbox first, always

  • Create a Square payment processor in CiviCRM with sandbox Application ID, Access Token, Location ID, and Webhook Signature Key.
  • In the Square Developer Dashboard, create a webhook subscription for that same sandbox application pointed at /civicrm/payment/ipn/{processor_id}.
  • Subscribe to the eight events listed above — anything else is acknowledged but intentionally ignored.
  • -
  • Confirm CiviCRM's Process Pending Webhooks scheduled job is enabled, to retry failed deliveries.
  • +
  • Confirm mjwshared's Process Payment Processor Webhooks scheduled job is enabled, to retry transient failures.
  • Run a test one-time contribution, and a test recurring one if it's in scope. Check the contribution, payment token, recurring record, and webhook queue all landed correctly.
  • Only after sandbox checks out, repeat the setup with the production Square application and live credentials.
  • diff --git a/docs/WEBHOOKS.md b/docs/WEBHOOKS.md index aa737714..5041ea83 100644 --- a/docs/WEBHOOKS.md +++ b/docs/WEBHOOKS.md @@ -11,8 +11,25 @@ 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`, and `refund.created`. +`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 +webhook subscriptions actually include it, not just `invoice.created`. Without it, +installments are still recorded from `payment.updated`, at the cost of one +Square invoice search per installment. `refund.updated` is needed to record +refunds made in the Square Dashboard, since `refund.created` usually reports a +refund that is still `PENDING`. ## Processing lifecycle @@ -20,12 +37,77 @@ Subscribe to: `subscription.created`, `subscription.updated`, 2. The extension validates the `X-Square-Hmacsha256-Signature` header against the raw body and CiviCRM notification URL. 3. Supported events are deduplicated by Square event ID and recorded in - `civicrm_paymentprocessor_webhook`. -4. The queue record is immediately processed and marked `success` or `error`. -5. **Process Pending Webhooks** can retry records that need further processing. + `civicrm_paymentprocessor_webhook`, in status `new`. +4. The record is processed immediately and marked: + - `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, 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). + These are not retried automatically. +5. If the request dies while processing (e.g. a PHP fatal error), the record + stays `new` and the scheduled job retries it. A record left in + `processing` was interrupted during a scheduled-job run; mjwshared's + system check reports these after an hour — use the webhook queue's + **Retry** action once the cause is fixed. Unsupported events are acknowledged but not processed. +## Recurring installments + +Square charges every installment of a subscription itself, including the +first. Its webhooks for an installment are, in order: `invoice.created` (a +draft — nothing is recorded), then `payment.updated` and +`invoice.payment_made`. The payment carries only the invoice's `order_id`, +not the subscription, so it is matched to its invoice at Square. + +- The **first installment** completes the Pending contribution CiviCRM created + at checkout; it never creates a new one. +- **Later installments** become new contributions via + `Contribution.repeattransaction` (keeping the series' financial type and + line items), then are completed. +- Payments are recorded with `Payment.create`. The Square payment ID becomes + the payment's and the contribution's transaction ID, so a replayed or + duplicate event for the same payment records nothing further. +- If Square's amount or currency differs from CiviCRM's, nothing is recorded + and the queue record is marked `error` with a reconciliation message. + CiviCRM's amounts are never rewritten to match Square. +- Square reports its processing fee in a later `payment.updated`; it is then + recorded as the contribution's fee. +- The first installment's contribution is receipted once: not if the checkout + 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 | Symptom | Check | @@ -34,6 +116,7 @@ Unsupported events are acknowledged but not processed. | HTTP 400 | Check that Square posted valid JSON. | | No CiviCRM update | Inspect the queue record's event type, processor ID, status, and error message. | | Repeated delivery | Resolve the queue-record error; duplicate event IDs are otherwise skipped. | +| First recurring contribution stays Pending | Check the queue for that subscription's `payment.updated` / `invoice.payment_made` records and their messages. | Do not log or share access tokens, signature keys, card tokens, raw webhook bodies, or unredacted Square responses. Enable temporary verbose diagnostics at 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/phpstan-baseline.neon b/phpstan-baseline.neon new file mode 100644 index 00000000..de06b2ae --- /dev/null +++ b/phpstan-baseline.neon @@ -0,0 +1,31 @@ +parameters: + ignoreErrors: + - + message: "#^Call to an undefined method CRM_Core_Form\\:\\:elementExists\\(\\)\\.$#" + count: 1 + path: CRM/Core/Payment/Square.php + + - + message: "#^Constructor of class CRM_Core_Payment_Square has an unused parameter \\$mode\\.$#" + count: 1 + path: CRM/Core/Payment/Square.php + + - + message: "#^Negated boolean expression is always false\\.$#" + count: 1 + path: CRM/Core/Payment/Square.php + + - + message: "#^Expression on left side of \\?\\? is not nullable\\.$#" + count: 1 + path: CRM/Square/Customers.php + + - + message: "#^Call to an undefined method CRM_Square_Form_Settings\\:\\:exportValues\\(\\)\\.$#" + count: 1 + path: CRM/Square/Form/Settings.php + + - + message: "#^Ternary operator condition is always true\\.$#" + count: 1 + path: CRM/Square/Gateway.php diff --git a/phpstan.neon.dist b/phpstan.neon.dist new file mode 100644 index 00000000..3b1959bc --- /dev/null +++ b/phpstan.neon.dist @@ -0,0 +1,25 @@ +# Static analysis against CiviCRM core's own classes. +# +# Set CIVICRM_CORE to a CiviCRM 6.16 source tree (e.g. an extracted release +# tarball), then run: phpstan analyse -c phpstan.neon.dist +includes: + - phpstan-baseline.neon + +parameters: + level: 5 + paths: + - CRM + - square.php + scanDirectories: + - %env.CIVICRM_CORE%/CRM + - %env.CIVICRM_CORE%/Civi + - %env.CIVICRM_CORE%/api + - %env.CIVICRM_CORE%/ext/civi_contribute + - %env.CIVICRM_CORE%/vendor/pear + scanFiles: + - %env.CIVICRM_CORE%/Civi.php + - %env.CIVICRM_CORE%/functions.php + - square.civix.php + - tests/phpstan/stubs.php + bootstrapFiles: + - vendor/autoload.php 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 4aefcb3e..5b49825d 100644 --- a/square.php +++ b/square.php @@ -14,6 +14,32 @@ 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,14 +51,17 @@ 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(); } /** * 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 { @@ -59,18 +88,28 @@ function square_civicrm_uninstall(): void { * Implements hook_civicrm_enable(). */ function square_civicrm_enable(): void { + _square_assert_php_version(); _square_civix_civicrm_enable(); } /** - * 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/phpstan/stubs.php b/tests/phpstan/stubs.php new file mode 100644 index 00000000..57d0fdf8 --- /dev/null +++ b/tests/phpstan/stubs.php @@ -0,0 +1,15 @@ +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/.phpunit.result.cache b/tests/phpunit/.phpunit.result.cache deleted file mode 100644 index 3ad35dcc..00000000 --- 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/ChangeSubscriptionAmountTest.php b/tests/phpunit/CRM/Core/Payment/Square/ChangeSubscriptionAmountTest.php new file mode 100644 index 00000000..63be00bd --- /dev/null +++ b/tests/phpunit/CRM/Core/Payment/Square/ChangeSubscriptionAmountTest.php @@ -0,0 +1,222 @@ +processor(); + $message = ''; + + $result = $processor->changeSubscriptionAmount($message, $this->formParams(['amount' => '25.00'])); + + $this->assertTrue($result); + $this->assertCount(1, $this->updates); + $this->assertSame('SUB-1', $this->updates[0]->getSubscriptionId()); + $this->assertSame(2500, $this->updates[0]->getSubscription()->getPriceOverrideMoney()->getAmount()); + $this->assertSame('USD', $this->updates[0]->getSubscription()->getPriceOverrideMoney()->getCurrency(), "The recurring contribution's currency."); + $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. + */ + public function testInstallmentChangeIsRefused(): void { + $this->expectRefusal('number of installments'); + $message = ''; + $this->processor()->changeSubscriptionAmount($message, $this->formParams(['installments' => '6'])); + } + + /** + * Later installments of a multi-item series could not follow the new amount. + */ + public function testMultipleLineItemSeriesIsRefused(): void { + $this->expectRefusal('more than one line item'); + $message = ''; + $this->processor(['line_item_count' => 2])->changeSubscriptionAmount($message, $this->formParams()); + } + + /** + * Only the Square subscription linked to this recurring contribution is changed. + * + * @dataProvider unlinkedRecurProvider + */ + public function testRecurNotLinkedToTheSubscriptionIsRefused(?array $recur): void { + $this->expectRefusal('not linked to that Square subscription'); + $message = ''; + $this->processor($recur, $recur === NULL)->changeSubscriptionAmount($message, $this->formParams()); + } + + public static function unlinkedRecurProvider(): array { + return [ + "another processor's recurring contribution" => [NULL], + 'a different subscription' => [['processor_id' => 'SUB-OTHER']], + ]; + } + + /** + * @dataProvider invalidAmountProvider + */ + public function testInvalidAmountIsRefused($amount): void { + $this->expectRefusal('positive amount'); + $message = ''; + $this->processor()->changeSubscriptionAmount($message, $this->formParams(['amount' => $amount])); + } + + public static function invalidAmountProvider(): array { + return [ + 'zero' => ['0'], + 'negative' => ['-5'], + 'not a number' => ['abc'], + 'missing' => [NULL], + ]; + } + + /** + * A Square failure bounces the form rather than saving a change Square never made. + */ + public function testSquareFailureIsReportedToTheForm(): void { + $subscriptions = $this->createMock(SubscriptionsClient::class); + $subscriptions->method('get')->willThrowException(new SquareException('connection timed out')); + + try { + $message = ''; + $this->processor([], FALSE, $subscriptions)->changeSubscriptionAmount($message, $this->formParams()); + $this->fail('Expected a PaymentProcessorException.'); + } + catch (PaymentProcessorException $e) { + $this->assertStringContainsString('connection timed out', $e->getMessage()); + $this->assertInstanceOf(CRM_Core_Payment_SquareRetryableException::class, $e->getPrevious()); + } + } + + /** + * @param string $message + */ + private function expectRefusal(string $message): void { + $this->expectException(PaymentProcessorException::class); + $this->expectExceptionMessage($message); + } + + /** + * What CRM_Contribute_Form_UpdateSubscription passes. + * + * @param array $overrides + * + * @return array + */ + private function formParams(array $overrides = []): array { + return array_replace([ + 'id' => 45, + 'contributionRecurID' => 45, + 'subscriptionId' => 'SUB-1', + 'recurProcessorID' => 'SUB-1', + 'amount' => '19.00', + 'installments' => '', + ], $overrides); + } + + /** + * A processor whose recurring contribution 45 is linked to SUB-1. + * + * @param array|null $recurOverrides + * @param bool $noRecur + * Whether recurring contribution 45 belongs to another processor. + * @param \Square\Subscriptions\SubscriptionsClient|null $subscriptions + * + * @return \CRM_Core_Payment_Square + */ + private function processor(?array $recurOverrides = [], bool $noRecur = FALSE, ?SubscriptionsClient $subscriptions = NULL): CRM_Core_Payment_Square { + if ($subscriptions === NULL) { + $subscriptions = $this->createMock(SubscriptionsClient::class); + $subscriptions->method('get')->willReturn(new GetSubscriptionResponse([ + 'subscription' => new Subscription(['id' => 'SUB-1', 'version' => 3]), + ])); + $subscriptions->method('update')->willReturnCallback(function (UpdateSubscriptionRequest $request) { + $this->updates[] = $request; + return new UpdateSubscriptionResponse(['subscription' => $request->getSubscription()]); + }); + } + $client = new SquareClient(token: 'test-token', options: ['baseUrl' => 'https://example.invalid']); + $client->subscriptions = $subscriptions; + $recur = $noRecur ? NULL : array_replace([ + 'processor_id' => 'SUB-1', + 'installments' => NULL, + 'currency' => 'USD', + 'line_item_count' => 1, + ], $recurOverrides ?? []); + $config = $this->processorConfig(); + + return new class($config, $client, $recur) extends CRM_Core_Payment_Square { + + /** + * @var \Square\SquareClient + */ + private SquareClient $mockClient; + + /** + * @var array|null + */ + private ?array $recur; + + /** + * @param array $paymentProcessor + * @param \Square\SquareClient $mockClient + * @param array|null $recur + */ + public function __construct(array $paymentProcessor, SquareClient $mockClient, ?array $recur) { + parent::__construct('live', $paymentProcessor); + $this->mockClient = $mockClient; + $this->recur = $recur; + } + + /** + * @return \Square\SquareClient + */ + protected function buildSquareClient(): SquareClient { + return $this->mockClient; + } + + /** + * @param int $recurId + * + * @return array|null + */ + protected function getRecurForAmountChange(int $recurId): ?array { + return $recurId === 45 ? $this->recur : NULL; + } + + }; + } + +} diff --git a/tests/phpunit/CRM/Core/Payment/Square/ConfigurationTest.php b/tests/phpunit/CRM/Core/Payment/Square/ConfigurationTest.php index cbba6697..be5d4e32 100644 --- a/tests/phpunit/CRM/Core/Payment/Square/ConfigurationTest.php +++ b/tests/phpunit/CRM/Core/Payment/Square/ConfigurationTest.php @@ -54,18 +54,21 @@ public function testGetLocationIdTrimsWhitespace(): void { } public function testApiBaseUrlDefaultsToSandboxInTestMode(): void { - $processor = $this->processor(['is_test' => TRUE]); - $this->assertSame('https://connect.squareupsandbox.com', $this->callMethod($processor, 'getApiBaseUrl')); + $gateway = new CRM_Square_Gateway($this->processorConfig(['is_test' => TRUE])); + $this->assertSame('https://connect.squareupsandbox.com', $this->callMethod($gateway, 'getApiBaseUrl')); } public function testApiBaseUrlDefaultsToLiveOutsideTestMode(): void { - $processor = $this->processor(['is_test' => FALSE]); - $this->assertSame('https://connect.squareup.com', $this->callMethod($processor, 'getApiBaseUrl')); + $gateway = new CRM_Square_Gateway($this->processorConfig(['is_test' => FALSE])); + $this->assertSame('https://connect.squareup.com', $this->callMethod($gateway, 'getApiBaseUrl')); } public function testApiBaseUrlHonorsConfiguredOverrideEvenInTestMode(): void { - $processor = $this->processor(['is_test' => TRUE, 'url_api' => 'https://example-override.test/']); - $this->assertSame('https://example-override.test', $this->callMethod($processor, 'getApiBaseUrl')); + $gateway = new CRM_Square_Gateway($this->processorConfig([ + 'is_test' => TRUE, + 'url_api' => 'https://example-override.test/', + ])); + $this->assertSame('https://example-override.test', $this->callMethod($gateway, 'getApiBaseUrl')); } public function testBuildSquareClientReturnsASquareClientForEitherEnvironment(): void { diff --git a/tests/phpunit/CRM/Core/Payment/Square/ExceptionHandlingTest.php b/tests/phpunit/CRM/Core/Payment/Square/ExceptionHandlingTest.php index 0ee937a5..2068e116 100644 --- a/tests/phpunit/CRM/Core/Payment/Square/ExceptionHandlingTest.php +++ b/tests/phpunit/CRM/Core/Payment/Square/ExceptionHandlingTest.php @@ -6,6 +6,8 @@ use Square\Exceptions\SquareApiException; use Square\Exceptions\SquareException; use Square\Payments\PaymentsClient; +use Square\Cards\CardsClient; +use Civi\Payment\Exception\PaymentProcessorException; /** * Translation of Square SDK exceptions into CRM_Core_Exception. @@ -15,11 +17,6 @@ */ class CRM_Core_Payment_Square_ExceptionHandlingTest extends CRM_Core_Payment_Square_SquareUnitTestCase { - private function processor(): CRM_Core_Payment_Square { - $config = $this->processorConfig(); - return new CRM_Core_Payment_Square('live', $config); - } - private function apiException(int $statusCode, array $errors): SquareApiException { return new SquareApiException('API request failed', $statusCode, json_encode(['errors' => $errors])); } @@ -33,7 +30,7 @@ public function testSquareApiErrorFormatsHttpCodeAndErrorDetails(): void { ], ]); - $result = $this->callMethod($this->processor(), 'squareApiError', [$exception]); + $result = (new CRM_Square_Gateway($this->processorConfig()))->apiError($exception); $this->assertInstanceOf(CRM_Core_Exception::class, $result); $this->assertStringContainsString('Square API returned HTTP 400.', $result->getMessage()); @@ -46,13 +43,16 @@ public function testSquareApiErrorJoinsMultipleErrors(): void { ['category' => 'INVALID_REQUEST_ERROR', 'code' => 'ALSO_BAD', 'detail' => 'second problem'], ]); - $message = $this->callMethod($this->processor(), 'squareApiError', [$exception])->getMessage(); + $message = (new CRM_Square_Gateway($this->processorConfig()))->apiError($exception)->getMessage(); $this->assertStringContainsString('BAD_REQUEST: first problem', $message); $this->assertStringContainsString('ALSO_BAD: second problem', $message); } - public function testCallSquareTranslatesApiExceptionIntoCrmCoreException(): void { + /** + * @dataProvider checkoutEntryPointProvider + */ + public function testCardDeclineUsesCorePaymentFailureException(string $entryPoint): void { $paymentsMock = $this->createMock(PaymentsClient::class); $paymentsMock->method('create')->willThrowException( $this->apiException(400, [ @@ -66,22 +66,135 @@ public function testCallSquareTranslatesApiExceptionIntoCrmCoreException(): void $processor = $this->processorWithMockClient(['payments' => $paymentsMock]); - $this->expectException(CRM_Core_Exception::class); + $this->expectException(PaymentProcessorException::class); $this->expectExceptionMessageMatches('/CARD_DECLINED/'); - $params = ['token' => 'cnon:declined', 'amount' => '10.00']; - $processor->doPayment($params); + $params = ['token' => 'cnon:declined', 'amount' => '10.00', 'invoiceID' => 'inv-declined']; + $processor->$entryPoint($params); + } + + public static function checkoutEntryPointProvider(): array { + return [['doPayment'], ['doDirectPayment']]; + } + + public function testCardOnFileDeclineUsesCorePaymentFailureException(): void { + $cards = $this->createMock(CardsClient::class); + $exception = $this->apiException(400, [ + [ + 'category' => 'PAYMENT_METHOD_ERROR', + 'code' => 'CARD_DECLINED', + 'detail' => 'Card was declined.', + ], + ]); + $cards->method('create')->willThrowException($exception); + $processor = $this->processorWithMockClient(['cards' => $cards]); + + try { + // Recurring checkout saves the card through this same entry point. + $processor->createCardOnFile('customer-1', 'cnon:declined'); + $this->fail('A declined card must throw.'); + } + catch (PaymentProcessorException $e) { + $this->assertSame('Your card was declined. Please use a different card.', $e->getMessage()); + $this->assertSame($exception, $e->getPrevious()); + } + } + + /** + * @dataProvider nonDeclineErrorProvider + */ + public function testOtherApiFailuresDoNotTriggerPaymentFailureCleanup(int $status, string $category, string $expectedClass): void { + $exception = $this->apiException($status, [ + [ + 'category' => $category, + 'code' => 'TEST_ERROR', + 'detail' => 'Request failed.', + ], + ]); + $result = (new CRM_Square_Gateway($this->processorConfig()))->apiError($exception); + + $this->assertSame($expectedClass, get_class($result)); + $this->assertNotInstanceOf(PaymentProcessorException::class, $result); + } + + public static function nonDeclineErrorProvider(): array { + return [ + 'invalid request' => [400, 'INVALID_REQUEST_ERROR', CRM_Core_Exception::class], + 'credentials' => [401, 'AUTHENTICATION_ERROR', CRM_Core_Exception::class], + 'rate limit' => [429, 'RATE_LIMIT_ERROR', CRM_Core_Payment_SquareRetryableException::class], + 'server failure' => [503, 'API_ERROR', CRM_Core_Payment_SquareRetryableException::class], + 'uncertain payment outcome' => [500, 'PAYMENT_METHOD_ERROR', CRM_Core_Payment_SquareRetryableException::class], + ]; } - public function testCallSquareTranslatesGenericSquareExceptionIntoCrmCoreException(): void { + public function testUnconfirmedChargeKeepsTheContributionPageContributionPending(): void { $paymentsMock = $this->createMock(PaymentsClient::class); $paymentsMock->method('create')->willThrowException(new SquareException('connection timed out')); $processor = $this->processorWithMockClient(['payments' => $paymentsMock]); + $params = ['token' => 'cnon:timeout', 'amount' => '10.00', 'invoiceID' => 'inv-timeout']; + + 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']; - $this->expectException(CRM_Core_Exception::class); - $this->expectExceptionMessage('Square API request failed: connection timed out'); - $params = ['token' => 'cnon:timeout', 'amount' => '10.00']; - $processor->doPayment($params); + // 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}."); } /** @@ -89,7 +202,7 @@ public function testCallSquareTranslatesGenericSquareExceptionIntoCrmCoreExcepti */ public function testTranslateSquareCardErrorHumanMessages(string $code, string $expectedSubstring): void { $error = new Error(['category' => 'PAYMENT_METHOD_ERROR', 'code' => $code]); - $message = $this->callMethod($this->processor(), 'translateSquareCardError', [[$error]]); + $message = $this->callMethod(new CRM_Square_Customers(new CRM_Square_Gateway($this->processorConfig())), 'translateSquareCardError', [[$error]]); $this->assertStringContainsString($expectedSubstring, $message); } @@ -110,13 +223,13 @@ public function testTranslateSquareCardErrorFallsBackToDetailForUnknownCodes(): 'code' => 'SOME_NEW_CODE', 'detail' => 'A brand new failure reason.', ]); - $message = $this->callMethod($this->processor(), 'translateSquareCardError', [[$error]]); + $message = $this->callMethod(new CRM_Square_Customers(new CRM_Square_Gateway($this->processorConfig())), 'translateSquareCardError', [[$error]]); $this->assertSame('A brand new failure reason.', $message); } public function testTranslateSquareCardErrorFallsBackToGenericMessageWithNoDetail(): void { $error = new Error(['category' => 'PAYMENT_METHOD_ERROR', 'code' => 'SOME_NEW_CODE']); - $message = $this->callMethod($this->processor(), 'translateSquareCardError', [[$error]]); + $message = $this->callMethod(new CRM_Square_Customers(new CRM_Square_Gateway($this->processorConfig())), 'translateSquareCardError', [[$error]]); $this->assertSame('The card could not be processed.', $message); } 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/IdempotencyTest.php b/tests/phpunit/CRM/Core/Payment/Square/IdempotencyTest.php index 7d48bf1a..cf853411 100644 --- a/tests/phpunit/CRM/Core/Payment/Square/IdempotencyTest.php +++ b/tests/phpunit/CRM/Core/Payment/Square/IdempotencyTest.php @@ -38,10 +38,13 @@ public function testKeyDiffersByOperation(): void { } 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/MoneyConversionTest.php b/tests/phpunit/CRM/Core/Payment/Square/MoneyConversionTest.php index a2dd392c..2a5536d1 100644 --- a/tests/phpunit/CRM/Core/Payment/Square/MoneyConversionTest.php +++ b/tests/phpunit/CRM/Core/Payment/Square/MoneyConversionTest.php @@ -25,7 +25,7 @@ public function testOneTimePaymentConvertsDollarsToCents(string $dollars, int $e }); $processor = $this->processorWithMockClient(['payments' => $paymentsMock]); - $params = ['token' => 'cnon:x', 'amount' => $dollars]; + $params = ['token' => 'cnon:x', 'amount' => $dollars, 'invoiceID' => 'inv-money']; $processor->doPayment($params); $this->assertSame($expectedCents, $captured->getAmountMoney()->getAmount()); @@ -48,7 +48,10 @@ public function testZeroAmountOneTimePaymentShortCircuitsWithoutCallingSquare(): $params = ['token' => 'cnon:zero', 'amount' => '0.00']; $result = $processor->doPayment($params); - $this->assertSame($params, $result); + // Reported complete, as CRM_Core_Payment::doPayment() does for $0. + $this->assertSame('Completed', $result['payment_status']); + $this->assertSame(1, $result['payment_status_id']); + $this->assertArrayNotHasKey('trxn_id', $result); } public function testRefundRejectsZeroAmount(): void { diff --git a/tests/phpunit/CRM/Core/Payment/Square/RecurringInstallmentTest.php b/tests/phpunit/CRM/Core/Payment/Square/RecurringInstallmentTest.php new file mode 100644 index 00000000..8444206c --- /dev/null +++ b/tests/phpunit/CRM/Core/Payment/Square/RecurringInstallmentTest.php @@ -0,0 +1,532 @@ +createMock(PaymentsClient::class); + $payments->expects($this->never())->method('create'); + /** @var \Square\Subscriptions\Requests\CreateSubscriptionRequest|null $captured */ + $captured = NULL; + $subscriptions = $this->createMock(SubscriptionsClient::class); + $subscriptions->method('create')->willReturnCallback(function (CreateSubscriptionRequest $request) use (&$captured) { + $captured = $request; + return new CreateSubscriptionResponse(['subscription' => new Subscription(['id' => 'NEW-SUBSCRIPTION'])]); + }); + $client = new SquareClient(token: 'test-token', options: ['baseUrl' => 'https://example.invalid']); + $client->payments = $payments; + $client->subscriptions = $subscriptions; + $processor = new CRM_Core_Payment_Square_FakeLedgerProcessor($this->processorConfig(['id' => self::PROCESSOR_ID]), $client); + $this->seedCheckout($processor); + $processor->recurs[self::RECUR_ID]['processor_id'] = NULL; + + $params = [ + 'square_payment_token' => 'cnon:card-nonce', + 'amount' => '19.00', + 'currency' => 'USD', + 'is_recur' => 1, + 'contributionRecurID' => self::RECUR_ID, + 'contributionID' => self::SIGNUP_CONTRIBUTION_ID, + 'contactID' => 7, + 'frequency_unit' => 'day', + 'frequency_interval' => 1, + ]; + $result = $processor->doPayment($params); + + $this->assertNotNull($captured); + $this->assertNull($captured->getStartDate(), 'No start date: Square starts the subscription, and bills its first invoice, immediately.'); + $this->assertSame('ccof:card-on-file', $captured->getCardId()); + $this->assertSame('PLAN-VARIATION-1', $captured->getPlanVariationId()); + + $this->assertSame('Pending', $result['payment_status']); + $this->assertSame(2, $result['payment_status_id']); + $this->assertNull($result['trxn_id'], 'The subscription ID is not a payment ID and must not become the contribution trxn_id.'); + $this->assertSame('NEW-SUBSCRIPTION', $processor->recurs[self::RECUR_ID]['processor_id']); + $this->assertSame(2, $processor->recurs[self::RECUR_ID]['contribution_status_id'], 'The series stays Pending until its first payment is recorded.'); + } + + /** + * Test A: invoice.payment_made completes the checkout's contribution itself. + */ + public function testFirstInstallmentCompletesTheCheckoutContribution(): void { + $this->payFirstInstallment(); + + $this->assertFirstInstallmentRecordedOnce(); + $payment = reset($this->processor->payments); + $this->assertSame(19.00, $payment['total_amount']); + $this->assertSame(0, $this->invoiceSearches, 'invoice.payment_made names its subscription; no invoice search is needed.'); + } + + /** + * Test A, as the recorded sandbox webhooks deliver it: no invoice.payment_made at all. + */ + public function testFirstInstallmentIsRecordedFromPaymentUpdatedAlone(): void { + $this->squareBills(self::FIRST); + + $this->deliver($this->invoiceCreatedEvent(self::FIRST)); + $this->deliver($this->paymentUpdatedEvent(self::FIRST)); + + $this->assertFirstInstallmentRecordedOnce(); + $payment = reset($this->processor->payments); + $this->assertSame(0.93, $payment['fee_amount']); + } + + /** + * Checkouts from before this fix stored the subscription ID as the contribution's trxn_id. + */ + public function testCheckoutContributionCarryingTheSubscriptionIdIsStillCompleted(): void { + $this->processor->contributions[self::SIGNUP_CONTRIBUTION_ID]['trxn_id'] = self::SUBSCRIPTION_ID; + + $this->payFirstInstallment(); + + $this->assertFirstInstallmentRecordedOnce(); + } + + /** + * Square reports the processing fee only in a later payment.updated. + */ + public function testProcessingFeeReportedLaterIsRecorded(): void { + $this->squareBills(self::FIRST); + + $this->deliver($this->paymentUpdatedEvent(self::FIRST, 'COMPLETED', 1900, NULL)); + $this->assertSame(0.0, (float) ($this->processor->contributions[self::SIGNUP_CONTRIBUTION_ID]['fee_amount'] ?? 0)); + $this->deliver($this->paymentUpdatedEvent(self::FIRST)); + + $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']); + } + + /** + * A checkout that already sent a receipt (as webform_civicrm does) is not receipted again. + */ + public function testCheckoutAlreadyReceiptedIsNotReceiptedAgain(): void { + $this->processor->contributions[self::SIGNUP_CONTRIBUTION_ID]['receipt_date'] = '2026-09-23 16:45:50'; + + $this->payFirstInstallment(); + + $this->assertFalse(reset($this->processor->payments)['send_receipt']); + } + + /** + * The recurring contribution's receipt setting is honoured. + */ + public function testFirstInstallmentHonoursTheRecurReceiptSetting(): void { + $this->processor->recurs[self::RECUR_ID]['is_email_receipt'] = 0; + + $this->payFirstInstallment(); + + $this->assertFalse(reset($this->processor->payments)['send_receipt']); + } + + /** + * Test B: replays of either event record nothing further. + */ + public function testReplaysRecordNothingFurther(): void { + $this->payFirstInstallment(); + + $this->deliver($this->invoicePaymentMadeEvent(self::FIRST)); + $this->deliver($this->paymentUpdatedEvent(self::FIRST)); + $this->deliver($this->paymentUpdatedEvent(self::FIRST)); + $this->deliver($this->invoicePaymentMadeEvent(self::FIRST)); + + $this->assertFirstInstallmentRecordedOnce(); + } + + /** + * Test B: a replay after the installment was refunded is still a no-op. + * + * The recorded payment, not the contribution's current status, is what + * says the Square payment was already processed. + */ + public function testReplayAfterARefundRecordsNothingFurther(): void { + $this->payFirstInstallment(); + $this->processor->contributions[self::SIGNUP_CONTRIBUTION_ID]['status'] = 'Refunded'; + + $this->deliver($this->paymentUpdatedEvent(self::FIRST)); + $this->deliver($this->invoicePaymentMadeEvent(self::FIRST)); + + $this->assertCount(1, $this->seriesContributions()); + $this->assertCount(1, $this->processor->payments); + $this->assertSame('Refunded', $this->processor->contributions[self::SIGNUP_CONTRIBUTION_ID]['status']); + } + + /** + * Test C: webhook orderings that must not create a duplicate. + * + * @dataProvider webhookOrderProvider + */ + public function testNoWebhookOrderCreatesADuplicate(array $order): void { + $this->squareBills(self::FIRST); + $events = [ + 'invoice.created' => $this->invoiceCreatedEvent(self::FIRST), + 'payment.updated' => $this->paymentUpdatedEvent(self::FIRST), + 'invoice.payment_made' => $this->invoicePaymentMadeEvent(self::FIRST), + ]; + + foreach ($order as $type) { + $this->deliver($events[$type]); + } + + $this->assertFirstInstallmentRecordedOnce(); + } + + public static function webhookOrderProvider(): array { + $orders = [ + ['invoice.created', 'payment.updated', 'invoice.payment_made'], + ['payment.updated', 'invoice.created', 'invoice.payment_made'], + ['invoice.payment_made', 'payment.updated', 'invoice.created'], + ]; + $cases = []; + foreach ($orders as $order) { + $cases[implode(', ', $order)] = [$order]; + } + return $cases; + } + + /** + * Invoice.created is never evidence of payment, and never creates a contribution. + */ + public function testInvoiceCreatedRecordsNothing(): void { + $this->deliver($this->invoiceCreatedEvent(self::FIRST)); + $this->deliver($this->invoiceCreatedEvent(self::SECOND)); + + $this->assertCount(1, $this->seriesContributions()); + $this->assertSame('Pending', $this->processor->contributions[self::SIGNUP_CONTRIBUTION_ID]['status']); + $this->assertSame([], $this->processor->payments); + } + + /** + * Test C: a payment arriving before checkout has linked the subscription is retried. + */ + public function testPaymentBeforeTheSubscriptionIsLinkedIsRetriedNotDuplicated(): void { + $this->squareBills(self::FIRST); + $this->processor->recurs[self::RECUR_ID]['processor_id'] = NULL; + + try { + $this->deliver($this->paymentUpdatedEvent(self::FIRST)); + $this->fail('Expected the event to be deferred for retry.'); + } + catch (CRM_Core_Payment_SquareRetryableException $e) { + $this->assertStringContainsString(self::SUBSCRIPTION_ID, $e->getMessage()); + } + $this->assertCount(1, $this->processor->contributions); + $this->assertSame([], $this->processor->payments); + $this->assertSame([], $this->processor->createCalls); + + // The checkout finishes saving; the retry records the installment. + $this->processor->recurs[self::RECUR_ID]['processor_id'] = self::SUBSCRIPTION_ID; + $this->deliver($this->paymentUpdatedEvent(self::FIRST)); + + $this->assertFirstInstallmentRecordedOnce(); + } + + /** + * Test C: a recent card-on-file charge Square has no invoice for yet is retried, not imported. + */ + public function testUnmatchedCardOnFileChargeIsRetriedNotImported(): void { + $this->expectException(CRM_Core_Payment_SquareRetryableException::class); + try { + $this->deliver($this->paymentUpdatedEvent(self::FIRST)); + } + finally { + $this->assertSame([], $this->processor->createCalls, 'No standalone contribution may be created for it.'); + $this->assertSame([], $this->processor->payments); + } + } + + /** + * A payment that is not complete records nothing, and costs no Square lookup. + */ + public function testIncompletePaymentRecordsNothing(): void { + $this->squareBills(self::FIRST); + + $this->deliver($this->paymentUpdatedEvent(self::FIRST, 'APPROVED')); + + $this->assertSame([], $this->processor->payments); + $this->assertSame('Pending', $this->processor->contributions[self::SIGNUP_CONTRIBUTION_ID]['status']); + $this->assertSame(0, $this->invoiceSearches); + } + + /** + * Test D: later installments are new contributions, via repeattransaction. + * + * @dataProvider secondInstallmentEventProvider + */ + public function testSecondInstallmentCreatesAndCompletesANewContribution(string $eventType): void { + $this->payFirstInstallment(); + $firstBefore = $this->processor->contributions[self::SIGNUP_CONTRIBUTION_ID]; + + $this->squareBills(self::SECOND); + $this->deliver($eventType === 'invoice.payment_made' + ? $this->invoicePaymentMadeEvent(self::SECOND) + : $this->paymentUpdatedEvent(self::SECOND)); + + $this->assertSame($firstBefore, $this->processor->contributions[self::SIGNUP_CONTRIBUTION_ID], 'The first contribution is unchanged.'); + $this->assertCount(2, $this->seriesContributions()); + $this->assertCount(1, $this->processor->repeatCalls); + $this->assertSame('Pending', $this->processor->repeatCalls[0]['contribution_status'], 'Created Pending, then completed by Payment.create.'); + $this->assertSame(self::SECOND['invoice_id'], $this->processor->repeatCalls[0]['invoice_id']); + + $second = $this->contributionWithTrxnId(self::SECOND['payment_id']); + $this->assertNotSame(self::SIGNUP_CONTRIBUTION_ID, $second['id']); + $this->assertSame(self::RECUR_ID, $second['contribution_recur_id']); + $this->assertSame('Completed', $second['status']); + $this->assertSame([self::FIRST['payment_id'], self::SECOND['payment_id']], array_column($this->processor->payments, 'trxn_id')); + $this->assertSame($second['id'], end($this->processor->payments)['contribution_id']); + $this->assertFalse(end($this->processor->payments)['send_receipt'], 'Later installments are not receipted, as before.'); + $this->assertSame([], $this->processor->createCalls, 'Installments never use a bare Contribution.create.'); + + // Replays of the second installment record nothing further either. + $this->deliver($this->invoicePaymentMadeEvent(self::SECOND)); + $this->deliver($this->paymentUpdatedEvent(self::SECOND)); + $this->assertCount(2, $this->seriesContributions()); + $this->assertCount(2, $this->processor->payments); + } + + public static function secondInstallmentEventProvider(): array { + return [ + 'invoice.payment_made' => ['invoice.payment_made'], + 'payment.updated' => ['payment.updated'], + ]; + } + + /** + * Test E: an amount mismatch is raised, never written into CiviCRM. + */ + public function testFirstInstallmentAmountMismatchIsNotRecorded(): void { + $this->squareBills(self::FIRST, 2000); + + try { + $this->deliver($this->invoicePaymentMadeEvent(self::FIRST, 2000)); + $this->fail('Expected a reconciliation error.'); + } + catch (CRM_Core_Exception $e) { + $this->assertNotInstanceOf(CRM_Core_Payment_SquareRetryableException::class, $e, 'A mismatch needs a person, not a retry.'); + $this->assertStringContainsString('manual reconciliation', $e->getMessage()); + } + + $contribution = $this->processor->contributions[self::SIGNUP_CONTRIBUTION_ID]; + $this->assertSame('Pending', $contribution['status']); + $this->assertSame(19.00, $contribution['total_amount']); + $this->assertSame('USD', $contribution['currency']); + $this->assertNull($contribution['trxn_id'], 'Not claimed by the mismatched payment.'); + $this->assertSame([], $this->processor->payments); + if (property_exists(Civi::class, 'logged')) { + $this->assertContains('error', array_column(Civi::$logged, 0)); + } + } + + /** + * Test E, for a later installment: no contribution is created for it. + */ + public function testLaterInstallmentAmountMismatchCreatesNothing(): void { + $this->payFirstInstallment(); + $this->squareBills(self::SECOND, 2000); + + try { + $this->deliver($this->paymentUpdatedEvent(self::SECOND, 'COMPLETED', 2000)); + $this->fail('Expected a reconciliation error.'); + } + catch (CRM_Core_Exception $e) { + $this->assertStringContainsString('manual reconciliation', $e->getMessage()); + } + $this->assertSame([], $this->processor->repeatCalls); + $this->assertCount(1, $this->seriesContributions()); + $this->assertCount(1, $this->processor->payments); + } + + /** + * Test F: a webhook for one Square processor never touches another's records. + * + * @dataProvider otherProcessorProvider + */ + public function testWebhookForAnotherProcessorTouchesNothing(array $configOverrides): void { + $this->squareBills(self::FIRST); + $other = $this->ledgerProcessor($configOverrides); + $this->seedCheckout($other); + // Its records belong to processor 42 (live); this one is someone else. + $recursBefore = $other->recurs; + $contributionsBefore = $other->contributions; + + try { + $this->deliverTo($other, $this->invoicePaymentMadeEvent(self::FIRST)); + } + catch (CRM_Core_Payment_SquareRetryableException $e) { + // A recent event for an unknown subscription is retried; either way + // nothing is recorded. + } + + $this->assertSame($recursBefore, $other->recurs); + $this->assertSame($contributionsBefore, $other->contributions); + $this->assertSame([], $other->payments); + $this->assertSame([], $other->repeatCalls); + } + + public static function otherProcessorProvider(): array { + return [ + 'another processor' => [['id' => 43]], + 'the sandbox processor' => [['id' => 43, 'is_test' => TRUE]], + ]; + } + + /** + * A failed first charge leaves the checkout's contribution Pending — no Failed duplicate. + */ + public function testFailedFirstChargeKeepsTheCheckoutContributionPending(): void { + $this->deliver($this->invoiceScheduledChargeFailedEvent(self::FIRST)); + + $this->assertCount(1, $this->seriesContributions()); + $this->assertSame('Pending', $this->processor->contributions[self::SIGNUP_CONTRIBUTION_ID]['status']); + $this->assertSame([], $this->processor->repeatCalls); + + // Square collects the invoice later. + $this->payFirstInstallment(); + $this->assertFirstInstallmentRecordedOnce(); + } + + /** + * A later installment that failed, then was collected, is completed — not duplicated. + */ + public function testFailedLaterInstallmentIsCompletedWhenCollected(): void { + $this->payFirstInstallment(); + + $this->deliver($this->invoiceScheduledChargeFailedEvent(self::SECOND)); + $this->assertCount(2, $this->seriesContributions()); + $failed = $this->seriesContributions()[1]; + $this->assertSame('Failed', $failed['status']); + $this->assertSame(self::SECOND['invoice_id'], $failed['invoice_id']); + + $this->squareBills(self::SECOND); + $this->deliver($this->invoicePaymentMadeEvent(self::SECOND)); + + $this->assertCount(2, $this->seriesContributions()); + $this->assertCount(1, $this->processor->repeatCalls, 'Only the failed attempt was created; the payment completed it.'); + $this->assertSame('Completed', $this->processor->contributions[$failed['id']]['status']); + $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. + */ + public function testCanceledOneTimePaymentMarksItsPendingContributionFailed(): void { + $this->processor->contributions[300] = [ + 'id' => 300, + 'contribution_recur_id' => NULL, + 'status' => 'Pending', + 'total_amount' => 25.00, + 'currency' => 'USD', + 'trxn_id' => 'ONE-TIME-PAYMENT', + 'invoice_id' => 'civicrm-invoice-300', + ]; + $event = $this->paymentUpdatedEvent(['payment_id' => 'ONE-TIME-PAYMENT', 'order_id' => 'ORDER-300'], 'CANCELED', 2500); + $event['data']['object']['payment']['reference_id'] = 'civicrm-invoice-300'; + + $this->deliver($event); + + $this->assertSame('Failed', $this->processor->contributions[300]['status']); + $this->assertSame([], $this->processor->payments); + $this->assertSame(0, $this->invoiceSearches); + } + + /** + * An invoice that is not fully paid yet records nothing. + */ + public function testInvoicePaymentMadeForAPartiallyPaidInvoiceRecordsNothing(): void { + $this->squareBills(self::FIRST); + $event = $this->invoicePaymentMadeEvent(self::FIRST); + $event['data']['object']['invoice']['status'] = 'PARTIALLY_PAID'; + + $this->deliver($event); + + $this->assertSame([], $this->processor->payments); + $this->assertSame('Pending', $this->processor->contributions[self::SIGNUP_CONTRIBUTION_ID]['status']); + } + + /** + * The first installment completed the checkout contribution, exactly once. + */ + private function assertFirstInstallmentRecordedOnce(): void { + $series = $this->seriesContributions(); + $this->assertCount(1, $series, 'No replacement contribution may be created for the first installment.'); + $this->assertSame(self::SIGNUP_CONTRIBUTION_ID, $series[0]['id']); + $this->assertSame('Completed', $series[0]['status']); + $this->assertSame(self::FIRST['payment_id'], $series[0]['trxn_id'], 'The trxn_id is the Square payment ID alone.'); + $this->assertSame(19.00, $series[0]['total_amount']); + $this->assertSame([], $this->processor->repeatCalls); + $this->assertSame([], $this->processor->createCalls); + + $this->assertCount(1, $this->processor->payments); + $payment = reset($this->processor->payments); + $this->assertSame(self::FIRST['payment_id'], $payment['trxn_id']); + $this->assertSame(self::SIGNUP_CONTRIBUTION_ID, $payment['contribution_id']); + $this->assertSame(self::PROCESSOR_ID, $payment['payment_processor_id']); + $this->assertTrue($payment['send_receipt'], "Receipts follow the recurring contribution's is_email_receipt."); + + $this->assertSame(5, $this->processor->recurs[self::RECUR_ID]['contribution_status_id'], 'The series is In Progress once its first payment is recorded.'); + } + + /** + * @param string $trxnId + * + * @return array + */ + private function contributionWithTrxnId(string $trxnId): array { + foreach ($this->processor->contributions as $row) { + if ($row['trxn_id'] === $trxnId) { + return $row; + } + } + $this->fail("No contribution has trxn_id {$trxnId}."); + } + +} diff --git a/tests/phpunit/CRM/Core/Payment/Square/RefundTest.php b/tests/phpunit/CRM/Core/Payment/Square/RefundTest.php new file mode 100644 index 00000000..11862953 --- /dev/null +++ b/tests/phpunit/CRM/Core/Payment/Square/RefundTest.php @@ -0,0 +1,379 @@ +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 { + $this->deliver($this->refundEvent('refund.created', 'PENDING', 1900)); + + $this->assertSame([], $this->refunds()); + $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. + */ + public function testFullRefundCancelsTheRefundedPayment(): void { + $this->deliver($this->refundEvent('refund.updated', 'COMPLETED', 1900)); + + $refunds = $this->refunds(); + $this->assertCount(1, $refunds); + $refund = reset($refunds); + $this->assertSame(-19.00, $refund['total_amount']); + $this->assertSame(self::REFUND_ID, $refund['trxn_id']); + $this->assertSame(self::SIGNUP_CONTRIBUTION_ID, $refund['contribution_id']); + $this->assertSame($this->originalPaymentId(), $refund['cancelled_payment_id']); + $this->assertSame(self::PROCESSOR_ID, $refund['payment_processor_id']); + $this->assertSame('Refunded', $this->processor->contributions[self::SIGNUP_CONTRIBUTION_ID]['status']); + } + + /** + * A partial one is not linked: that would reverse the whole payment's allocations. + */ + public function testPartialRefundIsNotLinkedToTheRefundedPayment(): void { + $this->deliver($this->refundEvent('refund.updated', 'COMPLETED', 500)); + + $refunds = $this->refunds(); + $this->assertCount(1, $refunds); + $refund = reset($refunds); + $this->assertSame(-5.00, $refund['total_amount']); + $this->assertArrayNotHasKey('cancelled_payment_id', $refund); + $this->assertSame('Completed', $this->processor->contributions[self::SIGNUP_CONTRIBUTION_ID]['status']); + } + + /** + * Square can report the same completed refund in both events. + */ + public function testRefundReportedTwiceIsRecordedOnce(): void { + $this->deliver($this->refundEvent('refund.created', 'COMPLETED', 1900)); + $this->deliver($this->refundEvent('refund.updated', 'COMPLETED', 1900)); + + $this->assertCount(1, $this->refunds()); + } + + /** + * Staff already recorded it when refunding from CiviCRM (with Square's refund ID). + */ + public function testRefundAlreadyRecordedFromCiviCrmIsSkipped(): 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', 'COMPLETED', 1900)); + + $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); + } + + /** + * @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, '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']); + } + + /** + * Another Square processor's webhook cannot refund this processor's payment. + */ + public function testRefundForAnotherProcessorTouchesNothing(): void { + $other = $this->ledgerProcessor(['id' => 43]); + $other->contributions = $this->processor->contributions; + // Recorded by processor 42, not 43. + $other->payments = $this->processor->payments; + + $this->deliverTo($other, $this->refundEvent('refund.updated', 'COMPLETED', 1900)); + + $this->assertSame($this->processor->payments, $other->payments, 'No refund recorded against a payment of processor 42.'); + } + + /** + * A payment recorded before payments carried a processor is still refunded. + */ + public function testRefundOfAPaymentRecordedWithoutAProcessor(): void { + $this->processor->contributions[300] = [ + 'id' => 300, + 'contribution_recur_id' => NULL, + 'status' => 'Completed', + 'total_amount' => 25.00, + 'currency' => 'USD', + 'trxn_id' => 'LEGACY-PAYMENT', + 'invoice_id' => NULL, + ]; + $this->processor->payments[850] = [ + 'contribution_id' => 300, + 'trxn_id' => 'LEGACY-PAYMENT', + 'total_amount' => 25.00, + 'payment_processor_id' => NULL, + ]; + $event = $this->refundEvent('refund.updated', 'COMPLETED', 2500); + $event['data']['object']['refund']['payment_id'] = 'LEGACY-PAYMENT'; + + $this->deliver($event); + + $refunds = $this->refunds(); + $this->assertCount(1, $refunds); + $refund = reset($refunds); + $this->assertSame(300, $refund['contribution_id']); + $this->assertSame(850, $refund['cancelled_payment_id']); + } + + /** + * Refund rows (negative payments) in the ledger. + * + * @return array + */ + private function refunds(): array { + return array_filter($this->processor->payments, fn (array $payment) => $payment['total_amount'] < 0); + } + + /** + * ID of the payment recorded for the first installment. + * + * @return int + */ + private function originalPaymentId(): int { + foreach ($this->processor->payments as $id => $payment) { + if ($payment['trxn_id'] === self::FIRST['payment_id']) { + return $id; + } + } + $this->fail('The first installment was not recorded.'); + } + + /** + * A refund webhook for the first installment's payment. + * + * @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, 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)), + 'data' => [ + 'type' => 'refund', + 'object' => [ + 'refund' => [ + 'id' => self::REFUND_ID, + 'payment_id' => $paymentId, + 'status' => $status, + 'amount_money' => ['amount' => $amountCents, 'currency' => 'USD'], + 'created_at' => $now, + 'updated_at' => $now, + ], + ], + ], + ]; + } + +} diff --git a/tests/phpunit/CRM/Core/Payment/Square/RequestShapeTest.php b/tests/phpunit/CRM/Core/Payment/Square/RequestShapeTest.php index 43ac34eb..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); @@ -65,37 +83,151 @@ public function testOneTimePaymentOmitsReferenceIdWhenNoInvoiceId(): void { }); $processor = $this->processorWithMockClient(['payments' => $paymentsMock]); - $params = ['token' => 'cnon:no-invoice', 'amount' => '5.00']; + $params = ['token' => 'cnon:no-invoice', 'amount' => '5.00', 'contributionID' => 17]; $processor->doPayment($params); $this->assertNull($captured->getReferenceId()); } + public function testOneTimePaymentFailsClosedWithoutACheckoutReference(): void { + $paymentsMock = $this->createMock(PaymentsClient::class); + $paymentsMock->expects($this->never())->method('create'); + + $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, + // 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 { + $paymentsMock = $this->createMock(PaymentsClient::class); + $paymentsMock->method('create')->willReturn( + new CreatePaymentResponse(['payment' => new Payment(['id' => 'pay_held', 'status' => 'APPROVED'])]) + ); + + $processor = $this->processorWithMockClient(['payments' => $paymentsMock]); + $params = ['token' => 'cnon:held', 'amount' => '5.00', 'invoiceID' => 'inv-held']; + $result = $processor->doPayment($params); + + $this->assertSame('Pending', $result['payment_status']); + $this->assertSame(2, $result['payment_status_id']); + $this->assertSame('pay_held', $result['trxn_id']); + } + 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) { @@ -104,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()); @@ -124,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 new file mode 100644 index 00000000..efb9c5f0 --- /dev/null +++ b/tests/phpunit/CRM/Core/Payment/Square/SquareLedgerTestCase.php @@ -0,0 +1,908 @@ +mockClient = $mockClient; + } + + /** + * Allocate the next record ID. + * + * @return int + */ + public function nextId(): int { + // Past every existing ID, including records a test copied in. + $this->nextId = max([$this->nextId, ...array_keys($this->contributions), ...array_keys($this->payments)]) + 1; + return $this->nextId; + } + + /** + * @return \Square\SquareClient + */ + protected function buildSquareClient(): SquareClient { + return $this->mockClient; + } + + /** + * @return \CRM_Square_Reconciler + */ + protected function reconciler(): CRM_Square_Reconciler { + return new CRM_Core_Payment_Square_FakeLedgerReconciler($this->gateway(), $this); + } + + /** + * @return \CRM_Square_Customers + */ + protected function customers(): CRM_Square_Customers { + return new class($this->gateway()) extends CRM_Square_Customers { + + /** + * @param array $params + * + * @return string + */ + public function ensureSquareCustomer(array $params) { + return 'CUSTOMER-1'; + } + + /** + * @param string $customerID + * @param array $params + */ + public function updateSquareCustomerDetails($customerID, $params) { + } + + }; + } + + /** + * @return \CRM_Square_Subscriptions + */ + protected function subscriptions(): CRM_Square_Subscriptions { + return new class($this->gateway()) extends CRM_Square_Subscriptions { + + /** + * @param array $params + * + * @return string + */ + public function getPlanVariationIdForParams(array $params): string { + return 'PLAN-VARIATION-1'; + } + + }; + } + + /** + * @param int $recurId + * + * @return string|null + */ + protected function getRecurCardId(int $recurId): ?string { + return $this->recurCardId; + } + + /** + * @param int $recurId + * @param string $subscriptionId + */ + protected function saveRecurSubscription(int $recurId, string $subscriptionId): void { + $this->recurs[$recurId]['processor_id'] = $subscriptionId; + $this->recurs[$recurId]['contribution_status_id'] = 2; + } + +} + +/** + * CRM_Square_Reconciler whose CiviCRM persistence is its ledger's arrays. + * + * Only the persistence seams are replaced; all reconciliation logic under + * test is the real class's. Each seam mimics the CiviCRM behaviour the + * logic relies on: processor and test-mode scoping, Payment.create + * appending its trxn_id and moving a Pending series to In Progress, and the + * unique trxn_id/invoice_id indexes on contributions. + */ +class CRM_Core_Payment_Square_FakeLedgerReconciler extends CRM_Square_Reconciler { + + /** + * CiviCRM's default contribution statuses (see tests/phpunit/bootstrap.php). + */ + private const STATUS_NAMES = [ + 1 => 'Completed', + 2 => 'Pending', + 3 => 'Cancelled', + 4 => 'Failed', + 5 => 'In Progress', + 7 => 'Refunded', + ]; + + /** + * The processor holding the fake ledger. + * + * @var \CRM_Core_Payment_Square_FakeLedgerProcessor + */ + private CRM_Core_Payment_Square_FakeLedgerProcessor $ledger; + + /** + * @param \CRM_Square_Gateway $gateway + * @param \CRM_Core_Payment_Square_FakeLedgerProcessor $ledger + */ + public function __construct(CRM_Square_Gateway $gateway, CRM_Core_Payment_Square_FakeLedgerProcessor $ledger) { + parent::__construct($gateway); + $this->ledger = $ledger; + } + + /** + * @param string $key + * + * @return object + */ + protected function acquireSquareLock(string $key) { + return new class() { + + /** + * Nothing to release. + */ + public function release(): void { + } + + }; + } + + /** + * @param string $subscriptionId + * + * @return array|null + */ + protected function findRecurBySubscriptionId(string $subscriptionId): ?array { + foreach ($this->ledger->recurs as $recur) { + if ($recur['processor_id'] === $subscriptionId + && $recur['payment_processor_id'] === $this->gateway->processorId() + && (bool) $recur['is_test'] === $this->gateway->isTestMode()) { + return $recur; + } + } + 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 + * + * @return array + */ + protected function getRecurContributions(int $recurId): array { + $rows = array_filter($this->ledger->contributions, fn (array $row) => $row['contribution_recur_id'] === $recurId && empty($row['is_template'])); + ksort($rows); + return array_values(array_map([$this, 'publicRow'], $rows)); + } + + /** + * @param string $paymentId + * @param string|null $referenceId + * + * @return array|null + */ + protected function findContributionForSquarePayment(string $paymentId, ?string $referenceId): ?array { + foreach ($this->ledger->contributions as $row) { + if (empty($row['contribution_recur_id']) + && ($row['trxn_id'] === $paymentId || ($referenceId && $row['invoice_id'] === $referenceId))) { + return $this->publicRow($row); + } + } + return NULL; + } + + /** + * @param string $trxnId + * + * @return array|null + */ + protected function findRecordedPayment(string $trxnId): ?array { + foreach ($this->ledger->payments as $id => $payment) { + if ($payment['trxn_id'] === $trxnId && $payment['payment_processor_id'] === $this->gateway->processorId()) { + return [ + 'id' => $id, + 'contribution_id' => $payment['contribution_id'], + 'total_amount' => $payment['total_amount'], + ]; + } + } + return NULL; + } + + /** + * @param int $contributionId + * @param array $values + * @param bool $sendReceipt + */ + protected function recordContributionPayment(int $contributionId, array $values, bool $sendReceipt): void { + $contribution = &$this->ledger->contributions[$contributionId]; + if ($contribution['status'] === 'Completed') { + // CiviCRM would silently record an overpayment. + throw new LogicException("A second payment was recorded on Completed contribution {$contributionId}."); + } + $this->ledger->payments[$this->ledger->nextId()] = $values + [ + 'contribution_id' => $contributionId, + 'payment_processor_id' => $this->gateway->processorId(), + 'send_receipt' => $sendReceipt, + ]; + + // Payment.create appends its trxn_id to the contribution's. + $trxnIds = array_filter(explode(',', (string) $contribution['trxn_id'])); + if (!in_array($values['trxn_id'], $trxnIds, TRUE)) { + $trxnIds[] = $values['trxn_id']; + } + $this->assertUnique($contributionId, 'trxn_id', implode(',', $trxnIds)); + $contribution['trxn_id'] = implode(',', $trxnIds); + if (isset($values['fee_amount'])) { + $contribution['fee_amount'] = $values['fee_amount']; + } + + if (round($values['total_amount'], 2) >= round($contribution['total_amount'], 2)) { + $contribution['status'] = 'Completed'; + // CRM_Contribute_BAO_ContributionRecur::updateOnNewPayment(). + $recurId = $contribution['contribution_recur_id']; + if ($recurId && $this->ledger->recurs[$recurId]['contribution_status_id'] === 2) { + $this->ledger->recurs[$recurId]['contribution_status_id'] = 5; + } + } + } + + /** + * @param array $recur + * @param array $values + * + * @return array + */ + protected function repeatRecurContribution(array $recur, array $values): array { + $this->ledger->repeatCalls[] = $values; + $recurId = (int) $recur['id']; + // The template is the series' latest contribution, whatever its status. + $series = array_filter($this->ledger->contributions, fn (array $row) => $row['contribution_recur_id'] === $recurId); + ksort($series); + $template = end($series) ?: []; + + $id = $this->ledger->nextId(); + $this->assertUnique($id, 'trxn_id', $values['trxn_id'] ?? NULL); + $this->assertUnique($id, 'invoice_id', $values['invoice_id'] ?? NULL); + $this->ledger->contributions[$id] = [ + 'id' => $id, + 'contribution_recur_id' => $recurId, + 'status' => $values['contribution_status'], + 'total_amount' => (float) $recur['amount'], + 'currency' => $recur['currency'], + 'trxn_id' => $values['trxn_id'] ?? NULL, + 'invoice_id' => $values['invoice_id'] ?? NULL, + 'financial_type_id' => $template['financial_type_id'] ?? NULL, + ]; + return $this->publicRow($this->ledger->contributions[$id]); + } + + /** + * @param int $contributionId + * + * @return float + */ + protected function getContributionFeeAmount(int $contributionId): float { + return (float) ($this->ledger->contributions[$contributionId]['fee_amount'] ?? 0); + } + + /** + * @param int $contributionId + * @param array $values + */ + protected function updateContribution(int $contributionId, array $values): void { + if (isset($values['contribution_status_id'])) { + $values['status'] = self::STATUS_NAMES[$values['contribution_status_id']]; + unset($values['contribution_status_id']); + } + foreach (['trxn_id', 'invoice_id'] as $field) { + if (array_key_exists($field, $values)) { + $this->assertUnique($contributionId, $field, $values[$field]); + } + } + $this->ledger->contributions[$contributionId] = $values + $this->ledger->contributions[$contributionId]; + } + + /** + * @param array $values + * + * @return int + */ + protected function createContribution(array $values): int { + $this->ledger->createCalls[] = $values; + $id = $this->ledger->nextId(); + $this->ledger->contributions[$id] = [ + 'id' => $id, + 'contribution_recur_id' => NULL, + 'status' => self::STATUS_NAMES[$values['contribution_status_id']], + 'total_amount' => (float) $values['total_amount'], + 'currency' => $values['currency'], + 'trxn_id' => $values['trxn_id'] ?? NULL, + 'invoice_id' => NULL, + ]; + return $id; + } + + /** + * @param array $payment + * + * @return int|null + */ + protected function findContactIdForPayment(array $payment) { + return 7; + } + + /** + * @param string $trxnId + * + * @return int|null + */ + protected function findContributionIdByTrxnId(string $trxnId): ?int { + foreach ($this->ledger->contributions as $id => $row) { + if (in_array($trxnId, explode(',', (string) ($row['trxn_id'] ?? '')), TRUE)) { + return $id; + } + } + return NULL; + } + + /** + * @param int $contributionId + * @param string $trxnId + * + * @return array|null + */ + protected function findContributionPayment(int $contributionId, string $trxnId): ?array { + foreach ($this->ledger->payments as $id => $payment) { + if ($payment['contribution_id'] === $contributionId && $payment['trxn_id'] === $trxnId) { + return [ + 'id' => $id, + 'total_amount' => $payment['total_amount'], + 'payment_processor_id' => $payment['payment_processor_id'] ?? NULL, + ]; + } + } + 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 + */ + protected function recordRefundPayment(array $params): void { + $contributionId = $params['contribution_id']; + $this->ledger->payments[$this->ledger->nextId()] = $params + ['send_receipt' => FALSE]; + // CRM_Financial_BAO_Payment::create(): Refunded once nothing paid remains. + $paid = array_sum(array_column(array_filter($this->ledger->payments, fn (array $payment) => $payment['contribution_id'] === $contributionId), 'total_amount')); + if (round($paid, 2) <= 0) { + $this->ledger->contributions[$contributionId]['status'] = 'Refunded'; + } + } + + /** + * Mimic the unique trxn_id/invoice_id indexes on civicrm_contribution. + * + * @param int $contributionId + * @param string $field + * @param string|null $value + */ + private function assertUnique(int $contributionId, string $field, ?string $value): void { + if ($value === NULL || $value === '') { + return; + } + foreach ($this->ledger->contributions as $id => $row) { + if ($id !== $contributionId && ($row[$field] ?? NULL) === $value) { + throw new RuntimeException("Duplicate {$field} {$value} (contribution {$id})."); + } + } + } + + /** + * The row shape getRecurContributions() and friends return. + * + * @param array $row + * + * @return array + */ + private function publicRow(array $row): array { + $fields = ['id', 'status', 'total_amount', 'currency', 'trxn_id', 'invoice_id', 'receipt_date']; + return array_intersect_key($row, array_flip($fields)); + } + +} + +/** + * Shared fixtures for recurring-installment reconciliation tests. + * + * Fixtures are modelled on the Square sandbox webhooks recorded in + * civicrm_paymentprocessor_webhook for a DAILY 19.00 USD subscription: + * invoice.created (still DRAFT) followed by payment.updated for the payment + * that paid it, linked only through the invoice's order_id. + */ +abstract class CRM_Core_Payment_Square_SquareLedgerTestCase extends CRM_Core_Payment_Square_SquareUnitTestCase { + + protected const PROCESSOR_ID = 42; + + protected const SUBSCRIPTION_ID = '4e6e5d41-a071-4e47-be68-087138ea360a'; + + protected const CUSTOMER_ID = 'PAGRJWQKJH1E11PCR7KG7SKTY8'; + + protected const LOCATION_ID = 'L6Z22RREK6NGN'; + + protected const RECUR_ID = 45; + + protected const SIGNUP_CONTRIBUTION_ID = 123; + + /** + * The first installment's Square invoice, order and payment. + */ + protected const FIRST = [ + 'invoice_id' => 'inv:0-ChAsOc2tUbZgeioE6TokE6ODEIgK', + 'order_id' => 'thVIfFwfL8yeD6fM94dvotSh2c4F', + 'payment_id' => 'VM5iP66yfHWI3UEIJWmbEAEzrrBZY', + ]; + + /** + * The second installment's Square invoice, order and payment. + */ + protected const SECOND = [ + 'invoice_id' => 'inv:0-ChAIcc-Uqf-MREOs4fwUEwthEIgK', + 'order_id' => 'X4awkGmhfaQe3C7Z4g4o0esoje4F', + 'payment_id' => 'n1xYKpEvBD0QyjdHt4l7WW7sgBgZY', + ]; + + /** + * Square invoices returned by the mocked invoices->search. + * + * @var \Square\Types\Invoice[] + */ + 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. + * + * @var \Square\Types\Order[] + */ + protected array $squareOrders = []; + + /** + * Number of invoices->search calls made. + * + * @var int + */ + protected int $invoiceSearches = 0; + + /** + * @var \CRM_Core_Payment_Square_FakeLedgerProcessor + */ + protected CRM_Core_Payment_Square_FakeLedgerProcessor $processor; + + /** + * Reset the log and build a processor seeded like a fresh checkout. + */ + protected function setUp(): void { + parent::setUp(); + // Only the stand-in Civi (tests/phpunit/bootstrap.php) records log calls. + if (property_exists(Civi::class, 'logged')) { + Civi::$logged = []; + } + $this->processor = $this->ledgerProcessor(); + $this->seedCheckout($this->processor); + } + + /** + * A fake-ledger processor whose Square invoices/orders clients are mocked. + * + * @param array $configOverrides + * + * @return \CRM_Core_Payment_Square_FakeLedgerProcessor + */ + protected function ledgerProcessor(array $configOverrides = []): CRM_Core_Payment_Square_FakeLedgerProcessor { + $invoices = $this->createMock(InvoicesClient::class); + $invoices->method('search')->willReturnCallback(function () { + $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); + } + + /** + * What CiviCRM's checkout leaves behind once doRecurPayment() returns. + * + * @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, + 'amount' => 19.00, + 'currency' => 'USD', + 'processor_id' => self::SUBSCRIPTION_ID, + 'payment_processor_id' => self::PROCESSOR_ID, + 'is_test' => FALSE, + 'contribution_status_id' => 2, + 'is_email_receipt' => 1, + ]; + $processor->contributions[self::SIGNUP_CONTRIBUTION_ID] = [ + 'id' => self::SIGNUP_CONTRIBUTION_ID, + 'contribution_recur_id' => self::RECUR_ID, + 'status' => 'Pending', + 'total_amount' => 19.00, + 'currency' => 'USD', + 'trxn_id' => NULL, + // CiviCRM's own invoice reference, set at checkout. + 'invoice_id' => 'b6f1a5c6a8f04c7e9c1d2e3f4a5b6c7d', + 'financial_type_id' => 2, + ]; + } + + /** + * Make an installment's invoice and order visible at (mocked) Square. + * + * @param array $installment + * self::FIRST or self::SECOND. + * @param int $amountCents + */ + protected function squareBills(array $installment, int $amountCents = 1900): void { + $this->squareInvoices[$installment['invoice_id']] = new Invoice([ + 'id' => $installment['invoice_id'], + 'orderId' => $installment['order_id'], + 'subscriptionId' => self::SUBSCRIPTION_ID, + 'locationId' => self::LOCATION_ID, + 'status' => 'PAID', + ]); + $this->squareOrders[$installment['order_id']] = new Order([ + 'id' => $installment['order_id'], + 'locationId' => self::LOCATION_ID, + 'tenders' => [ + new Tender([ + 'type' => 'CARD', + 'paymentId' => $installment['payment_id'], + 'amountMoney' => new Money(['amount' => $amountCents, 'currency' => 'USD']), + 'createdAt' => gmdate('Y-m-d\TH:i:s\Z'), + ]), + ], + ]); + } + + /** + * An invoice.created payload, as Square sends it: DRAFT, nothing paid. + * + * @param array $installment + * + * @return array + */ + protected function invoiceCreatedEvent(array $installment): array { + return $this->invoiceEvent('invoice.created', $installment, 'DRAFT', 0); + } + + /** + * An invoice.payment_made payload. + * + * @param array $installment + * @param int $amountCents + * + * @return array + */ + protected function invoicePaymentMadeEvent(array $installment, int $amountCents = 1900): array { + return $this->invoiceEvent('invoice.payment_made', $installment, 'PAID', $amountCents); + } + + /** + * 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 invoiceScheduledChargeFailedEvent(array $installment): array { + return $this->invoiceEvent('invoice.scheduled_charge_failed', $installment, 'UNPAID', 0); + } + + /** + * A payment.updated payload, shaped like the recorded sandbox webhooks. + * + * No subscription_id and no reference_id: only order_id ties it to the + * invoice. + * + * @param array $installment + * @param string $status + * @param int $amountCents + * @param int|null $feeCents + * NULL for the first COMPLETED update, which does not report the fee. + * + * @return array + */ + protected function paymentUpdatedEvent(array $installment, string $status = 'COMPLETED', int $amountCents = 1900, ?int $feeCents = 93): array { + $now = gmdate('Y-m-d\TH:i:s\Z'); + $event = $this->event('payment.updated', [ + 'payment' => [ + 'id' => $installment['payment_id'], + 'status' => $status, + 'order_id' => $installment['order_id'], + 'customer_id' => self::CUSTOMER_ID, + 'location_id' => self::LOCATION_ID, + 'amount_money' => ['amount' => $amountCents, 'currency' => 'USD'], + 'processing_fee' => [['amount_money' => ['amount' => 93, 'currency' => 'USD'], 'type' => 'INITIAL']], + 'source_type' => 'CARD', + 'card_details' => ['entry_method' => 'ON_FILE', 'status' => 'CAPTURED'], + 'created_at' => $now, + 'updated_at' => $now, + ], + ]); + if ($feeCents === NULL) { + unset($event['data']['object']['payment']['processing_fee']); + } + else { + $event['data']['object']['payment']['processing_fee'][0]['amount_money']['amount'] = $feeCents; + } + return $event; + } + + /** + * Deliver a webhook payload through the IPN router. + * + * @param array $payload + */ + protected function deliver(array $payload): void { + $this->deliverTo($this->processor, $payload); + } + + /** + * Deliver a webhook payload through the IPN router to a given processor. + * + * @param \CRM_Core_Payment_Square $processor + * @param array $payload + */ + protected function deliverTo(CRM_Core_Payment_Square $processor, array $payload): void { + $ipn = new CRM_Core_Payment_SquareIPN($processor); + $ipn->setInputParameters($payload, $payload['type']); + $ipn->processWebhookEvent($payload, $payload['type']); + } + + /** + * Contributions of the test series. + * + * @return array + */ + protected function seriesContributions(): array { + return array_values(array_filter($this->processor->contributions, fn (array $row) => $row['contribution_recur_id'] === self::RECUR_ID)); + } + + /** + * Record the first installment, as Square's invoice.payment_made reports it. + */ + protected function payFirstInstallment(): void { + $this->squareBills(self::FIRST); + $this->deliver($this->invoicePaymentMadeEvent(self::FIRST)); + } + + /** + * @param string $type + * @param array $installment + * @param string $status + * @param int $completedCents + * + * @return array + */ + private function invoiceEvent(string $type, array $installment, string $status, int $completedCents): array { + $now = gmdate('Y-m-d\TH:i:s\Z'); + return $this->event($type, [ + 'invoice' => [ + 'id' => $installment['invoice_id'], + 'order_id' => $installment['order_id'], + 'subscription_id' => self::SUBSCRIPTION_ID, + 'location_id' => self::LOCATION_ID, + 'status' => $status, + 'primary_recipient' => ['customer_id' => self::CUSTOMER_ID], + 'payment_requests' => [ + [ + 'computed_amount_money' => ['amount' => 1900, 'currency' => 'USD'], + 'total_completed_amount_money' => ['amount' => $completedCents, 'currency' => 'USD'], + ], + ], + 'created_at' => $now, + 'updated_at' => $now, + ], + ]); + } + + /** + * @param string $type + * @param array $object + * + * @return array + */ + private function event(string $type, array $object): array { + return [ + 'type' => $type, + 'event_id' => bin2hex(random_bytes(8)), + 'data' => ['type' => array_key_first($object), 'object' => $object], + ]; + } + +} diff --git a/tests/phpunit/CRM/Core/Payment/Square/SquareUnitTestCase.php b/tests/phpunit/CRM/Core/Payment/Square/SquareUnitTestCase.php index 6363bacb..4f24e4be 100644 --- a/tests/phpunit/CRM/Core/Payment/Square/SquareUnitTestCase.php +++ b/tests/phpunit/CRM/Core/Payment/Square/SquareUnitTestCase.php @@ -95,9 +95,8 @@ protected function buildSquareClient(): SquareClient { * Whatever the invoked method returns. */ protected function callMethod(object $object, string $method, array $args = []) { - $reflection = new ReflectionMethod($object, $method); - $reflection->setAccessible(TRUE); - return $reflection->invokeArgs($object, $args); + // No setAccessible(): unnecessary since PHP 8.1, deprecated in PHP 8.5. + return (new ReflectionMethod($object, $method))->invokeArgs($object, $args); } } diff --git a/tests/phpunit/CRM/Core/Payment/Square/StatusMappingTest.php b/tests/phpunit/CRM/Core/Payment/Square/StatusMappingTest.php index 2f838c39..a078385f 100644 --- a/tests/phpunit/CRM/Core/Payment/Square/StatusMappingTest.php +++ b/tests/phpunit/CRM/Core/Payment/Square/StatusMappingTest.php @@ -11,23 +11,19 @@ */ class CRM_Core_Payment_Square_StatusMappingTest extends CRM_Core_Payment_Square_SquareUnitTestCase { - private function processor(): CRM_Core_Payment_Square { - $config = $this->processorConfig(); - return new CRM_Core_Payment_Square('live', $config); - } - /** * @dataProvider paymentStatusProvider */ public function testMapPaymentStatus(string $squareStatus, ?int $expected): void { - $actual = $this->callMethod($this->processor(), 'mapPaymentStatus', [$squareStatus]); + $actual = CRM_Square_Status::mapPaymentStatus($squareStatus); $this->assertSame($expected, $actual); } public static function paymentStatusProvider(): array { return [ 'completed' => ['COMPLETED', 1], - 'approved' => ['APPROVED', 1], + // Authorized, but not captured: not a completed payment yet. + 'approved is still pending' => ['APPROVED', 2], 'pending' => ['PENDING', 2], 'processing' => ['PROCESSING', 2], 'failed' => ['FAILED', 4], @@ -43,29 +39,59 @@ public static function paymentStatusProvider(): array { * @dataProvider subscriptionStatusProvider */ public function testMapSquareSubscriptionStatusToCivi(string $squareStatus, ?int $expected): void { - $actual = $this->callMethod($this->processor(), 'mapSquareSubscriptionStatusToCivi', [$squareStatus]); + $actual = CRM_Square_Status::mapSubscriptionStatus($squareStatus); $this->assertSame($expected, $actual); } 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], ]; } + /** + * @dataProvider recurStatusChangeProvider + */ + public function testRecurStatusChangeGuard(int $current, int $new, bool $expected): void { + $reconciler = new CRM_Square_Reconciler(new CRM_Square_Gateway($this->processorConfig())); + $actual = $this->callMethod($reconciler, 'isRecurStatusChangeAllowed', [$current, $new]); + $this->assertSame($expected, $actual); + } + + public static function recurStatusChangeProvider(): array { + // 1=Completed, 2=Pending, 3=Cancelled, 4=Failed, 5=In Progress. + return [ + // A late subscription.created (PENDING) must not undo the In Progress + // that recording the first payment set. + 'never downgraded to Pending once In Progress' => [5, 2, FALSE], + // ACTIVE says billing started, not that a payment was recorded. + 'not promoted to In Progress before its first payment' => [2, 5, FALSE], + 'restored to In Progress after a failure' => [4, 5, TRUE], + // Square reports a cancelled subscription ACTIVE until its cancel date. + 'a cancelled series is not reopened' => [3, 5, FALSE], + 'a completed series is not reopened' => [1, 5, FALSE], + 'cancellation always applies' => [5, 3, TRUE], + 'cancellation applies before the first payment too' => [2, 3, TRUE], + 'completion applies' => [5, 1, TRUE], + 'deactivation applies' => [5, 4, TRUE], + ]; + } + /** * @dataProvider paymentInstrumentProvider */ public function testMapPaymentInstrument(?string $sourceType, int $expected): void { - $actual = $this->callMethod($this->processor(), 'mapPaymentInstrument', [$sourceType]); + $actual = CRM_Square_Status::mapPaymentInstrument($sourceType); $this->assertSame($expected, $actual); } 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 new file mode 100644 index 00000000..612a5259 --- /dev/null +++ b/tests/phpunit/CRM/Core/Payment/Square/SubscriptionsTest.php @@ -0,0 +1,223 @@ +subscriptions()->getPlanVariationIdForParams($this->params(['installments' => 12])); + + $phase = $this->onlyPhase(); + $this->assertSame(12, $phase->getPeriods()); + $this->assertSame('MONTHLY', $phase->getCadence()); + $this->assertSame('STATIC', $phase->getPricing()->getType()); + $this->assertSame(1900, $phase->getPricing()->getPriceMoney()->getAmount()); + $this->assertSame('USD', $phase->getPricing()->getPriceMoney()->getCurrency()); + } + + /** + * An open-ended one sends no periods at all (0 would mean no periods). + * + * @dataProvider openEndedProvider + */ + public function testOpenEndedSubscriptionOmitsPeriods(array $installments): void { + $this->subscriptions()->getPlanVariationIdForParams($this->params($installments)); + + $this->assertNull($this->onlyPhase()->getPeriods()); + } + + public static function openEndedProvider(): array { + return [ + 'zero installments' => [['installments' => 0]], + 'no installments' => [[]], + ]; + } + + /** + * Plans are cached, but a finite plan never reuses an open-ended one's. + */ + public function testCachedVariationsAreKeptApartByInstallments(): void { + $subscriptions = $this->subscriptions(); + + $open = $subscriptions->getPlanVariationIdForParams($this->params()); + $this->assertSame($open, $subscriptions->getPlanVariationIdForParams($this->params()), 'Reused from the cache.'); + $finite = $subscriptions->getPlanVariationIdForParams($this->params(['installments' => 6])); + + $this->assertNotSame($open, $finite); + $this->assertCount(2, $this->variations, 'One variation for each; the repeat came from the cache.'); + } + + /** + * Retrying a catalog write after a lost response cannot create a duplicate. + */ + public function testCatalogIdempotencyKeysAreStableAndDistinct(): void { + $this->subscriptions()->getPlanVariationIdForParams($this->params()); + $firstKeys = $this->upsertKeys; + + // Nothing cached, as after a failure between Square's reply and caching. + Civi::$settings = []; + $this->upsertKeys = []; + $this->subscriptions()->getPlanVariationIdForParams($this->params()); + + $this->assertSame($firstKeys, $this->upsertKeys); + $this->assertCount(2, array_unique($firstKeys), 'The plan and its variation use different keys.'); + foreach ($firstKeys as $key) { + $this->assertLessThanOrEqual(45, strlen($key)); + } + } + + /** + * An unsupported cadence is refused rather than approximated. + */ + public function testUnsupportedCadenceIsRefused(): void { + $this->expectException(CRM_Core_Exception::class); + $this->expectExceptionMessage('Unsupported Square cadence'); + $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. + */ + public function testChangeAmountOverridesThePriceAtTheCurrentVersion(): void { + /** @var \Square\Subscriptions\Requests\UpdateSubscriptionRequest|null $captured */ + $captured = NULL; + $subscriptionsClient = $this->createMock(SubscriptionsClient::class); + $subscriptionsClient->method('get')->willReturn(new GetSubscriptionResponse([ + 'subscription' => new Subscription(['id' => 'SUB-1', 'version' => 7]), + ])); + $subscriptionsClient->method('update')->willReturnCallback(function (UpdateSubscriptionRequest $request) use (&$captured) { + $captured = $request; + return new UpdateSubscriptionResponse(['subscription' => $request->getSubscription()]); + }); + + $this->subscriptions(['subscriptions' => $subscriptionsClient])->changeAmount('SUB-1', 25.00, 'USD'); + + $this->assertNotNull($captured); + $this->assertSame('SUB-1', $captured->getSubscriptionId()); + $this->assertSame(7, $captured->getSubscription()->getVersion()); + $this->assertSame(2500, $captured->getSubscription()->getPriceOverrideMoney()->getAmount()); + $this->assertSame('USD', $captured->getSubscription()->getPriceOverrideMoney()->getCurrency()); + } + + /** + * @param array $overrides + * + * @return array + * doRecurPayment() params for a monthly 19.00 USD contribution. + */ + private function params(array $overrides = []): array { + return $overrides + [ + 'amount' => '19.00', + 'currency' => 'USD', + 'frequency_unit' => 'month', + 'frequency_interval' => 1, + ]; + } + + /** + * @param array $mockSubClients + * SquareClient sub-clients to use instead of the recording catalog. + * + * @return \CRM_Square_Subscriptions + */ + private function subscriptions(array $mockSubClients = []): CRM_Square_Subscriptions { + $catalog = $this->createMock(CatalogClient::class); + $catalog->method('batchUpsert')->willReturnCallback(function (BatchUpsertCatalogObjectsRequest $request) { + $this->upsertKeys[] = $request->getIdempotencyKey(); + $object = $request->getBatches()[0]->getObjects()[0]->getValue(); + if ($object instanceof CatalogObjectSubscriptionPlanVariation) { + $this->variations[] = $object; + $saved = CatalogObject::subscriptionPlanVariation(new CatalogObjectSubscriptionPlanVariation(['id' => 'VARIATION-' . count($this->variations)])); + } + else { + $this->assertInstanceOf(CatalogObjectSubscriptionPlan::class, $object); + $saved = CatalogObject::subscriptionPlan(new CatalogObjectSubscriptionPlan(['id' => 'PLAN-1'])); + } + return new BatchUpsertCatalogObjectsResponse(['objects' => [$saved]]); + }); + + $client = new SquareClient(token: 'test-token', options: ['baseUrl' => 'https://example.invalid']); + $client->catalog = $catalog; + foreach ($mockSubClients as $property => $mock) { + $client->$property = $mock; + } + return new CRM_Square_Subscriptions(new CRM_Square_Gateway($this->processorConfig(), fn () => $client)); + } + + /** + * The single phase of the one plan variation sent to Square. + * + * @return \Square\Types\SubscriptionPhase + */ + private function onlyPhase(): SubscriptionPhase { + $this->assertCount(1, $this->variations); + $phases = $this->variations[0]->getSubscriptionPlanVariationData()->getPhases(); + $this->assertCount(1, $phases); + return $phases[0]; + } + +} diff --git a/tests/phpunit/CRM/Core/Payment/Square/WebhookQueueTest.php b/tests/phpunit/CRM/Core/Payment/Square/WebhookQueueTest.php new file mode 100644 index 00000000..8dd800cd --- /dev/null +++ b/tests/phpunit/CRM/Core/Payment/Square/WebhookQueueTest.php @@ -0,0 +1,337 @@ +lockFree ? new class() { + + /** + * Nothing to release. + */ + public function release(): void { + } + + } : NULL; + } + + /** + * @param int $processorId + * @param string $eventId + * + * @return array|null + */ + protected function findQueuedEvent(int $processorId, string $eventId): ?array { + foreach ($this->records as $record) { + if ($record['payment_processor_id'] === $processorId && $record['event_id'] === $eventId) { + return $record; + } + } + return NULL; + } + + /** + * @param array $values + * + * @return array + */ + protected function createQueueRecord(array $values): array { + $this->created[] = $values; + $id = count($this->records) + 1; + // The table's defaults. + $this->records[$id] = $values + [ + 'id' => $id, + 'status' => 'new', + 'processed_date' => NULL, + 'created_date' => date('Y-m-d H:i:s'), + ]; + return $this->records[$id]; + } + + /** + * @param int $id + * @param array $values + */ + protected function updateQueueRecord(int $id, array $values): void { + $this->records[$id] = $values + $this->records[$id]; + } + +} + +/** + * Webhook queue states: what is processed, retried, or left for a person. + */ +class CRM_Core_Payment_Square_WebhookQueueTest extends CRM_Core_Payment_Square_SquareUnitTestCase { + + /** + * What the processor's payment.updated handler does. + * + * @var callable|null + */ + private $onPayment = NULL; + + /** + * Number of payment.updated events handled. + * + * @var int + */ + private int $handled = 0; + + public function testNewEventIsRecordedAsNewThenProcessed(): void { + $ipn = $this->ipn(); + $payload = $this->event(); + + $this->assertTrue($this->receive($ipn, $payload)); + + $this->assertSame(1, $this->handled); + $this->assertCount(1, $ipn->created); + $this->assertArrayNotHasKey('status', $ipn->created[0], "Recorded in the default 'new', so a request that dies mid-processing is still retried."); + $this->assertSame('payment.updated', $ipn->created[0]['trigger']); + $this->assertSame($payload['event_id'], $ipn->created[0]['event_id']); + $this->assertSame('PAY-1::', $ipn->created[0]['identifier']); + $record = $ipn->records[1]; + $this->assertSame('success', $record['status']); + $this->assertSame('now', $record['processed_date']); + } + + public function testRedeliveredEventIsNotProcessedAgain(): void { + $ipn = $this->ipn(); + $payload = $this->event(); + $this->receive($ipn, $payload); + + $this->assertTrue($this->receive($ipn, $payload)); + + $this->assertSame(1, $this->handled); + $this->assertCount(1, $ipn->records); + } + + public function testEventBeingRecordedElsewhereIsTreatedAsADuplicate(): void { + $ipn = $this->ipn(); + $ipn->lockFree = FALSE; + + $this->assertTrue($this->receive($ipn, $this->event())); + + $this->assertSame([], $ipn->records); + $this->assertSame(0, $this->handled); + } + + public function testUnsupportedEventIsAcknowledgedButNotRecorded(): void { + $ipn = $this->ipn(); + + $payload = ['type' => 'customer.created', 'event_id' => 'EVT-X', 'data' => ['object' => []]]; + $this->assertTrue($this->receive($ipn, $payload)); + + $this->assertSame([], $ipn->records); + } + + public function testEventWithoutAnIdIsRejected(): void { + $ipn = $this->ipn(); + $payload = $this->event(); + unset($payload['event_id']); + + $this->assertFalse($this->receive($ipn, $payload)); + $this->assertSame([], $ipn->records); + } + + /** + * A transient failure is left in 'new' for the scheduled job. + */ + public function testTransientFailureIsLeftForRetry(): void { + $this->onPayment = fn () => throw new CRM_Core_Payment_SquareRetryableException('Square API returned HTTP 503.'); + $ipn = $this->ipn(); + + $this->assertTrue($this->receive($ipn, $this->event()), 'Accepted: it is queued for retry.'); + + $record = $ipn->records[1]; + $this->assertSame('new', $record['status']); + $this->assertNull($record['processed_date'], 'The job only retries records with no processed_date.'); + $this->assertStringContainsString('HTTP 503', $record['message']); + } + + /** + * The job retries 'new' forever, so the retry window ends it. + */ + public function testTransientFailurePastTheRetryWindowIsAnError(): void { + $this->onPayment = fn () => throw new CRM_Core_Payment_SquareRetryableException('still not there'); + $ipn = $this->ipn(); + $record = $this->queued($ipn, date('Y-m-d H:i:s', time() - CRM_Core_Payment_SquareIPN::RETRY_WINDOW_SECONDS - 60)); + + $this->assertFalse($ipn->processQueuedWebhookEvent($record)); + + $this->assertSame('error', $ipn->records[$record['id']]['status']); + $this->assertStringContainsString('Gave up retrying', $ipn->records[$record['id']]['message']); + } + + /** + * A retry from the scheduled job, whose record holds the JSON body. + */ + public function testQueuedEventIsProcessedByTheScheduledJob(): void { + $ipn = $this->ipn(); + $record = $this->queued($ipn, date('Y-m-d H:i:s')); + + $this->assertTrue($ipn->processQueuedWebhookEvent($record)); + + $this->assertSame(1, $this->handled); + $this->assertSame('success', $ipn->records[$record['id']]['status']); + } + + /** + * @dataProvider permanentFailureProvider + */ + public function testPermanentFailureIsAnError(\Throwable $failure): void { + $this->onPayment = fn () => throw $failure; + $ipn = $this->ipn(); + + $this->assertFalse($this->receive($ipn, $this->event())); + + $record = $ipn->records[1]; + $this->assertSame('error', $record['status']); + $this->assertNull($record['processed_date']); + $this->assertStringContainsString($failure->getMessage(), $record['message']); + } + + public static function permanentFailureProvider(): array { + return [ + 'reconciliation error' => [new CRM_Core_Exception('needs manual reconciliation')], + // The scheduled job catches nothing itself, so an Error must not escape. + 'PHP error' => [new TypeError('Argument #1 must be of type array')], + ]; + } + + /** + * An IPN for payment processor 42 whose payment.updated handler is $this->onPayment. + * + * @return \CRM_Core_Payment_Square_FakeQueueIPN + */ + private function ipn(): CRM_Core_Payment_Square_FakeQueueIPN { + $test = $this; + $processor = new class($test) { + + /** + * @var \CRM_Core_Payment_Square_WebhookQueueTest + */ + private $test; + + /** + * @param \CRM_Core_Payment_Square_WebhookQueueTest $test + */ + public function __construct($test) { + $this->test = $test; + } + + /** + * @return int + */ + public function getID() { + return 42; + } + + /** + * @param array $payment + */ + public function syncPaymentFromSquare(array $payment): void { + $this->test->handlePayment($payment); + } + + }; + return new CRM_Core_Payment_Square_FakeQueueIPN($processor); + } + + /** + * The processor's payment.updated handler. + * + * @param array $payment + */ + public function handlePayment(array $payment): void { + $this->handled++; + if ($this->onPayment) { + ($this->onPayment)($payment); + } + } + + /** + * Receive a webhook, as CRM_Core_Payment_Square::handlePaymentNotification() does. + * + * @param \CRM_Core_Payment_Square_FakeQueueIPN $ipn + * @param array $payload + * + * @return bool + */ + private function receive(CRM_Core_Payment_Square_FakeQueueIPN $ipn, array $payload): bool { + $ipn->setData(json_encode($payload)); + return $ipn->onReceiveWebhook($payload); + } + + /** + * A payment.updated event already in the queue, as the scheduled job reads it. + * + * @param \CRM_Core_Payment_Square_FakeQueueIPN $ipn + * @param string $createdDate + * + * @return array + */ + private function queued(CRM_Core_Payment_Square_FakeQueueIPN $ipn, string $createdDate): array { + $payload = $this->event(); + $id = count($ipn->records) + 1; + $ipn->records[$id] = [ + 'id' => $id, + 'payment_processor_id' => 42, + 'event_id' => $payload['event_id'], + 'trigger' => $payload['type'], + 'data' => json_encode($payload), + 'status' => 'processing', + 'processed_date' => NULL, + 'created_date' => $createdDate, + ]; + return $ipn->records[$id]; + } + + /** + * @return array + */ + private function event(): array { + return [ + 'type' => 'payment.updated', + 'event_id' => 'EVT-1', + 'data' => ['type' => 'payment', 'object' => ['payment' => ['id' => 'PAY-1', 'status' => 'COMPLETED']]], + ]; + } + +} 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 new file mode 100644 index 00000000..83c08cc2 --- /dev/null +++ b/tests/phpunit/CRM/Square/UpgraderTest.php @@ -0,0 +1,138 @@ +upgrader(FALSE, [ + ['payment_processor_id' => 7, 'square_customer_id' => 'CUST-A', 'contact_ids' => '12,34'], + ['payment_processor_id' => 9, 'square_customer_id' => 'CUST-B', 'contact_ids' => '56,78,90'], + ]); + + try { + $upgrader->upgrade_1001(); + $this->fail('Expected the upgrade to stop.'); + } + catch (CRM_Core_Exception $e) { + // Every conflict, and what to do about it. + $this->assertStringContainsString('2 Square customer(s)', $e->getMessage()); + $this->assertStringContainsString('payment processor 7, Square customer CUST-A: contacts 12, 34', $e->getMessage()); + $this->assertStringContainsString('payment processor 9, Square customer CUST-B: contacts 56, 78, 90', $e->getMessage()); + $this->assertStringContainsString('delete the other contacts', $e->getMessage()); + } + $this->assertFalse($upgrader->keyAdded, 'No mapping is re-assigned or dropped automatically.'); + } + + public function testKeyIsAddedWhenNoMappingsConflict(): void { + $upgrader = $this->upgrader(FALSE, []); + + $this->assertTrue($upgrader->upgrade_1001()); + + $this->assertTrue($upgrader->keyAdded); + } + + public function testUpgradeIsANoOpWhenTheKeyExists(): void { + // E.g. installed after the key was added to the table definition. + $upgrader = $this->upgrader(TRUE, [ + ['payment_processor_id' => 7, 'square_customer_id' => 'CUST-A', 'contact_ids' => '12,34'], + ]); + + $this->assertTrue($upgrader->upgrade_1001()); + + $this->assertFalse($upgrader->conflictsChecked); + $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. + * + * @param bool $hasKey + * @param array $conflicts + * + * @return \CRM_Square_Upgrader + */ + private function upgrader(bool $hasKey, array $conflicts): CRM_Square_Upgrader { + return new class($hasKey, $conflicts) extends CRM_Square_Upgrader { + + /** + * @var bool + */ + public bool $keyAdded = FALSE; + + /** + * @var bool + */ + public bool $conflictsChecked = FALSE; + + /** + * @var bool + */ + public bool $cascadeAdded = FALSE; + + /** + * @var bool + */ + private bool $hasKey; + + /** + * @var array + */ + private array $conflicts; + + /** + * @param bool $hasKey + * @param array $conflicts + */ + public function __construct(bool $hasKey, array $conflicts) { + $this->hasKey = $hasKey; + $this->conflicts = $conflicts; + } + + /** + * @return bool + */ + protected function hasUniqueCustomerKey(): bool { + return $this->hasKey; + } + + /** + * @return array + */ + protected function findConflictingCustomerMappings(): array { + $this->conflictsChecked = TRUE; + return $this->conflicts; + } + + /** + * Record instead of altering the table. + */ + 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 f423111e..a925f0fc 100644 --- a/tests/phpunit/bootstrap.php +++ b/tests/phpunit/bootstrap.php @@ -9,8 +9,25 @@ require_once $extensionRoot . '/vendor/autoload.php'; -// Focused unit tests load the payment class without a full CiviCRM install. -// The production classes supplied by CiviCRM take precedence when available. +// Load real CiviCRM first, when a bootstrap file is given, so that its +// classes take precedence: every stand-in below is only defined if the real +// class is missing. Focused unit tests run without it. +$cmsPath = getenv('CIVICRM_BOOTSTRAP_FILE'); +if ($cmsPath && file_exists($cmsPath)) { + require_once $cmsPath; +} + +// The extension's own CRM_* classes (CiviCRM's classloader loads these in +// production, from info.xml's ). +spl_autoload_register(function (string $class) use ($extensionRoot): void { + if (str_starts_with($class, 'CRM_')) { + $file = $extensionRoot . '/' . str_replace('_', '/', $class) . '.php'; + if (is_file($file)) { + require_once $file; + } + } +}); + if (!class_exists('CRM_Core_Payment')) { /** @@ -35,10 +52,39 @@ abstract class CRM_Core_Payment { /** * Minimal stand-in for CiviCRM core's exception class. + * + * With core's constructor signature, whose previous exception is the + * fourth argument (not PHP's third). */ class CRM_Core_Exception extends Exception { + + /** + * @param string $message + * @param int|string $error_code + * @param array $errorData + * @param \Throwable|null $previous + */ + // phpcs:ignore Drupal.NamingConventions.ValidVariableName.LowerCamelName + public function __construct($message = '', $error_code = 0, $errorData = [], $previous = NULL) { + parent::__construct((string) $message, is_int($error_code) ? $error_code : 0, $previous); + } + + } +} +if (!class_exists('CRM_Extension_Upgrader_Base')) { + + /** + * Minimal stand-in for CiviCRM core's extension upgrader base class. + */ + abstract class CRM_Extension_Upgrader_Base { } } +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')) { /** @@ -62,6 +108,16 @@ public static function url(string $path = ''): string { return $path; } + /** + * @param string $text + * @param array $params + * + * @return string + */ + public static function ts($text, array $params = []): string { + return ts($text, $params); + } + } } if (!function_exists('ts')) { @@ -75,45 +131,295 @@ public static function url(string $path = ''): 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')) { +if (!class_exists('CRM_Core_PseudoConstant')) { /** - * Minimal stand-in for CiviCRM core's contribution-status lookup. + * Minimal stand-in for CiviCRM core's pseudoconstant 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. + * 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_Contribute_PseudoConstant { + class CRM_Core_PseudoConstant { /** - * @return array + * @param string $baoName + * @param string $fieldName + * @param string $value + * + * @return int|false */ - public static function contributionStatus(): array { - return [ - 1 => 'Completed', - 2 => 'Pending', - 3 => 'Cancelled', - 4 => 'Failed', - 5 => 'In Progress', - 6 => 'Overdue', - 7 => 'Refunded', + public static function getKey($baoName, $fieldName, $value) { + $options = [ + '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', + ], + ], + '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[$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')) { -// CiviCRM test bootstrap (if available). Not required for mock-only tests, -// but harmless if present. -$cmsPath = getenv('CIVICRM_BOOTSTRAP_FILE'); -if ($cmsPath && file_exists($cmsPath)) { - require_once $cmsPath; + /** + * 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 ?? '')); + } + + } +} +if (!class_exists('Civi')) { + + /** + * Minimal stand-in for CiviCRM's Civi service locator. + * + * Settings, logging and an injectable lock manager are provided. Logs go to + * Civi::$logged so tests can assert reconciliation errors were raised. + */ + class Civi { + + /** + * Messages logged during the current test, as [level, message] pairs. + * + * @var array + */ + public static array $logged = []; + + /** + * Settings saved during the current test, by name. + * + * @var array + */ + 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 + */ + public static function settings() { + return new class() { + + /** + * @param string $name + * + * @return mixed + */ + public function get($name) { + return Civi::$settings[$name] ?? NULL; + } + + /** + * @param string $name + * @param mixed $value + */ + public function set($name, $value): void { + Civi::$settings[$name] = $value; + } + + }; + } + + /** + * @param string $channel + * + * @return object + */ + public static function log($channel = 'default') { + return new class() { + + /** + * @param string $level + * @param array $args + */ + public function __call($level, $args) { + Civi::$logged[] = [$level, (string) ($args[0] ?? '')]; + } + + }; + } + + } } diff --git a/tests/phpunit/phpunit.xml.dist b/tests/phpunit/phpunit.xml.dist index c4cfc2be..34c8b7f7 100644 --- a/tests/phpunit/phpunit.xml.dist +++ b/tests/phpunit/phpunit.xml.dist @@ -7,7 +7,8 @@ backupStaticAttributes="false" convertWarningsToExceptions="true" convertErrorsToExceptions="true" - convertNoticesToExceptions="false" + convertNoticesToExceptions="true" + convertDeprecationsToExceptions="true" > diff --git a/tests/phpunit/stubs/PaymentProcessorException.php b/tests/phpunit/stubs/PaymentProcessorException.php new file mode 100644 index 00000000..c60670f5 --- /dev/null +++ b/tests/phpunit/stubs/PaymentProcessorException.php @@ -0,0 +1,11 @@ + 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', ),