-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhooks.php
More file actions
356 lines (321 loc) · 11.4 KB
/
hooks.php
File metadata and controls
356 lines (321 loc) · 11.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
<?php
/**
* Implementation of hook_civicrm_config().
* Required to autoload CRM/UschessSquare classes.
*/
function org_uschess_square_civicrm_config(&$config) {
_org_uschess_square_civix_civicrm_config($config);
}
/**
* Implementation of hook_civicrm_xmlMenu().
*/
function org_uschess_square_civicrm_xmlMenu(&$files) {
_org_uschess_square_civix_civicrm_xmlMenu($files);
}
/**
* Implementation of hook_civicrm_install().
*/
function org_uschess_square_civicrm_install() {
_org_uschess_square_civix_civicrm_install();
org_uschess_square_create_custom_fields();
}
/**
* Create custom fields for Square integration on install.
*/
function org_uschess_square_create_custom_fields() {
try {
// Check if custom group exists
$group = civicrm_api3('CustomGroup', 'get', [
'name' => 'square_data',
'sequential' => 1,
]);
if (!empty($group['count'])) {
$groupId = $group['values'][0]['id'];
}
else {
// Create custom group
$result = civicrm_api3('CustomGroup', 'create', [
'title' => 'Square Data',
'name' => 'square_data',
'extends' => 'Contact',
'style' => 'Inline',
'is_active' => 1,
]);
$groupId = $result['id'];
}
// Create Square Customer ID field
$field = civicrm_api3('CustomField', 'get', [
'custom_group_id' => $groupId,
'name' => 'square_customer_id',
'sequential' => 1,
]);
if (empty($field['count'])) {
civicrm_api3('CustomField', 'create', [
'custom_group_id' => $groupId,
'label' => 'Square Customer ID',
'name' => 'square_customer_id',
'data_type' => 'String',
'html_type' => 'Text',
'is_active' => 1,
'is_view' => 1,
'is_searchable' => 0,
]);
}
// Create Square Card ID field
$field = civicrm_api3('CustomField', 'get', [
'custom_group_id' => $groupId,
'name' => 'square_card_id',
'sequential' => 1,
]);
if (empty($field['count'])) {
civicrm_api3('CustomField', 'create', [
'custom_group_id' => $groupId,
'label' => 'Square Card ID',
'name' => 'square_card_id',
'data_type' => 'String',
'html_type' => 'Text',
'is_active' => 1,
'is_view' => 1,
'is_searchable' => 0,
]);
}
}
catch (Exception $e) {
CRM_Core_Error::debug_log_message('Square: Error creating custom fields: ' . $e->getMessage());
}
}
/**
* Implementation of hook_civicrm_uninstall().
*/
function org_uschess_square_civicrm_uninstall() {
_org_uschess_square_civix_civicrm_uninstall();
}
/**
* Implementation of hook_civicrm_enable().
*/
function org_uschess_square_civicrm_enable() {
_org_uschess_square_civix_civicrm_enable();
org_uschess_square_ensureOnSiteBillingMode(TRUE);
}
/**
* Ensure Square payment processors are configured as on-site (billing_mode=1).
*
* Webform CiviCRM checks the payment processor instance's billing_mode; if it's
* off-site it will use an IPN/confirm flow which does not preserve our token
* field, leading to "Missing Square payment token".
*
* @param bool $force
* If TRUE, run even if previously marked as fixed.
*/
function org_uschess_square_ensureOnSiteBillingMode($force = FALSE) {
try {
if (!$force && class_exists('\\Civi') && \Civi::settings()->get('org_uschess_square_billing_mode_fixed')) {
return;
}
// Prefer API4.
if (class_exists('\\Civi\\Api4\\PaymentProcessor')) {
$rows = \Civi\Api4\PaymentProcessor::get(FALSE)
->addSelect('id', 'class_name', 'billing_mode', 'payment_processor_type_id:label')
->execute();
$toUpdate = [];
foreach ($rows as $row) {
$label = $row['payment_processor_type_id:label'] ?? '';
$isSquare = (
(!empty($row['class_name']) && $row['class_name'] === 'Payment_Square') ||
(!empty($label) && stripos($label, 'square') !== FALSE)
);
if ($isSquare && ((int) ($row['billing_mode'] ?? 0) !== 1)) {
$toUpdate[] = (int) $row['id'];
}
}
if (!empty($toUpdate)) {
foreach ($toUpdate as $id) {
\Civi\Api4\PaymentProcessor::update(FALSE)
->addWhere('id', '=', $id)
->addValue('billing_mode', 1)
->execute();
}
}
}
else {
// Fallback to API3 if API4 isn't available.
$result = civicrm_api3('PaymentProcessor', 'get', [
'options' => ['limit' => 0],
]);
foreach (($result['values'] ?? []) as $pp) {
$label = $pp['payment_processor_type_id:label'] ?? '';
$isSquare = (
(!empty($pp['class_name']) && $pp['class_name'] === 'Payment_Square') ||
(!empty($label) && stripos($label, 'square') !== FALSE)
);
if ($isSquare && ((int) ($pp['billing_mode'] ?? 0) !== 1)) {
civicrm_api3('PaymentProcessor', 'create', [
'id' => $pp['id'],
'billing_mode' => 1,
]);
}
}
}
if (class_exists('\\Civi')) {
\Civi::settings()->set('org_uschess_square_billing_mode_fixed', 1);
}
}
catch (Exception $e) {
// Non-fatal: if we can't auto-fix, the admin can update billing_mode manually.
CRM_Core_Error::debug_log_message('Square: Unable to enforce on-site billing_mode: ' . $e->getMessage());
}
}
/**
* Implementation of hook_civicrm_disable().
*/
function org_uschess_square_civicrm_disable() {
_org_uschess_square_civix_civicrm_disable();
}
/**
* Implementation of hook_civicrm_upgrade().
*/
function org_uschess_square_civicrm_upgrade($op, CRM_Queue_Queue $queue = NULL) {
return _org_uschess_square_civix_civicrm_upgrade($op, $queue);
}
/**
* Implementation of hook_civicrm_managed().
*/
function org_uschess_square_civicrm_managed(&$entities) {
_org_uschess_square_civix_civicrm_managed($entities);
}
/**
* Add hidden square_payment_token field to native CiviCRM contribution/event forms.
*
* Markup, JS, and settings injection is now handled by
* CRM_Core_Payment_Square::buildForm() which fires for ALL contexts including
* Drupal Webform AJAX billing block requests. This hook only adds the hidden
* field that carries the Square nonce back to the server on native forms.
*
* @param string $formName
* @param CRM_Core_Form $form
*/
function org_uschess_square_civicrm_buildForm($formName, &$form) {
// Only act on native contribution and event registration forms.
if (!in_array($formName, ['CRM_Contribute_Form_Contribution', 'CRM_Event_Form_Registration'], TRUE)) {
return;
}
// Get payment processor currently in use.
$processor = $form->getVar('_paymentProcessor');
if (empty($processor)) {
return;
}
// Only if this is the Square processor.
$className = $processor['class_name'] ?? '';
if ($className !== 'Payment_Square' && $className !== 'CRM_Core_Payment_Square') {
return;
}
// Hidden field where the JS will store the Square card nonce before submit.
if (!$form->elementExists('square_payment_token')) {
$form->add('hidden', 'square_payment_token', '', ['id' => 'square_payment_token']);
}
}
/**
* Implementation of hook_civicrm_post().
*
* Handles edits and cancellations to recurring contributions that
* are processed by the Square payment processor.
*/
function org_uschess_square_civicrm_post($op, $objectName, $objectId, &$objectRef) {
// We only care about edits and deletes to recurring contribution records.
if ($objectName !== 'ContributionRecur' || !in_array($op, ['edit', 'delete'], TRUE)) {
return;
}
// Ensure API4 is available.
if (!class_exists('\\Civi\\Api4\\ContributionRecur')) {
CRM_Core_Error::debug_log_message('Square: API4 ContributionRecur class not available in civicrm_post.');
return;
}
try {
// Load the recurring contribution record.
$recur = \Civi\Api4\ContributionRecur::get(FALSE)
->addSelect('id', 'payment_processor_id', 'amount', 'contribution_status_id', 'frequency_interval', 'frequency_unit', 'processor_id')
->addWhere('id', '=', (int) $objectId)
->execute()
->first();
if (empty($recur) || empty($recur['payment_processor_id'])) {
return;
}
// Load the payment processor to see if it is a Square processor.
$processor = \Civi\Api4\PaymentProcessor::get(FALSE)
->addSelect('id', 'name', 'class_name', 'payment_processor_type_id:label', 'is_test')
->addWhere('id', '=', (int) $recur['payment_processor_id'])
->execute()
->first();
if (empty($processor)) {
return;
}
// We treat this as a Square-backed recurring contribution either if the
// class_name is Payment_Square or the type label contains 'Square'.
$isSquare = (
(!empty($processor['class_name']) && $processor['class_name'] === 'Payment_Square') ||
(!empty($processor['payment_processor_type_id:label']) && stripos($processor['payment_processor_type_id:label'], 'square') !== FALSE)
);
if (!$isSquare) {
return;
}
// Handle cancellation (status_id = 3 is Cancelled)
if ($op === 'edit' && !empty($recur['processor_id'])) {
$oldStatus = $objectRef->contribution_status_id ?? NULL;
$newStatus = $recur['contribution_status_id'] ?? NULL;
// Check if status changed to Cancelled (3)
if ($newStatus == 3 && $oldStatus != 3) {
// Cancel the Square subscription
try {
$mode = !empty($processor['is_test']) ? 'test' : 'live';
$squareProcessor = new CRM_Core_Payment_Square($mode, $processor);
$squareProcessor->cancelSquareSubscription($recur['processor_id']);
CRM_Core_Error::debug_log_message(sprintf(
'Square: Cancelled subscription %s for recurring contribution #%d',
$recur['processor_id'],
$recur['id']
));
}
catch (Exception $e) {
CRM_Core_Error::debug_log_message('Square: Error cancelling subscription: ' . $e->getMessage());
}
}
// Handle amount changes
elseif (!empty($recur['processor_id']) && !empty($objectRef->amount)) {
$oldAmount = $objectRef->amount ?? NULL;
$newAmount = $recur['amount'] ?? NULL;
if ($oldAmount != $newAmount && $newAmount > 0) {
try {
$mode = !empty($processor['is_test']) ? 'test' : 'live';
$squareProcessor = new CRM_Core_Payment_Square($mode, $processor);
$currency = $recur['currency'] ?? 'USD';
$squareProcessor->updateSubscriptionAmount($recur['processor_id'], $newAmount, $currency);
CRM_Core_Error::debug_log_message(sprintf(
'Square: Updated subscription %s amount from %s to %s for recurring contribution #%d',
$recur['processor_id'],
$oldAmount,
$newAmount,
$recur['id']
));
}
catch (Exception $e) {
CRM_Core_Error::debug_log_message('Square: Error updating subscription amount: ' . $e->getMessage());
}
}
}
}
// Log all edits for debugging
CRM_Core_Error::debug_log_message(sprintf(
'Square: ContributionRecur #%d %s (amount=%s, status_id=%s, freq=%s %s, processor_id=%s).',
$recur['id'],
$op,
$recur['amount'] ?? 'n/a',
$recur['contribution_status_id'] ?? 'n/a',
$recur['frequency_interval'] ?? 'n/a',
$recur['frequency_unit'] ?? 'n/a',
$recur['processor_id'] ?? 'n/a'
));
}
catch (Exception $e) {
CRM_Core_Error::debug_log_message('Square: Error in civicrm_post ContributionRecur handler: ' . $e->getMessage());
}
}