Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 54 additions & 10 deletions CRM/Core/Payment/Square.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Civi\Payment\Exception\PaymentProcessorException;
use Civi\Payment\PropertyBag;
use Square\SquareClient;
use Square\Types\CustomerDetails;
use Square\Types\Money;
use Square\Types\SubscriptionSource;
use Square\Payments\Requests\CreatePaymentRequest;
Expand All @@ -20,7 +21,9 @@
*
* This processor supports:
* - One-off (non-recurring) card payments via Square Payments API
* - Recurring contributions via Square Subscriptions API.
* - Recurring contributions via Square Subscriptions API
* - Both on CiviCRM's back-office forms too, where staff enter the
* payer's card (see supportsBackOffice()).
*
* Card details are never handled by CiviCRM directly. Instead, the
* Square Web Payments SDK is used in the browser to tokenize the card
Expand Down Expand Up @@ -124,6 +127,9 @@ public function buildForm(&$form) {
// A new card for an existing recurring contribution: saved, not
// charged (see updateSubscriptionBillingInfo()).
'isCardUpdate' => $form instanceof CRM_Contribute_Form_UpdateBilling,
// Staff are keying in the payer's card (MOTO), so Square must not
// ask them to verify as the buyer.
'isBackOffice' => $this->isBackOfficeForm($form),
];

// Add hidden field for the payment token.
Expand Down Expand Up @@ -165,6 +171,22 @@ public function buildForm(&$form) {
return FALSE;
}

/**
* Whether staff, not the payer, enter the card on this form.
*
* CiviCRM's payment forms declare it ($form->isBackOffice: TRUE on the
* back-office contribution, membership, event registration and payment
* forms, and on the billing block they reload). For any other form, fall
* back to what CiviCRM told this processor (setBackOffice()).
*
* @param \CRM_Core_Form $form
*
* @return bool
*/
protected function isBackOfficeForm($form): bool {
return (bool) ($form->isBackOffice ?? $this->isBackOffice());
}

/**
* Build a SquareClient configured for this processor (2025 SDK style).
*
Expand Down Expand Up @@ -513,14 +535,23 @@ protected function doOneTimePayment(&$params) {
$amountMinorUnits = CRM_Square_Currency::toMinorUnits($amount, $currency);

// 3. Idempotency key, derived from the checkout's own reference so that a
// retried request for the same checkout can never charge twice. Every
// 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.
// retried request for the same checkout can never charge twice. Without
// one 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 === '') {
$idempotencyReference = $paymentReference;
if (($paymentReference === NULL || $paymentReference === '') && $this->isBackOffice()) {
// CiviCRM's back-office "Submit Credit Card Payment" form, which adds a
// payment to an existing contribution, passes no reference. The card
// token is single-use, so it identifies this checkout instead: a
// re-posted form carries the same token, a new payment a new one.
$paymentReference = 'entered by staff for contact ' . ($params['contactID'] ?? $params['contact_id'] ?? 'unknown');
$idempotencyReference = 'card-token:' . $token;
}
if ($idempotencyReference === NULL || $idempotencyReference === '') {
throw new \CRM_Core_Exception('Cannot take a Square payment without a CiviCRM invoice or contribution reference.');
}
$idempotencyKey = $this->idempotencyKey('payment', (string) $paymentReference);
$idempotencyKey = $this->idempotencyKey('payment', (string) $idempotencyReference);

// 4. Build payload for CreatePayment.
$requestValues = [
Expand All @@ -530,6 +561,15 @@ protected function doOneTimePayment(&$params) {
'locationId' => $this->getLocationId(),
];

// Staff keyed in the payer's card: a Mail Order / Telephone Order (MOTO)
// payment, as js/square.js told Square when tokenizing it.
if ($this->isBackOffice()) {
$requestValues['customerDetails'] = new CustomerDetails([
'customerInitiated' => FALSE,
'sellerKeyedIn' => TRUE,
]);
}

// Add customer ID if available (optional for one-off payments)
$contactId = $params['contactID'] ?? $params['contact_id'] ?? NULL;
if ($contactId) {
Expand Down Expand Up @@ -1191,15 +1231,19 @@ public function cancelSquareSubscription(string $subscriptionId): void {
}

/**
* Whether processor supports back-office (admin) payments.
* Whether staff can take card payments with this processor on back-office forms.
*
* For now, we only support front-end Web Payments SDK tokenization.
* They can: CiviCRM's back-office contribution, membership, event
* registration and "Submit Credit Card Payment" forms show Square's card
* form just as the front end does. Staff key in the payer's card, so
* js/square.js and doOneTimePayment() flag those payments to Square as
* Mail Order / Telephone Order (MOTO), and Square does not ask staff to
* verify as the buyer.
*
* @return bool
*/
public function supportsBackOffice() {
// You can change this to TRUE if you later support card entry in admin UI.
return FALSE;
return TRUE;
}

