Commit | Line | Data |
---|---|---|
6a488035 TO |
1 | <?php |
2 | /* | |
3 | +--------------------------------------------------------------------+ | |
bc77d7c0 | 4 | | Copyright CiviCRM LLC. All rights reserved. | |
6a488035 | 5 | | | |
bc77d7c0 TO |
6 | | This work is published under the GNU AGPLv3 license with some | |
7 | | permitted exceptions and without any warranty. For full license | | |
8 | | and copyright information, see https://civicrm.org/licensing | | |
6a488035 | 9 | +--------------------------------------------------------------------+ |
d25dd0ee | 10 | */ |
6a488035 | 11 | |
ec022878 | 12 | use Civi\Payment\Exception\PaymentProcessorException; |
13 | ||
6a488035 TO |
14 | /** |
15 | * | |
16 | * @package CRM | |
ca5cec67 | 17 | * @copyright CiviCRM LLC https://civicrm.org/licensing |
5fb28746 EM |
18 | */ |
19 | ||
20 | /** | |
21 | * Class CRM_Core_Payment_PayPalImpl for paypal pro, paypal standard & paypal express. | |
6a488035 TO |
22 | */ |
23 | class CRM_Core_Payment_PayPalImpl extends CRM_Core_Payment { | |
7da04cde | 24 | const CHARSET = 'iso-8859-1'; |
6a488035 | 25 | |
8acddb67 | 26 | const PAYPAL_PRO = 'PayPal'; |
27 | const PAYPAL_STANDARD = 'PayPal_Standard'; | |
28 | const PAYPAL_EXPRESS = 'PayPal_Express'; | |
29 | ||
6a488035 TO |
30 | protected $_mode = NULL; |
31 | ||
6a488035 | 32 | /** |
fe482240 | 33 | * Constructor. |
6a488035 | 34 | * |
6a0b768e TO |
35 | * @param string $mode |
36 | * The mode of operation: live or test. | |
6a488035 | 37 | * |
e58c1c1a | 38 | * @param CRM_Core_Payment $paymentProcessor |
77b97be7 EM |
39 | * |
40 | * @return \CRM_Core_Payment_PayPalImpl | |
8acddb67 | 41 | * @throws \Civi\Payment\Exception\PaymentProcessorException |
6a488035 | 42 | */ |
00be9182 | 43 | public function __construct($mode, &$paymentProcessor) { |
6a488035 TO |
44 | $this->_mode = $mode; |
45 | $this->_paymentProcessor = $paymentProcessor; | |
8acddb67 | 46 | } |
6a488035 | 47 | |
15912a4d | 48 | /** |
49 | * @var GuzzleHttp\Client | |
50 | */ | |
51 | protected $guzzleClient; | |
52 | ||
53 | /** | |
54 | * @return \GuzzleHttp\Client | |
55 | */ | |
56 | public function getGuzzleClient(): \GuzzleHttp\Client { | |
57 | return $this->guzzleClient ?? new \GuzzleHttp\Client(); | |
58 | } | |
59 | ||
60 | /** | |
61 | * @param \GuzzleHttp\Client $guzzleClient | |
62 | */ | |
63 | public function setGuzzleClient(\GuzzleHttp\Client $guzzleClient) { | |
64 | $this->guzzleClient = $guzzleClient; | |
65 | } | |
66 | ||
8acddb67 | 67 | /** |
68 | * Helper function to check which payment processor type is being used. | |
69 | * | |
70 | * @param $typeName | |
71 | * | |
72 | * @return bool | |
73 | * @throws \Civi\Payment\Exception\PaymentProcessorException | |
74 | */ | |
75 | public function isPayPalType($typeName) { | |
76 | // Historically payment_processor_type may have been set to the name of the processor but newer versions of CiviCRM use the id set in payment_processor_type_id | |
77 | if (empty($this->_paymentProcessor['payment_processor_type_id']) && empty($this->_paymentProcessor['payment_processor_type'])) { | |
78 | // We need one of them to be set! | |
79 | throw new PaymentProcessorException('CRM_Core_Payment_PayPalImpl: Payment processor type is not defined!'); | |
80 | } | |
81 | if (empty($this->_paymentProcessor['payment_processor_type_id']) && !empty($this->_paymentProcessor['payment_processor_type'])) { | |
82 | // Handle legacy case where payment_processor_type was set, but payment_processor_type_id was not. | |
83 | $this->_paymentProcessor['payment_processor_type_id'] | |
84 | = CRM_Core_PseudoConstant::getKey('CRM_Financial_BAO_PaymentProcessor', 'payment_processor_type_id', $this->_paymentProcessor['payment_processor_type']); | |
85 | } | |
86 | if ((int) $this->_paymentProcessor['payment_processor_type_id'] === | |
87 | CRM_Core_PseudoConstant::getKey('CRM_Financial_BAO_PaymentProcessor', 'payment_processor_type_id', $typeName)) { | |
88 | return TRUE; | |
89 | } | |
90 | return FALSE; | |
6a488035 TO |
91 | } |
92 | ||
fbcb6fba | 93 | /** |
e58c1c1a | 94 | * Are back office payments supported. |
95 | * | |
96 | * E.g paypal standard won't permit you to enter a credit card associated | |
97 | * with someone else's login. | |
98 | * | |
fbcb6fba | 99 | * @return bool |
8acddb67 | 100 | * @throws \Civi\Payment\Exception\PaymentProcessorException |
fbcb6fba | 101 | */ |
d8ce0d68 | 102 | protected function supportsBackOffice() { |
e491d0c9 | 103 | if ($this->isPayPalType($this::PAYPAL_PRO)) { |
fbcb6fba EM |
104 | return TRUE; |
105 | } | |
106 | return FALSE; | |
107 | } | |
353ffa53 | 108 | |
3910048c EM |
109 | /** |
110 | * Does this processor support pre-approval. | |
111 | * | |
112 | * This would generally look like a redirect to enter credentials which can then be used in a later payment call. | |
113 | * | |
114 | * Currently Paypal express supports this, with a redirect to paypal after the 'Main' form is submitted in the | |
115 | * contribution page. This token can then be processed at the confirm phase. Although this flow 'looks' like the | |
116 | * 'notify' flow a key difference is that in the notify flow they don't have to return but in this flow they do. | |
117 | * | |
118 | * @return bool | |
8acddb67 | 119 | * @throws \Civi\Payment\Exception\PaymentProcessorException |
3910048c EM |
120 | */ |
121 | protected function supportsPreApproval() { | |
e491d0c9 | 122 | if ($this->isPayPalType($this::PAYPAL_EXPRESS) || $this->isPayPalType($this::PAYPAL_PRO)) { |
3910048c EM |
123 | return TRUE; |
124 | } | |
125 | return FALSE; | |
126 | } | |
127 | ||
dbbd55dc EM |
128 | /** |
129 | * Opportunity for the payment processor to override the entire form build. | |
130 | * | |
131 | * @param CRM_Core_Form $form | |
132 | * | |
133 | * @return bool | |
134 | * Should form building stop at this point? | |
8acddb67 | 135 | * @throws \Civi\Payment\Exception\PaymentProcessorException |
dbbd55dc EM |
136 | */ |
137 | public function buildForm(&$form) { | |
aef7f33a | 138 | if ($this->supportsPreApproval()) { |
dbbd55dc | 139 | $this->addPaypalExpressCode($form); |
e491d0c9 | 140 | if ($this->isPayPalType($this::PAYPAL_EXPRESS)) { |
be2fb01f | 141 | CRM_Core_Region::instance('billing-block-post')->add([ |
31d31a05 | 142 | 'template' => 'CRM/Financial/Form/PaypalExpress.tpl', |
aefd7f6b | 143 | 'name' => 'paypal_express', |
be2fb01f | 144 | ]); |
31d31a05 | 145 | } |
e491d0c9 | 146 | if ($this->isPayPalType($this::PAYPAL_PRO)) { |
be2fb01f | 147 | CRM_Core_Region::instance('billing-block-pre')->add([ |
31d31a05 | 148 | 'template' => 'CRM/Financial/Form/PaypalPro.tpl', |
be2fb01f | 149 | ]); |
31d31a05 | 150 | } |
dbbd55dc EM |
151 | } |
152 | return FALSE; | |
153 | } | |
154 | ||
155 | /** | |
e58c1c1a | 156 | * Billing mode button is basically synonymous with paypal express. |
157 | * | |
158 | * This is probably a good example of 'odds & sods' code we | |
159 | * need to find a way for the payment processor to assign. | |
160 | * | |
161 | * A tricky aspect is that the payment processor may need to set the order | |
dbbd55dc | 162 | * |
416a7c99 | 163 | * @param CRM_Core_Form $form |
dbbd55dc | 164 | */ |
31d31a05 | 165 | protected function addPaypalExpressCode(&$form) { |
18135422 | 166 | // @todo use $this->isBackOffice() instead, test. |
dbbd55dc | 167 | if (empty($form->isBackOffice)) { |
5f0c586e SP |
168 | |
169 | /** | |
170 | * if payment method selected using ajax call then form object is of 'CRM_Financial_Form_Payment', | |
171 | * instead of 'CRM_Contribute_Form_Contribution_Main' so it generate wrong button name | |
172 | * and then clicking on express button it redirect to confirm screen rather than PayPal Express form | |
173 | */ | |
174 | ||
fb5e89bc | 175 | if ('CRM_Financial_Form_Payment' == get_class($form) && $form->_formName) { |
5f0c586e | 176 | $form->_expressButtonName = '_qf_' . $form->_formName . '_upload_express'; |
fb5e89bc SP |
177 | } |
178 | else { | |
179 | $form->_expressButtonName = $form->getButtonName('upload', 'express'); | |
180 | } | |
dbbd55dc | 181 | $form->assign('expressButtonName', $form->_expressButtonName); |
67afda37 SL |
182 | $form->add('xbutton', $form->_expressButtonName, ts('Pay using PayPal'), [ |
183 | 'type' => 'submit', | |
184 | 'formnovalidate' => 'formnovalidate', | |
185 | 'class' => 'crm-form-submit', | |
186 | ]); | |
187 | CRM_Core_Resources::singleton()->addStyle(' | |
188 | button#' . $form->_expressButtonName . '{ | |
189 | background-image: url(' . $this->_paymentProcessor['url_button'] . '); | |
190 | color: transparent; | |
191 | background-repeat: no-repeat; | |
192 | background-color: transparent; | |
193 | background-position: center; | |
194 | min-width: 150px; | |
195 | min-height: 50px; | |
196 | border: none; | |
197 | '); | |
dbbd55dc EM |
198 | } |
199 | } | |
200 | ||
677fe56c EM |
201 | /** |
202 | * Can recurring contributions be set against pledges. | |
203 | * | |
204 | * In practice all processors that use the baseIPN function to finish transactions or | |
205 | * call the completetransaction api support this by looking up previous contributions in the | |
206 | * series and, if there is a prior contribution against a pledge, and the pledge is not complete, | |
207 | * adding the new payment to the pledge. | |
208 | * | |
209 | * However, only enabling for processors it has been tested against. | |
210 | * | |
211 | * @return bool | |
212 | */ | |
213 | protected function supportsRecurContributionsForPledges() { | |
214 | return TRUE; | |
215 | } | |
216 | ||
8ccce14a | 217 | /** |
218 | * Default payment instrument validation. | |
219 | * | |
220 | * Implement the usual Luhn algorithm via a static function in the CRM_Core_Payment_Form if it's a credit card | |
221 | * Not a static function, because I need to check for payment_type. | |
222 | * | |
223 | * @param array $values | |
224 | * @param array $errors | |
8acddb67 | 225 | * |
226 | * @throws \Civi\Payment\Exception\PaymentProcessorException | |
8ccce14a | 227 | */ |
228 | public function validatePaymentInstrument($values, &$errors) { | |
e491d0c9 | 229 | if ($this->isPayPalType($this::PAYPAL_PRO) && !$this->isPaypalExpress($values)) { |
06051ca4 | 230 | CRM_Core_Payment_Form::validateCreditCard($values, $errors, $this->_paymentProcessor['id']); |
c319039f | 231 | CRM_Core_Form::validateMandatoryFields($this->getMandatoryFields(), $values, $errors); |
8ccce14a | 232 | } |
233 | } | |
234 | ||
6a488035 | 235 | /** |
e58c1c1a | 236 | * Express checkout code. |
237 | * | |
238 | * Check PayPal documentation for more information | |
6a488035 | 239 | * |
6a0b768e TO |
240 | * @param array $params |
241 | * Assoc array of input parameters for this transaction. | |
6a488035 | 242 | * |
a6c01b45 CW |
243 | * @return array |
244 | * the result in an nice formatted array (or an error object) | |
dbb0d30b | 245 | * @throws \Civi\Payment\Exception\PaymentProcessorException |
6a488035 | 246 | */ |
3a80832a | 247 | protected function setExpressCheckOut(&$params) { |
be2fb01f | 248 | $args = []; |
6a488035 TO |
249 | |
250 | $this->initialize($args, 'SetExpressCheckout'); | |
251 | ||
aefd7f6b | 252 | $args['paymentAction'] = 'Sale'; |
6a488035 TO |
253 | $args['amt'] = $params['amount']; |
254 | $args['currencyCode'] = $params['currencyID']; | |
9c1bc317 | 255 | $args['desc'] = $params['description'] ?? NULL; |
6a488035 | 256 | $args['invnum'] = $params['invoiceID']; |
aefd7f6b EM |
257 | $args['returnURL'] = $this->getReturnSuccessUrl($params['qfKey']); |
258 | $args['cancelURL'] = $this->getCancelUrl($params['qfKey'], NULL); | |
6a488035 | 259 | $args['version'] = '56.0'; |
7041ce4a | 260 | $args['SOLUTIONTYPE'] = 'Sole'; |
6a488035 TO |
261 | |
262 | //LCD if recurring, collect additional data and set some values | |
a7488080 | 263 | if (!empty($params['is_recur'])) { |
6a488035 TO |
264 | $args['L_BILLINGTYPE0'] = 'RecurringPayments'; |
265 | //$args['L_BILLINGAGREEMENTDESCRIPTION0'] = 'Recurring Contribution'; | |
266 | $args['L_BILLINGAGREEMENTDESCRIPTION0'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit']; | |
267 | $args['L_PAYMENTTYPE0'] = 'Any'; | |
268 | } | |
269 | ||
270 | // Allow further manipulation of the arguments via custom hooks .. | |
271 | CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $args); | |
272 | ||
273 | $result = $this->invokeAPI($args); | |
274 | ||
6a488035 TO |
275 | /* Success */ |
276 | ||
277 | return $result['token']; | |
278 | } | |
279 | ||
3105efd2 EM |
280 | /** |
281 | * Get any details that may be available to the payment processor due to an approval process having happened. | |
282 | * | |
283 | * In some cases the browser is redirected to enter details on a processor site. Some details may be available as a | |
284 | * result. | |
285 | * | |
286 | * @param array $storedDetails | |
287 | * | |
288 | * @return array | |
8acddb67 | 289 | * @throws \Civi\Payment\Exception\PaymentProcessorException |
3105efd2 EM |
290 | */ |
291 | public function getPreApprovalDetails($storedDetails) { | |
be2fb01f | 292 | return empty($storedDetails['token']) ? [] : $this->getExpressCheckoutDetails($storedDetails['token']); |
3105efd2 EM |
293 | } |
294 | ||
6a488035 | 295 | /** |
e58c1c1a | 296 | * Get details from paypal. |
297 | * | |
298 | * Check PayPal documentation for more information | |
6a488035 | 299 | * |
6a0b768e TO |
300 | * @param string $token |
301 | * The key associated with this transaction. | |
6a488035 | 302 | * |
a6c01b45 CW |
303 | * @return array |
304 | * the result in an nice formatted array (or an error object) | |
8acddb67 | 305 | * @throws \Civi\Payment\Exception\PaymentProcessorException |
6a488035 | 306 | */ |
00be9182 | 307 | public function getExpressCheckoutDetails($token) { |
be2fb01f | 308 | $args = []; |
6a488035 TO |
309 | |
310 | $this->initialize($args, 'GetExpressCheckoutDetails'); | |
311 | $args['token'] = $token; | |
312 | // LCD | |
313 | $args['method'] = 'GetExpressCheckoutDetails'; | |
314 | ||
315 | $result = $this->invokeAPI($args); | |
316 | ||
6a488035 | 317 | /* Success */ |
be2fb01f | 318 | $fieldMap = [ |
933da5b5 EM |
319 | 'token' => 'token', |
320 | 'payer_status' => 'payerstatus', | |
321 | 'payer_id' => 'payerid', | |
a9b50c7c N |
322 | 'billing_first_name' => 'firstname', |
323 | 'billing_middle_name' => 'middlename', | |
324 | 'billing_last_name' => 'lastname', | |
933da5b5 EM |
325 | 'street_address' => 'shiptostreet', |
326 | 'supplemental_address_1' => 'shiptostreet2', | |
327 | 'city' => 'shiptocity', | |
328 | 'postal_code' => 'shiptozip', | |
329 | 'state_province' => 'shiptostate', | |
330 | 'country' => 'shiptocountrycode', | |
be2fb01f | 331 | ]; |
933da5b5 | 332 | return $this->mapPaypalParamsToCivicrmParams($fieldMap, $result); |
6a488035 TO |
333 | } |
334 | ||
335 | /** | |
e58c1c1a | 336 | * Do the express checkout at paypal. |
6a488035 | 337 | * |
e58c1c1a | 338 | * Check PayPal documentation for more information |
da6b46f4 | 339 | * |
e58c1c1a | 340 | * @param array $params |
6a488035 | 341 | * |
a6c01b45 | 342 | * @return array |
e58c1c1a | 343 | * The result in an nice formatted array. |
344 | * | |
345 | * @throws \Civi\Payment\Exception\PaymentProcessorException | |
6a488035 | 346 | */ |
00be9182 | 347 | public function doExpressCheckout(&$params) { |
5fb28746 EM |
348 | if (!empty($params['is_recur'])) { |
349 | return $this->createRecurringPayments($params); | |
350 | } | |
be2fb01f | 351 | $args = []; |
6a488035 TO |
352 | |
353 | $this->initialize($args, 'DoExpressCheckoutPayment'); | |
6a488035 | 354 | $args['token'] = $params['token']; |
aefd7f6b | 355 | $args['paymentAction'] = 'Sale'; |
6a488035 TO |
356 | $args['amt'] = $params['amount']; |
357 | $args['currencyCode'] = $params['currencyID']; | |
358 | $args['payerID'] = $params['payer_id']; | |
359 | $args['invnum'] = $params['invoiceID']; | |
aefd7f6b EM |
360 | $args['returnURL'] = $this->getReturnSuccessUrl($params['qfKey']); |
361 | $args['cancelURL'] = $this->getCancelUrl($params['qfKey'], NULL); | |
fc7063a4 | 362 | $args['desc'] = $params['description']; |
6a488035 | 363 | |
ebf695c3 | 364 | // add CiviCRM BN code |
365 | $args['BUTTONSOURCE'] = 'CiviCRM_SP'; | |
366 | ||
6a488035 TO |
367 | $result = $this->invokeAPI($args); |
368 | ||
6a488035 | 369 | /* Success */ |
6a488035 | 370 | $params['trxn_id'] = $result['transactionid']; |
6a488035 | 371 | $params['fee_amount'] = $result['feeamt']; |
9c1bc317 | 372 | $params['net_amount'] = $result['settleamt'] ?? NULL; |
6a488035 | 373 | if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) { |
b26c99af | 374 | $params['net_amount'] = number_format(($params['gross_amount'] - $params['fee_amount']), 2); |
6a488035 TO |
375 | } |
376 | $params['payment_status'] = $result['paymentstatus']; | |
377 | $params['pending_reason'] = $result['pendingreason']; | |
f8453bef | 378 | if (!empty($params['is_recur'])) { |
379 | // See comment block. | |
455cd95d | 380 | $params['payment_status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending'); |
f8453bef | 381 | } |
382 | else { | |
455cd95d | 383 | $params['payment_status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'); |
f8453bef | 384 | } |
6a488035 TO |
385 | return $params; |
386 | } | |
387 | ||
6c786a9b | 388 | /** |
e58c1c1a | 389 | * Create recurring payments. |
390 | * | |
8acddb67 | 391 | * Use a pre-authorisation token to activate a recurring payment profile |
392 | * https://developer.paypal.com/docs/classic/api/merchant/CreateRecurringPaymentsProfile_API_Operation_NVP/ | |
393 | * | |
c490a46a | 394 | * @param array $params |
6c786a9b EM |
395 | * |
396 | * @return mixed | |
8acddb67 | 397 | * @throws \Exception |
6c786a9b | 398 | */ |
00be9182 | 399 | public function createRecurringPayments(&$params) { |
be2fb01f | 400 | $args = []; |
6a488035 TO |
401 | $this->initialize($args, 'CreateRecurringPaymentsProfile'); |
402 | ||
403 | $start_time = strtotime(date('m/d/Y')); | |
404 | $start_date = date('Y-m-d\T00:00:00\Z', $start_time); | |
405 | ||
406 | $args['token'] = $params['token']; | |
aefd7f6b | 407 | $args['paymentAction'] = 'Sale'; |
6a488035 TO |
408 | $args['amt'] = $params['amount']; |
409 | $args['currencyCode'] = $params['currencyID']; | |
410 | $args['payerID'] = $params['payer_id']; | |
411 | $args['invnum'] = $params['invoiceID']; | |
6a488035 TO |
412 | $args['profilestartdate'] = $start_date; |
413 | $args['method'] = 'CreateRecurringPaymentsProfile'; | |
414 | $args['billingfrequency'] = $params['frequency_interval']; | |
415 | $args['billingperiod'] = ucwords($params['frequency_unit']); | |
416 | $args['desc'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit']; | |
9c1bc317 | 417 | $args['totalbillingcycles'] = $params['installments'] ?? NULL; |
6a488035 | 418 | $args['version'] = '56.0'; |
6c552737 | 419 | $args['profilereference'] = "i={$params['invoiceID']}" . |
933da5b5 | 420 | "&m=" . |
1ac462d0 DL |
421 | "&c={$params['contactID']}" . |
422 | "&r={$params['contributionRecurID']}" . | |
423 | "&b={$params['contributionID']}" . | |
424 | "&p={$params['contributionPageID']}"; | |
6a488035 | 425 | |
a3caf338 | 426 | // add CiviCRM BN code |
427 | $args['BUTTONSOURCE'] = 'CiviCRM_SP'; | |
428 | ||
6a488035 TO |
429 | $result = $this->invokeAPI($args); |
430 | ||
819c0bd6 | 431 | /* Success - result looks like" |
432 | * array ( | |
433 | * 'profileid' => 'I-CP1U0PLG91R2', | |
434 | * 'profilestatus' => 'ActiveProfile', | |
435 | * 'timestamp' => '2018-05-07T03:55:52Z', | |
436 | * 'correlationid' => 'e717999e9bf62', | |
437 | * 'ack' => 'Success', | |
438 | * 'version' => '56.0', | |
439 | * 'build' => '39949200',) | |
6439290e | 440 | */ |
819c0bd6 | 441 | $params['trxn_id'] = $result['profileid']; |
442 | $params['payment_status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending'); | |
6a488035 TO |
443 | |
444 | return $params; | |
445 | } | |
e58c1c1a | 446 | |
6c786a9b | 447 | /** |
e58c1c1a | 448 | * Initialise. |
449 | * | |
6c786a9b EM |
450 | * @param $args |
451 | * @param $method | |
452 | */ | |
00be9182 | 453 | public function initialize(&$args, $method) { |
353ffa53 TO |
454 | $args['user'] = $this->_paymentProcessor['user_name']; |
455 | $args['pwd'] = $this->_paymentProcessor['password']; | |
456 | $args['version'] = 3.0; | |
6a488035 | 457 | $args['signature'] = $this->_paymentProcessor['signature']; |
9c1bc317 | 458 | $args['subject'] = $this->_paymentProcessor['subject'] ?? NULL; |
353ffa53 | 459 | $args['method'] = $method; |
6a488035 | 460 | } |
f8453bef | 461 | |
462 | /** | |
e1268958 | 463 | * Process payment - this function wraps around both doTransferCheckout and doDirectPayment. |
f8453bef | 464 | * |
465 | * The function ensures an exception is thrown & moves some of this logic out of the form layer and makes the forms | |
466 | * more agnostic. | |
467 | * | |
468 | * Payment processors should set payment_status_id. This function adds some historical defaults ie. the | |
469 | * assumption that if a 'doDirectPayment' processors comes back it completed the transaction & in fact | |
470 | * doTransferCheckout would not traditionally come back. | |
471 | * | |
472 | * doDirectPayment does not do an immediate payment for Authorize.net or Paypal so the default is assumed | |
473 | * to be Pending. | |
474 | * | |
475 | * Once this function is fully rolled out then it will be preferred for processors to throw exceptions than to | |
476 | * return Error objects | |
477 | * | |
478 | * @param array $params | |
479 | * | |
480 | * @param string $component | |
481 | * | |
482 | * @return array | |
483 | * Result array | |
484 | * | |
485 | * @throws \Civi\Payment\Exception\PaymentProcessorException | |
486 | */ | |
487 | public function doPayment(&$params, $component = 'contribute') { | |
42fcf598 | 488 | $this->_component = $component; |
e491d0c9 | 489 | if ($this->isPayPalType($this::PAYPAL_EXPRESS) || ($this->isPayPalType($this::PAYPAL_PRO) && !empty($params['token']))) { |
e58c1c1a | 490 | return $this->doExpressCheckout($params); |
f8453bef | 491 | } |
8e819886 | 492 | $result = $this->setStatusPaymentPending([]); |
42fcf598 MW |
493 | |
494 | // If we have a $0 amount, skip call to processor and set payment_status to Completed. | |
495 | // Conceivably a processor might override this - perhaps for setting up a token - but we don't | |
496 | // have an example of that at the mome. | |
497 | if ($params['amount'] == 0) { | |
8e819886 | 498 | $result = $this->setStatusPaymentCompleted($result); |
42fcf598 MW |
499 | return $result; |
500 | } | |
501 | ||
502 | if ($this->_paymentProcessor['billing_mode'] == 4) { | |
503 | $this->doPaymentRedirectToPayPal($params, $component); | |
504 | // redirect calls CiviExit() so execution is stopped | |
505 | } | |
506 | else { | |
507 | $result = $this->doPaymentPayPalButton($params, $component); | |
508 | if (is_array($result) && !isset($result['payment_status_id'])) { | |
509 | if (!empty($params['is_recur'])) { | |
8e819886 | 510 | $result = $this->setStatusPaymentPending($result); |
42fcf598 MW |
511 | } |
512 | else { | |
8e819886 | 513 | $result = $this->setStatusPaymentCompleted($result); |
42fcf598 MW |
514 | } |
515 | } | |
516 | } | |
517 | if (is_a($result, 'CRM_Core_Error')) { | |
518 | CRM_Core_Error::deprecatedFunctionWarning('payment processors should throw exceptions rather than return errors'); | |
519 | throw new PaymentProcessorException(CRM_Core_Error::getMessages($result)); | |
520 | } | |
521 | return $result; | |
f8453bef | 522 | } |
6a488035 | 523 | |
ecd36877 MW |
524 | /** |
525 | * Temporary function to catch transition to doPaymentPayPalButton() | |
526 | * @deprecated | |
527 | */ | |
528 | public function doDirectPayment(&$params) { | |
529 | CRM_Core_Error::deprecatedFunctionWarning('doPayment'); | |
530 | return $this->doPaymentPayPalButton($params); | |
531 | } | |
532 | ||
6a488035 TO |
533 | /** |
534 | * This function collects all the information from a web/api form and invokes | |
535 | * the relevant payment processor specific functions to perform the transaction | |
536 | * | |
6a0b768e TO |
537 | * @param array $params |
538 | * Assoc array of input parameters for this transaction. | |
6a488035 | 539 | * |
da6b46f4 | 540 | * @param string $component |
a6c01b45 CW |
541 | * @return array |
542 | * the result in an nice formatted array (or an error object) | |
8acddb67 | 543 | * @throws \Civi\Payment\Exception\PaymentProcessorException |
6a488035 | 544 | */ |
42fcf598 | 545 | public function doPaymentPayPalButton(&$params, $component = 'contribute') { |
be2fb01f | 546 | $args = []; |
6a488035 | 547 | |
8e819886 MW |
548 | $result = $this->setStatusPaymentPending([]); |
549 | ||
6a488035 TO |
550 | $this->initialize($args, 'DoDirectPayment'); |
551 | ||
aefd7f6b | 552 | $args['paymentAction'] = 'Sale'; |
88afada7 | 553 | $args['amt'] = $this->getAmount($params); |
899c09b3 | 554 | $args['currencyCode'] = $this->getCurrency($params); |
6a488035 TO |
555 | $args['invnum'] = $params['invoiceID']; |
556 | $args['ipaddress'] = $params['ip_address']; | |
557 | $args['creditCardType'] = $params['credit_card_type']; | |
558 | $args['acct'] = $params['credit_card_number']; | |
559 | $args['expDate'] = sprintf('%02d', $params['month']) . $params['year']; | |
560 | $args['cvv2'] = $params['cvv2']; | |
561 | $args['firstName'] = $params['first_name']; | |
562 | $args['lastName'] = $params['last_name']; | |
9c1bc317 | 563 | $args['email'] = $params['email'] ?? NULL; |
6a488035 TO |
564 | $args['street'] = $params['street_address']; |
565 | $args['city'] = $params['city']; | |
566 | $args['state'] = $params['state_province']; | |
567 | $args['countryCode'] = $params['country']; | |
568 | $args['zip'] = $params['postal_code']; | |
0ab1fbfb | 569 | $args['desc'] = substr(CRM_Utils_Array::value('description', $params), 0, 127); |
9c1bc317 | 570 | $args['custom'] = $params['accountingCode'] ?? NULL; |
6a488035 | 571 | |
ebf695c3 | 572 | // add CiviCRM BN code |
573 | $args['BUTTONSOURCE'] = 'CiviCRM_SP'; | |
574 | ||
6a488035 TO |
575 | if (CRM_Utils_Array::value('is_recur', $params) == 1) { |
576 | $start_time = strtotime(date('m/d/Y')); | |
577 | $start_date = date('Y-m-d\T00:00:00\Z', $start_time); | |
578 | ||
579 | $args['PaymentAction'] = 'Sale'; | |
580 | $args['billingperiod'] = ucwords($params['frequency_unit']); | |
581 | $args['billingfrequency'] = $params['frequency_interval']; | |
582 | $args['method'] = "CreateRecurringPaymentsProfile"; | |
583 | $args['profilestartdate'] = $start_date; | |
6c552737 | 584 | $args['desc'] = "" . |
1ac462d0 DL |
585 | $params['description'] . ": " . |
586 | $params['amount'] . " Per " . | |
587 | $params['frequency_interval'] . " " . | |
588 | $params['frequency_unit']; | |
88afada7 | 589 | $args['amt'] = $this->getAmount($params); |
9c1bc317 | 590 | $args['totalbillingcycles'] = $params['installments'] ?? NULL; |
6a488035 | 591 | $args['version'] = 56.0; |
6c552737 | 592 | $args['PROFILEREFERENCE'] = "" . |
1ac462d0 DL |
593 | "i=" . $params['invoiceID'] . "&m=" . $component . |
594 | "&c=" . $params['contactID'] . "&r=" . $params['contributionRecurID'] . | |
595 | "&b=" . $params['contributionID'] . "&p=" . $params['contributionPageID']; | |
6a488035 TO |
596 | } |
597 | ||
598 | // Allow further manipulation of the arguments via custom hooks .. | |
599 | CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $args); | |
600 | ||
8e819886 | 601 | $apiResult = $this->invokeAPI($args); |
6a488035 | 602 | |
6a488035 TO |
603 | $params['recurr_profile_id'] = NULL; |
604 | ||
605 | if (CRM_Utils_Array::value('is_recur', $params) == 1) { | |
8e819886 | 606 | $params['recurr_profile_id'] = $apiResult['profileid']; |
6a488035 TO |
607 | } |
608 | ||
609 | /* Success */ | |
8e819886 MW |
610 | $result = $this->setStatusPaymentCompleted($result); |
611 | $doQueryParams = [ | |
612 | 'gross_amount' => $apiResult['amt'] ?? NULL, | |
613 | 'trxn_id' => $apiResult['transactionid'] ?? NULL, | |
614 | 'is_recur' => $params['is_recur'] ?? FALSE, | |
615 | ]; | |
616 | $params = array_merge($params, $this->doQuery($doQueryParams)); | |
6a488035 | 617 | |
8e819886 MW |
618 | $result['fee_amount'] = $params['fee_amount'] ?? 0; |
619 | $result['trxn_id'] = $apiResult['transactionid'] ?? NULL; | |
620 | return $result; | |
6a488035 TO |
621 | } |
622 | ||
9d2f24ee | 623 | /** |
624 | * Query payment processor for details about a transaction. | |
625 | * | |
626 | * For paypal see : https://developer.paypal.com/webapps/developer/docs/classic/api/merchant/GetTransactionDetails_API_Operation_NVP/ | |
627 | * | |
628 | * @param array $params | |
629 | * Array of parameters containing one of: | |
630 | * - trxn_id Id of an individual transaction. | |
631 | * - processor_id Id of a recurring contribution series as stored in the civicrm_contribution_recur table. | |
632 | * | |
633 | * @return array | |
634 | * Extra parameters retrieved. | |
635 | * Any parameters retrievable through this should be documented in the function comments at | |
636 | * CRM_Core_Payment::doQuery. Currently | |
637 | * - fee_amount Amount of fee paid | |
638 | * | |
639 | * @throws \Civi\Payment\Exception\PaymentProcessorException | |
640 | */ | |
641 | public function doQuery($params) { | |
0bde274f | 642 | //CRM-18140 - trxn_id not returned for recurring paypal transaction |
643 | if (!empty($params['is_recur'])) { | |
be2fb01f | 644 | return []; |
0bde274f | 645 | } |
646 | elseif (empty($params['trxn_id'])) { | |
9d2f24ee | 647 | throw new \Civi\Payment\Exception\PaymentProcessorException('transaction id not set'); |
648 | } | |
be2fb01f | 649 | $args = [ |
9d2f24ee | 650 | 'TRANSACTIONID' => $params['trxn_id'], |
be2fb01f | 651 | ]; |
9d2f24ee | 652 | $this->initialize($args, 'GetTransactionDetails'); |
653 | $result = $this->invokeAPI($args); | |
be2fb01f | 654 | return [ |
9d2f24ee | 655 | 'fee_amount' => $result['feeamt'], |
8a2a56e9 | 656 | 'net_amount' => $params['gross_amount'] - $result['feeamt'], |
be2fb01f | 657 | ]; |
9d2f24ee | 658 | } |
659 | ||
6a488035 | 660 | /** |
fe482240 | 661 | * This function checks to see if we have the right config values. |
6a488035 | 662 | * |
8acddb67 | 663 | * @return null|string |
a6c01b45 | 664 | * the error message if any |
8acddb67 | 665 | * @throws \Civi\Payment\Exception\PaymentProcessorException |
6a488035 | 666 | */ |
00be9182 | 667 | public function checkConfig() { |
be2fb01f | 668 | $error = []; |
6a488035 | 669 | |
e491d0c9 | 670 | if (!$this->isPayPalType($this::PAYPAL_STANDARD)) { |
6a488035 | 671 | if (empty($this->_paymentProcessor['signature'])) { |
0501a7d6 | 672 | $error[] = ts('Signature is not set in the Administer » System Settings » Payment Processors.'); |
6a488035 TO |
673 | } |
674 | ||
675 | if (empty($this->_paymentProcessor['password'])) { | |
0501a7d6 | 676 | $error[] = ts('Password is not set in the Administer » System Settings » Payment Processors.'); |
6a488035 TO |
677 | } |
678 | } | |
75466733 | 679 | if (empty($this->_paymentProcessor['user_name'])) { |
1b9f9ca3 EM |
680 | $error[] = ts('User Name is not set in the Administer » System Settings » Payment Processors.'); |
681 | } | |
8bd72809 MW |
682 | if ($this->isPayPalType($this::PAYPAL_STANDARD)) { |
683 | if (empty($this->_paymentProcessor['url_site'])) { | |
684 | $error[] = ts('Site URL is not set (eg. https://www.paypal.com/ - https://www.sandbox.paypal.com/)'); | |
685 | } | |
686 | } | |
6a488035 TO |
687 | |
688 | if (!empty($error)) { | |
689 | return implode('<p>', $error); | |
690 | } | |
691 | else { | |
692 | return NULL; | |
693 | } | |
694 | } | |
695 | ||
6c786a9b | 696 | /** |
4f2c0e2a | 697 | * Get url for users to manage this recurring contribution for this processor. |
698 | * | |
699 | * @param int $entityID | |
5e21e0f3 | 700 | * @param string|null $entity |
4f2c0e2a | 701 | * @param string $action |
702 | * | |
703 | * @return string|null | |
704 | * @throws \CRM_Core_Exception | |
6c786a9b | 705 | */ |
4f2c0e2a | 706 | public function subscriptionURL($entityID = NULL, $entity = NULL, $action = 'cancel') { |
e491d0c9 | 707 | if ($this->isPayPalType($this::PAYPAL_STANDARD)) { |
4f2c0e2a | 708 | if ($action !== 'cancel') { |
709 | return NULL; | |
710 | } | |
6a488035 TO |
711 | return "{$this->_paymentProcessor['url_site']}cgi-bin/webscr?cmd=_subscr-find&alias=" . urlencode($this->_paymentProcessor['user_name']); |
712 | } | |
4f2c0e2a | 713 | return parent::subscriptionURL($entityID, $entity, $action); |
6a488035 TO |
714 | } |
715 | ||
b5c2afd0 | 716 | /** |
100fef9d | 717 | * Check whether a method is present ( & supported ) by the payment processor object. |
b5c2afd0 | 718 | * |
6a0b768e TO |
719 | * @param string $method |
720 | * Method to check for. | |
b5c2afd0 | 721 | * |
5c766a0b | 722 | * @return bool |
e491d0c9 | 723 | * @throws \Civi\Payment\Exception\PaymentProcessorException |
b5c2afd0 | 724 | */ |
1524a007 | 725 | public function isSupported($method) { |
e491d0c9 | 726 | if (!$this->isPayPalType($this::PAYPAL_PRO)) { |
6a488035 TO |
727 | // since subscription methods like cancelSubscription or updateBilling is not yet implemented / supported |
728 | // by standard or express. | |
729 | return FALSE; | |
730 | } | |
731 | return parent::isSupported($method); | |
732 | } | |
733 | ||
1ba4a3aa EM |
734 | /** |
735 | * Paypal express replaces the submit button with it's own. | |
736 | * | |
737 | * @return bool | |
738 | * Should the form button by suppressed? | |
e491d0c9 | 739 | * @throws \Civi\Payment\Exception\PaymentProcessorException |
1ba4a3aa EM |
740 | */ |
741 | public function isSuppressSubmitButtons() { | |
e491d0c9 | 742 | if ($this->isPayPalType($this::PAYPAL_EXPRESS)) { |
1ba4a3aa EM |
743 | return TRUE; |
744 | } | |
745 | return FALSE; | |
746 | } | |
747 | ||
6c786a9b EM |
748 | /** |
749 | * @param string $message | |
750 | * @param array $params | |
751 | * | |
4ae44cc6 | 752 | * @return bool |
e491d0c9 | 753 | * @throws \Civi\Payment\Exception\PaymentProcessorException |
6c786a9b | 754 | */ |
be2fb01f | 755 | public function cancelSubscription(&$message = '', $params = []) { |
ccc7f59c | 756 | if ($this->isPayPalType($this::PAYPAL_PRO) || $this->isPayPalType($this::PAYPAL_EXPRESS)) { |
be2fb01f | 757 | $args = []; |
6a488035 TO |
758 | $this->initialize($args, 'ManageRecurringPaymentsProfileStatus'); |
759 | ||
9c1bc317 | 760 | $args['PROFILEID'] = $params['subscriptionId'] ?? NULL; |
353ffa53 | 761 | $args['ACTION'] = 'Cancel'; |
9c1bc317 | 762 | $args['NOTE'] = $params['reason'] ?? NULL; |
6a488035 TO |
763 | |
764 | $result = $this->invokeAPI($args); | |
b813df8f | 765 | |
6a488035 TO |
766 | $message = "{$result['ack']}: profileid={$result['profileid']}"; |
767 | return TRUE; | |
768 | } | |
769 | return FALSE; | |
770 | } | |
771 | ||
5495e78a EM |
772 | /** |
773 | * Process incoming notification. | |
e491d0c9 MW |
774 | * |
775 | * @throws \CRM_Core_Exception | |
776 | * @throws \CiviCRM_API3_Exception | |
5495e78a | 777 | */ |
9645e182 | 778 | public function handlePaymentNotification() { |
ddc4b5af | 779 | $params = array_merge($_GET, $_REQUEST); |
780 | $q = explode('/', CRM_Utils_Array::value('q', $params, '')); | |
781 | $lastParam = array_pop($q); | |
782 | if (is_numeric($lastParam)) { | |
783 | $params['processor_id'] = $lastParam; | |
784 | } | |
be2fb01f | 785 | $result = civicrm_api3('PaymentProcessor', 'get', [ |
08e6409d AS |
786 | 'sequential' => 1, |
787 | 'id' => $params['processor_id'], | |
be2fb01f CW |
788 | 'api.PaymentProcessorType.getvalue' => ['return' => "name"], |
789 | ]); | |
b501170c AS |
790 | if (!$result['count']) { |
791 | throw new CRM_Core_Exception("Could not find a processor with the given processor_id value '{$params['processor_id']}'."); | |
792 | } | |
793 | ||
9c1bc317 | 794 | $paymentProcessorType = $result['values'][0]['api.PaymentProcessorType.getvalue'] ?? NULL; |
b501170c | 795 | switch ($paymentProcessorType) { |
08e6409d AS |
796 | case 'PayPal': |
797 | // "PayPal - Website Payments Pro" | |
798 | $paypalIPN = new CRM_Core_Payment_PayPalProIPN($params); | |
799 | break; | |
800 | ||
1577dc9f DS |
801 | case 'PayPal_Express': |
802 | // "PayPal - Express" | |
803 | $paypalIPN = new CRM_Core_Payment_PayPalProIPN($params); | |
b3679aa7 DS |
804 | break; |
805 | ||
08e6409d AS |
806 | case 'PayPal_Standard': |
807 | // "PayPal - Website Payments Standard" | |
808 | $paypalIPN = new CRM_Core_Payment_PayPalIPN($params); | |
809 | break; | |
810 | ||
811 | default: | |
812 | // If we don't have PayPal Standard or PayPal Pro, something's wrong. | |
813 | // Log an error and exit. | |
b501170c | 814 | throw new CRM_Core_Exception("The processor_id value '{$params['processor_id']}' is for a processor of type '{$paymentProcessorType}', which is invalid in this context."); |
ddc4b5af | 815 | } |
08e6409d | 816 | |
5495e78a EM |
817 | $paypalIPN->main(); |
818 | } | |
819 | ||
6c786a9b EM |
820 | /** |
821 | * @param string $message | |
822 | * @param array $params | |
823 | * | |
824 | * @return array|bool|object | |
8acddb67 | 825 | * @throws \Civi\Payment\Exception\PaymentProcessorException |
6c786a9b | 826 | */ |
be2fb01f | 827 | public function updateSubscriptionBillingInfo(&$message = '', $params = []) { |
e491d0c9 | 828 | if ($this->isPayPalType($this::PAYPAL_PRO)) { |
6a488035 | 829 | $config = CRM_Core_Config::singleton(); |
be2fb01f | 830 | $args = []; |
6a488035 TO |
831 | $this->initialize($args, 'UpdateRecurringPaymentsProfile'); |
832 | ||
833 | $args['PROFILEID'] = $params['subscriptionId']; | |
88afada7 | 834 | $args['AMT'] = $this->getAmount($params); |
6a488035 TO |
835 | $args['CURRENCYCODE'] = $config->defaultCurrency; |
836 | $args['CREDITCARDTYPE'] = $params['credit_card_type']; | |
837 | $args['ACCT'] = $params['credit_card_number']; | |
838 | $args['EXPDATE'] = sprintf('%02d', $params['month']) . $params['year']; | |
839 | $args['CVV2'] = $params['cvv2']; | |
840 | ||
353ffa53 TO |
841 | $args['FIRSTNAME'] = $params['first_name']; |
842 | $args['LASTNAME'] = $params['last_name']; | |
843 | $args['STREET'] = $params['street_address']; | |
844 | $args['CITY'] = $params['city']; | |
845 | $args['STATE'] = $params['state_province']; | |
6a488035 | 846 | $args['COUNTRYCODE'] = $params['postal_code']; |
353ffa53 | 847 | $args['ZIP'] = $params['country']; |
6a488035 TO |
848 | |
849 | $result = $this->invokeAPI($args); | |
b813df8f | 850 | |
6a488035 TO |
851 | $message = "{$result['ack']}: profileid={$result['profileid']}"; |
852 | return TRUE; | |
853 | } | |
854 | return FALSE; | |
855 | } | |
856 | ||
6c786a9b EM |
857 | /** |
858 | * @param string $message | |
859 | * @param array $params | |
860 | * | |
4ae44cc6 | 861 | * @return bool |
e491d0c9 | 862 | * @throws \Civi\Payment\Exception\PaymentProcessorException |
6c786a9b | 863 | */ |
be2fb01f | 864 | public function changeSubscriptionAmount(&$message = '', $params = []) { |
e491d0c9 | 865 | if ($this->isPayPalType($this::PAYPAL_PRO)) { |
6a488035 | 866 | $config = CRM_Core_Config::singleton(); |
be2fb01f | 867 | $args = []; |
6a488035 TO |
868 | $this->initialize($args, 'UpdateRecurringPaymentsProfile'); |
869 | ||
870 | $args['PROFILEID'] = $params['subscriptionId']; | |
88afada7 | 871 | $args['AMT'] = $this->getAmount($params); |
6a488035 TO |
872 | $args['CURRENCYCODE'] = $config->defaultCurrency; |
873 | $args['BILLINGFREQUENCY'] = $params['installments']; | |
874 | ||
875 | $result = $this->invokeAPI($args); | |
876 | CRM_Core_Error::debug_var('$result', $result); | |
b813df8f | 877 | |
6a488035 TO |
878 | $message = "{$result['ack']}: profileid={$result['profileid']}"; |
879 | return TRUE; | |
880 | } | |
881 | return FALSE; | |
882 | } | |
883 | ||
38b66756 EM |
884 | /** |
885 | * Function to action pre-approval if supported | |
886 | * | |
887 | * @param array $params | |
888 | * Parameters from the form | |
889 | * | |
890 | * @return array | |
891 | * - pre_approval_parameters (this will be stored on the calling form & available later) | |
892 | * - redirect_url (if set the browser will be redirected to this. | |
8acddb67 | 893 | * @throws \Civi\Payment\Exception\PaymentProcessorException |
38b66756 | 894 | */ |
3910048c | 895 | public function doPreApproval(&$params) { |
1d292cf3 | 896 | if (!$this->isPaypalExpress($params)) { |
be2fb01f | 897 | return []; |
ec022878 | 898 | } |
05c302ec | 899 | $this->_component = $params['component']; |
3910048c | 900 | $token = $this->setExpressCheckOut($params); |
39110928 | 901 | $siteUrl = rtrim($this->_paymentProcessor['url_site'], '/'); |
be2fb01f CW |
902 | return [ |
903 | 'pre_approval_parameters' => ['token' => $token], | |
39110928 | 904 | 'redirect_url' => $siteUrl . "/cgi-bin/webscr?cmd=_express-checkout&token=$token", |
be2fb01f | 905 | ]; |
3910048c EM |
906 | } |
907 | ||
ecd36877 MW |
908 | /** |
909 | * Temporary function to catch transition to doPaymentRedirectToPayPal() | |
910 | * @deprecated | |
911 | */ | |
912 | public function doTransferCheckout(&$params, $component = 'contribute') { | |
913 | CRM_Core_Error::deprecatedFunctionWarning('doPayment'); | |
914 | $this->doPaymentRedirectToPayPal($params); | |
915 | } | |
916 | ||
6c786a9b | 917 | /** |
c490a46a | 918 | * @param array $params |
6c786a9b EM |
919 | * @param string $component |
920 | * | |
921 | * @throws Exception | |
922 | */ | |
42fcf598 | 923 | public function doPaymentRedirectToPayPal(&$params, $component = 'contribute') { |
be2fb01f CW |
924 | $notifyParameters = ['module' => $component]; |
925 | $notifyParameterMap = [ | |
ddc4b5af | 926 | 'contactID' => 'contactID', |
927 | 'contributionID' => 'contributionID', | |
928 | 'eventID' => 'eventID', | |
929 | 'participantID' => 'participantID', | |
930 | 'membershipID' => 'membershipID', | |
931 | 'related_contact' => 'relatedContactID', | |
932 | 'onbehalf_dupe_alert' => 'onBehalfDupeAlert', | |
068fb0de | 933 | 'accountingCode' => 'accountingCode', |
11a4431c | 934 | 'contributionRecurID' => 'contributionRecurID', |
935 | 'contributionPageID' => 'contributionPageID', | |
be2fb01f | 936 | ]; |
ddc4b5af | 937 | foreach ($notifyParameterMap as $paramsName => $notifyName) { |
938 | if (!empty($params[$paramsName])) { | |
939 | $notifyParameters[$notifyName] = $params[$paramsName]; | |
6a488035 TO |
940 | } |
941 | } | |
ddc4b5af | 942 | $notifyURL = $this->getNotifyUrl(); |
6a488035 | 943 | |
ddc4b5af | 944 | $config = CRM_Core_Config::singleton(); |
353ffa53 TO |
945 | $url = ($component == 'event') ? 'civicrm/event/register' : 'civicrm/contribute/transact'; |
946 | $cancel = ($component == 'event') ? '_qf_Register_display' : '_qf_Main_display'; | |
6a488035 TO |
947 | |
948 | $cancelUrlString = "$cancel=1&cancel=1&qfKey={$params['qfKey']}"; | |
a7488080 | 949 | if (!empty($params['is_recur'])) { |
1ac462d0 | 950 | $cancelUrlString .= "&isRecur=1&recurId={$params['contributionRecurID']}&contribId={$params['contributionID']}"; |
6a488035 TO |
951 | } |
952 | ||
1ac462d0 DL |
953 | $cancelURL = CRM_Utils_System::url( |
954 | $url, | |
6a488035 TO |
955 | $cancelUrlString, |
956 | TRUE, NULL, FALSE | |
957 | ); | |
958 | ||
be2fb01f | 959 | $paypalParams = [ |
6a488035 TO |
960 | 'business' => $this->_paymentProcessor['user_name'], |
961 | 'notify_url' => $notifyURL, | |
683538c8 | 962 | 'item_name' => $this->getPaymentDescription($params, 127), |
6a488035 TO |
963 | 'quantity' => 1, |
964 | 'undefined_quantity' => 0, | |
965 | 'cancel_return' => $cancelURL, | |
966 | 'no_note' => 1, | |
967 | 'no_shipping' => 1, | |
ddc4b5af | 968 | 'return' => $this->getReturnSuccessUrl($params['qfKey']), |
6a488035 TO |
969 | 'rm' => 2, |
970 | 'currency_code' => $params['currencyID'], | |
971 | 'invoice' => $params['invoiceID'], | |
972 | 'lc' => substr($config->lcMessages, -2), | |
973 | 'charset' => function_exists('mb_internal_encoding') ? mb_internal_encoding() : 'UTF-8', | |
068fb0de | 974 | 'custom' => json_encode($notifyParameters), |
de753541 | 975 | 'bn' => 'CiviCRM_SP', |
be2fb01f | 976 | ]; |
6a488035 TO |
977 | |
978 | // add name and address if available, CRM-3130 | |
be2fb01f | 979 | $otherVars = [ |
6a488035 TO |
980 | 'first_name' => 'first_name', |
981 | 'last_name' => 'last_name', | |
982 | 'street_address' => 'address1', | |
983 | 'country' => 'country', | |
984 | 'preferred_language' => 'lc', | |
985 | 'city' => 'city', | |
986 | 'state_province' => 'state', | |
987 | 'postal_code' => 'zip', | |
988 | 'email' => 'email', | |
be2fb01f | 989 | ]; |
6a488035 TO |
990 | |
991 | foreach (array_keys($params) as $p) { | |
992 | // get the base name without the location type suffixed to it | |
993 | $parts = explode('-', $p); | |
994 | $name = count($parts) > 1 ? $parts[0] : $p; | |
995 | if (isset($otherVars[$name])) { | |
996 | $value = $params[$p]; | |
997 | if ($value) { | |
998 | if ($name == 'state_province') { | |
999 | $stateName = CRM_Core_PseudoConstant::stateProvinceAbbreviation($value); | |
1000 | $value = $stateName; | |
1001 | } | |
1002 | if ($name == 'country') { | |
1003 | $countryName = CRM_Core_PseudoConstant::countryIsoCode($value); | |
1004 | $value = $countryName; | |
1005 | } | |
1006 | // ensure value is not an array | |
1007 | // CRM-4174 | |
1008 | if (!is_array($value)) { | |
1009 | $paypalParams[$otherVars[$name]] = $value; | |
1010 | } | |
1011 | } | |
1012 | } | |
1013 | } | |
1014 | ||
1015 | // if recurring donations, add a few more items | |
1016 | if (!empty($params['is_recur'])) { | |
11a4431c | 1017 | if (!$params['contributionRecurID']) { |
2d296f18 | 1018 | throw new CRM_Core_Exception(ts('Recurring contribution, but no database id')); |
6a488035 TO |
1019 | } |
1020 | ||
be2fb01f | 1021 | $paypalParams += [ |
6a488035 | 1022 | 'cmd' => '_xclick-subscriptions', |
88afada7 | 1023 | 'a3' => $this->getAmount($params), |
353ffa53 TO |
1024 | 'p3' => $params['frequency_interval'], |
1025 | 't3' => ucfirst(substr($params['frequency_unit'], 0, 1)), | |
6a488035 TO |
1026 | 'src' => 1, |
1027 | 'sra' => 1, | |
6b409353 | 1028 | 'srt' => $params['installments'] ?? NULL, |
6a488035 TO |
1029 | 'no_note' => 1, |
1030 | 'modify' => 0, | |
be2fb01f | 1031 | ]; |
6a488035 TO |
1032 | } |
1033 | else { | |
be2fb01f | 1034 | $paypalParams += [ |
6a488035 TO |
1035 | 'cmd' => '_xclick', |
1036 | 'amount' => $params['amount'], | |
be2fb01f | 1037 | ]; |
6a488035 TO |
1038 | } |
1039 | ||
1040 | // Allow further manipulation of the arguments via custom hooks .. | |
1041 | CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $paypalParams); | |
1042 | ||
9b2d484f CW |
1043 | /* |
1044 | * PayPal urlencodes the IPN Notify URL. For sites not using Clean URLs (or | |
1045 | * using Shortcodes in WordPress) this results in "%2F" becoming "%252F" and | |
1046 | * therefore incomplete transactions. We need to prevent that. | |
1047 | * @see https://lab.civicrm.org/dev/core/-/issues/1931 | |
1048 | */ | |
1049 | $paypalParams['notify_url'] = rawurldecode($paypalParams['notify_url']); | |
1050 | ||
6a488035 TO |
1051 | $uri = ''; |
1052 | foreach ($paypalParams as $key => $value) { | |
1053 | if ($value === NULL) { | |
1054 | continue; | |
1055 | } | |
1056 | ||
1057 | $value = urlencode($value); | |
1058 | if ($key == 'return' || | |
1059 | $key == 'cancel_return' || | |
1060 | $key == 'notify_url' | |
1061 | ) { | |
1062 | $value = str_replace('%2F', '/', $value); | |
1063 | } | |
1064 | $uri .= "&{$key}={$value}"; | |
1065 | } | |
1066 | ||
353ffa53 TO |
1067 | $uri = substr($uri, 1); |
1068 | $url = $this->_paymentProcessor['url_site']; | |
1069 | $sub = empty($params['is_recur']) ? 'cgi-bin/webscr' : 'subscriptions'; | |
6a488035 TO |
1070 | $paypalURL = "{$url}{$sub}?$uri"; |
1071 | ||
bef5923d | 1072 | // Allow each CMS to do a pre-flight check before redirecting to PayPal. |
67a10cc4 | 1073 | CRM_Core_Config::singleton()->userSystem->prePostRedirect(); |
6a488035 TO |
1074 | CRM_Utils_System::redirect($paypalURL); |
1075 | } | |
1076 | ||
1077 | /** | |
ad37ac8e | 1078 | * Hash_call: Function to perform the API call to PayPal using API signature. |
1079 | * | |
6a488035 TO |
1080 | * @methodName is name of API method. |
1081 | * @nvpStr is nvp string. | |
ad37ac8e | 1082 | * returns an associative array containing the response from the server. |
1083 | * | |
1084 | * @param array $args | |
ad37ac8e | 1085 | * |
1086 | * @return array|object | |
5a57460f | 1087 | * @throws \Civi\Payment\Exception\PaymentProcessorException |
6a488035 | 1088 | */ |
b813df8f | 1089 | public function invokeAPI($args) { |
6a488035 | 1090 | |
b813df8f | 1091 | if (empty($this->_paymentProcessor['url_api'])) { |
1092 | throw new PaymentProcessorException(ts('Please set the API URL. Please refer to the documentation for more details')); | |
6a488035 TO |
1093 | } |
1094 | ||
b813df8f | 1095 | $url = $this->_paymentProcessor['url_api'] . 'nvp'; |
1096 | ||
be2fb01f | 1097 | $p = []; |
fa2c4d0b | 1098 | foreach ($args as $n => $v) { |
1099 | $p[] = "$n=" . urlencode($v); | |
1100 | } | |
1101 | ||
1102 | //NVPRequest for submitting to server | |
1103 | $nvpreq = implode('&', $p); | |
1104 | ||
6a488035 | 1105 | if (!function_exists('curl_init')) { |
b813df8f | 1106 | throw new PaymentProcessorException('curl functions NOT available.'); |
6a488035 TO |
1107 | } |
1108 | ||
15912a4d | 1109 | $response = (string) $this->getGuzzleClient()->post($url, [ |
1110 | 'body' => $nvpreq, | |
1111 | 'curl' => [ | |
1112 | CURLOPT_RETURNTRANSFER => TRUE, | |
1113 | CURLOPT_SSL_VERIFYPEER => Civi::settings()->get('verifySSL'), | |
1114 | ], | |
1115 | ])->getBody(); | |
6a488035 | 1116 | |
6a488035 TO |
1117 | $result = self::deformat($response); |
1118 | ||
15912a4d | 1119 | $outcome = strtolower($result['ack'] ?? ''); |
fa2c4d0b | 1120 | |
15912a4d | 1121 | if ($outcome !== 'success' && $outcome !== 'successwithwarning') { |
abfb35ee | 1122 | throw new PaymentProcessorException("{$result['l_shortmessage0']} {$result['l_longmessage0']}"); |
6a488035 TO |
1123 | } |
1124 | ||
1125 | return $result; | |
1126 | } | |
1127 | ||
be2e0c6a | 1128 | /** |
ad37ac8e | 1129 | * This function will take NVPString and convert it to an Associative Array. |
1130 | * | |
1131 | * It will decode the response. It is useful to search for a particular key and displaying arrays. | |
1132 | * | |
1133 | * @param string $str | |
1134 | * | |
1135 | * @return array | |
6a488035 | 1136 | */ |
00be9182 | 1137 | public static function deformat($str) { |
be2fb01f | 1138 | $result = []; |
6a488035 TO |
1139 | |
1140 | while (strlen($str)) { | |
b44e3f84 | 1141 | // position of key |
6a488035 TO |
1142 | $keyPos = strpos($str, '='); |
1143 | ||
1144 | // position of value | |
1145 | $valPos = strpos($str, '&') ? strpos($str, '&') : strlen($str); | |
1146 | ||
1147 | /*getting the Key and Value values and storing in a Associative Array*/ | |
1148 | ||
1149 | $key = substr($str, 0, $keyPos); | |
1150 | $val = substr($str, $keyPos + 1, $valPos - $keyPos - 1); | |
1151 | ||
1152 | //decoding the respose | |
1153 | $result[strtolower(urldecode($key))] = urldecode($val); | |
1154 | $str = substr($str, $valPos + 1, strlen($str)); | |
1155 | } | |
1156 | ||
1157 | return $result; | |
1158 | } | |
96025800 | 1159 | |
3cc8d80d | 1160 | /** |
1161 | * Get array of fields that should be displayed on the payment form. | |
1162 | * | |
1163 | * @return array | |
e491d0c9 | 1164 | * @throws \Civi\Payment\Exception\PaymentProcessorException |
3cc8d80d | 1165 | */ |
1166 | public function getPaymentFormFields() { | |
e491d0c9 | 1167 | if ($this->isPayPalType($this::PAYPAL_PRO)) { |
3cc8d80d | 1168 | return $this->getCreditCardFormFields(); |
1169 | } | |
1170 | else { | |
be2fb01f | 1171 | return []; |
3cc8d80d | 1172 | } |
1173 | } | |
1174 | ||
933da5b5 EM |
1175 | /** |
1176 | * Map the paypal params to CiviCRM params using a field map. | |
1177 | * | |
1178 | * @param array $fieldMap | |
1179 | * @param array $paypalParams | |
1180 | * | |
1181 | * @return array | |
1182 | */ | |
1183 | protected function mapPaypalParamsToCivicrmParams($fieldMap, $paypalParams) { | |
be2fb01f | 1184 | $params = []; |
933da5b5 | 1185 | foreach ($fieldMap as $civicrmField => $paypalField) { |
2e1f50d6 | 1186 | $params[$civicrmField] = $paypalParams[$paypalField] ?? NULL; |
933da5b5 EM |
1187 | } |
1188 | return $params; | |
1189 | } | |
1190 | ||
1d292cf3 | 1191 | /** |
1192 | * Is this being processed by payment express. | |
1193 | * | |
1194 | * Either because it is payment express or because is pro with paypal express in use. | |
1195 | * | |
1196 | * @param array $params | |
1197 | * | |
1198 | * @return bool | |
8acddb67 | 1199 | * @throws \Civi\Payment\Exception\PaymentProcessorException |
1d292cf3 | 1200 | */ |
1201 | protected function isPaypalExpress($params) { | |
e491d0c9 | 1202 | if ($this->isPayPalType($this::PAYPAL_EXPRESS)) { |
1d292cf3 | 1203 | return TRUE; |
1204 | } | |
1d292cf3 | 1205 | // This would occur postProcess. |
1206 | if (!empty($params['token'])) { | |
1207 | return TRUE; | |
1208 | } | |
1209 | if (isset($params['button']) && stristr($params['button'], 'express')) { | |
1210 | return TRUE; | |
1211 | } | |
1212 | ||
1213 | // The contribution form passes a 'button' but the event form might still set one of these fields. | |
1214 | // @todo more standardisation & get paypal fully out of the form layer. | |
be2fb01f | 1215 | $possibleExpressFields = [ |
ca748f0d | 1216 | // @todo - we think these top 2 are likely not required & it's still here |
1217 | // on a precautionary basis. | |
1218 | // see https://github.com/civicrm/civicrm-core/pull/18680 | |
1d292cf3 | 1219 | '_qf_Register_upload_express_x', |
1220 | '_qf_Payment_upload_express_x', | |
ca748f0d | 1221 | '_qf_Register_upload_express', |
1222 | '_qf_Payment_upload_express', | |
67afda37 | 1223 | '_qf_Main_upload_express', |
be2fb01f | 1224 | ]; |
1d292cf3 | 1225 | if (array_intersect_key($params, array_fill_keys($possibleExpressFields, 1))) { |
1226 | return TRUE; | |
1227 | } | |
1228 | return FALSE; | |
1229 | } | |
1230 | ||
6a488035 | 1231 | } |