/**
Expand Down
3 changes: 2 additions & 1 deletion CRM/Square/Subscriptions.php
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,8 @@ public function __construct(CRM_Square_Gateway $gateway) {
public function getPlanVariationIdForParams(array $params): string {
$entity = $params['component'] ?? 'contribute';
$amount = (float) ($params['amount'] ?? 0);
$currency = $params['currency'] ?? 'USD';
// CiviCRM's back-office membership form passes only currencyID.
$currency = $params['currency'] ?? $params['currencyID'] ?? 'USD';
$intervalUnit = $params['frequency_unit'] ?? '';
$intervalStep = (int) ($params['frequency_interval'] ?? 1);
$installments = (int) ($params['installments'] ?? 0);
Expand Down
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ required after cloning/downloading — just enable the extension as usual
- 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
- Donors can replace the card a recurring contribution is charged to (CiviCRM's **Update billing details**)
- Back-office card payments: staff can take one-time and recurring payments on CiviCRM's **Submit Credit Card Contribution / Membership / Event Registration** and **Submit Credit Card Payment** forms, flagged to Square as keyed in by the seller (MOTO)
- 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
Expand Down Expand Up @@ -150,8 +151,9 @@ deletes its mappings.

- CiviCRM native contribution pages and event registration forms
- Drupal Webform (webform_civicrm module) billing blocks, including AJAX reloads
- CiviCRM's back-office credit card forms (contribution, membership signup and renewal, event registration, and **Submit Credit Card Payment** on an existing contribution), on a page or in a popup

Back-office (staff-entered) card payments are not supported.
On a back-office form staff key in the payer's card, so the payment is a Mail Order / Telephone Order (MOTO) one: `card.tokenize()` is told `customerInitiated: false` and `sellerKeyedIn: true` (Square then does not ask staff to verify as the buyer), and `CreatePayment` sends the same as its `customer_details`. CiviCRM's **Submit Credit Card Payment** form passes no invoice or contribution reference, so that payment's idempotency key is derived from its single-use card token instead; front-end checkouts without a reference are still refused. When staff switch the form to another payment processor, `square.js` stops handling the form's submit buttons, leaving them to that processor.

Key globals:
- `CRM.squarePayment` — Square's namespaced integration state
Expand Down
4 changes: 2 additions & 2 deletions docs/OVERVIEW.html
Original file line number Diff line number Diff line change
Expand Up @@ -340,7 +340,7 @@ <h1 class="title">Square Payment Processor</h1>
<section id="overview">
<p class="kicker">Overview</p>
<h2 class="section-title">What this extension does</h2>
<p class="lede">org.civicrm.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.</p>
<p class="lede">org.civicrm.square registers Square as a CiviCRM payment processor type — the same role Stripe or PayPal extensions play — so contribution pages, event registration, Drupal webforms, and staff on CiviCRM's back-office credit card forms can charge a Square-issued card without CiviCRM ever seeing the card number.</p>
<p>It depends on two core CiviCRM extensions, <code>mjwshared</code> and <code>civi_contribute</code>, and is built against CiviCRM 6.16 or later. Composer dependencies ship committed in <code>vendor/</code>, so installing it is a normal extension enable — no build step. It is developed and maintained by Skvare, distributed under AGPL-3.0-or-later.</p>
<div class="callout"><strong>Why it exists:</strong> 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.</div>
</section>
Expand Down Expand Up @@ -444,7 +444,7 @@ <h2 class="section-title">Components</h2>
<tr><td class="mono">CRM/Core/Payment/SquareIPN.php</td><td>Webhook filtering, signature verification, deduplication, queue persistence, processing.</td></tr>
<tr><td class="mono">CRM/Core/Payment/SquareDebugLogger.php</td><td>Opt-in diagnostic logging, gated by a setting so it's off by default.</td></tr>
<tr><td class="mono">CRM/Square/Upgrader.php</td><td>Creates <code>square_customer_map</code> and <code>square_catalog_map</code>, and drops them on uninstall.</td></tr>
<tr><td class="mono">js/square.js</td><td>Mounts 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.</td></tr>
<tr><td class="mono">js/square.js</td><td>Mounts the Square card element and tokenizes on submit, across native, Webform and back-office forms (flagging staff-keyed cards as MOTO); keeps the card form's ZIP in step with the billing address's.</td></tr>
<tr><td class="mono">managed/PaymentProcessorType.mgd.php</td><td>Registers "Square" as a selectable payment processor type.</td></tr>
</tbody>
</table>
Expand Down
9 changes: 9 additions & 0 deletions docs/WORKFLOWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,15 @@ checkout: Square charges the first installment itself, within seconds.

![Recurring contribution signup sequence](images/recurring-signup.svg)

## Back-office payments

Staff use the same two flows on CiviCRM's back-office credit card forms, keying
in the payer's card. Square is told the payment is keyed in by the seller (MOTO),
both when the card is tokenized and in `CreatePayment`, so it does not ask staff
to verify as the buyer. **Submit Credit Card Payment**, which adds a payment to
an existing contribution, has no invoice reference of its own: its idempotency
key comes from the single-use card token instead.

## Subscription installment webhooks

The events Square sends for each installment, paid or declined, and how
Expand Down
65 changes: 58 additions & 7 deletions js/square.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
* Supports:
* - CiviCRM native contribution pages and event registration forms
* - Drupal Webform (webform_civicrm module) billing blocks
* - Backend contribution / event forms
* - Back-office contribution, membership, event registration and payment
* forms, on a page or in a popup, where staff key in the payer's card
* (flagged to Square as MOTO)
*
* Architecture mirrors Stripe (civicrmStripe.js) and AuthNet (civicrmAuthNetAccept.js):
* - CRM.squarePayment — shared form-utility object (equivalent to CRM.payment in mjwshared)
Expand Down Expand Up @@ -166,7 +168,11 @@
$(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');
// The original name, if an earlier call (or another processor's
// script) already renamed the checkbox: the billing block, and so
// this, is reloaded whenever the processor or amount changes.
var name = $(this).attr('data-name') || $(this).attr('name');
if (!name) return;
$(this).attr('data-name', name);
$(this).attr('name', name.replace('[' + name.split('[').pop(), ''));
});
Expand All @@ -188,6 +194,18 @@
for (var i = 0; i < this.submitButtons.length; ++i) {
this.submitButtons[i].setAttribute('disabled', true);
}
this.submitForm();
},

/**
* Submit the billing form, bypassing its submit event handlers.
*
* CiviCRM turns off its "You have unsaved changes" warning in a submit
* event handler, which form.submit() does not fire. Back-office forms
* warn of unsaved changes, so turn it off here, as that handler would.
*/
submitForm: function() {
$('[data-warn-changes]').attr('data-warn-changes', 'false');
this.resetBillingFieldsRequiredForJQueryValidate();
this.form.submit();
},
Expand Down Expand Up @@ -342,6 +360,9 @@
cardPostalCode: '',
// The value this script last copied into the billing postal code field.
autofilledPostalCode: null,
// Whether this script renamed the form's checkboxes for jQuery
// validation (see setBillingFieldsRequiredForJQueryValidate()).
billingFieldsAdjusted: false,
billingPostalCodePattern: /billing_postal_code(-\d+)?\]?$/,

debugging: function(msg) {
Expand All @@ -358,6 +379,7 @@
currency: cfg.currency || 'USD',
countryIsoCodes: cfg.countryIsoCodes || {},
isCardUpdate: !!cfg.isCardUpdate,
isBackOffice: !!cfg.isBackOffice,
};
},

Expand Down Expand Up @@ -416,6 +438,10 @@
* STORE, as is a card update's. Square refuses an amount or currency for
* STORE ("The STORE intent does not support the amount field."), even an
* empty one: only CHARGE has them.
*
* On a back-office form staff key in the payer's card: a Mail Order /
* Telephone Order (MOTO) payment, which the payer did not initiate
* there. Square then does not ask staff to verify as the buyer.
*/
getVerificationDetails: function(totalAmount) {
var cfg = script.getConfig();
Expand Down Expand Up @@ -446,8 +472,8 @@
var details = {
billingContact: contact,
intent: script.isRecurring() ? 'STORE' : 'CHARGE',
customerInitiated: true,
sellerKeyedIn: false
customerInitiated: !cfg.isBackOffice,
sellerKeyedIn: cfg.isBackOffice
};
if (details.intent === 'CHARGE') {
details.amount = Number(totalAmount || 0).toFixed(2);
Expand Down Expand Up @@ -595,6 +621,18 @@
if (typeof CRM.vars !== 'undefined') {
delete CRM.vars.orgCivicrmSquare;
}
// Step aside for the processor now selected (e.g. another one in a
// back-office form's processor list): its own script, or CiviCRM,
// submits the form, with the checkboxes' own names.
var form = CRM.squarePayment.form;
if (form) {
$('[type=submit]', form).off('click.square click.squareWebform');
$(form).off('change.squarePostalCode keydown.squareWebform');
}
if (script.billingFieldsAdjusted) {
CRM.squarePayment.resetBillingFieldsRequiredForJQueryValidate();
script.billingFieldsAdjusted = false;
}
if (CRM.squarePayment.submitButtons) {
$(CRM.squarePayment.submitButtons).show();
}
Expand Down Expand Up @@ -668,6 +706,7 @@

doAfterElementsHaveLoaded: function() {
CRM.squarePayment.setBillingFieldsRequiredForJQueryValidate();
script.billingFieldsAdjusted = true;
CRM.squarePayment.form.dataset.submitdontprocess = 'false';
CRM.squarePayment.addHandlerNonPaymentSubmitButtons();

Expand All @@ -678,7 +717,9 @@

function submitButtonClick(clickEvent) {
if (typeof CRM.vars === 'undefined' || typeof CRM.vars.orgCivicrmSquare === 'undefined') {
return CRM.squarePayment.doStandardFormSubmit();
// Square is no longer the selected processor: leave the submit
// to the form, or to that processor's own script.
return;
}
CRM.squarePayment.form.dataset.submitdontprocess = 'false';
return script.submit(clickEvent);
Expand Down Expand Up @@ -857,8 +898,7 @@
}
tokenField.value = result.token;

CRM.squarePayment.resetBillingFieldsRequiredForJQueryValidate();
CRM.squarePayment.form.submit();
CRM.squarePayment.submitForm();
}
catch(e) {
// Logged whatever the debug setting: otherwise nothing says what failed.
Expand Down Expand Up @@ -953,4 +993,15 @@
}
};

// Loaded with a billing block that arrived after the page did, e.g. a
// back-office form opened in a popup: DOMContentLoaded has fired already,
// and the request that brought it (such as civicrm/payment/add or
// civicrm/contribute/updatebilling) may not be one isAJAXPaymentForm()
// knows. Initialized now, as a reload is above; one that request does
// trigger is skipped while this one is still mounting the card form.
if (document.readyState !== 'loading') {
CRM.squarePayment.debugging(script.name, 'loaded after the page');
load();
}

}(CRM.$, CRM.ts('org.civicrm.square')));
Loading
Loading