3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
28 use Civi\Payment\Exception\PaymentProcessorException
;
33 * @copyright CiviCRM LLC (c) 2004-2017
37 * Class CRM_Core_Payment_PayPalImpl for paypal pro, paypal standard & paypal express.
39 class CRM_Core_Payment_PayPalImpl
extends CRM_Core_Payment
{
40 const CHARSET
= 'iso-8859-1';
42 protected $_mode = NULL;
48 * The mode of operation: live or test.
50 * @param CRM_Core_Payment $paymentProcessor
52 * @return \CRM_Core_Payment_PayPalImpl
54 public function __construct($mode, &$paymentProcessor) {
56 $this->_paymentProcessor
= $paymentProcessor;
57 $this->_processorName
= ts('PayPal Pro');
58 $paymentProcessorType = CRM_Core_PseudoConstant
::paymentProcessorType(FALSE, NULL, 'name');
60 if ($this->_paymentProcessor
['payment_processor_type_id'] == CRM_Utils_Array
::key('PayPal_Standard', $paymentProcessorType)) {
61 $this->_processorName
= ts('PayPal Standard');
64 elseif ($this->_paymentProcessor
['payment_processor_type_id'] == CRM_Utils_Array
::key('PayPal_Express', $paymentProcessorType)) {
65 $this->_processorName
= ts('PayPal Express');
71 * Are back office payments supported.
73 * E.g paypal standard won't permit you to enter a credit card associated
74 * with someone else's login.
78 protected function supportsBackOffice() {
79 if ($this->_processorName
== ts('PayPal Pro')) {
86 * Does this processor support pre-approval.
88 * This would generally look like a redirect to enter credentials which can then be used in a later payment call.
90 * Currently Paypal express supports this, with a redirect to paypal after the 'Main' form is submitted in the
91 * contribution page. This token can then be processed at the confirm phase. Although this flow 'looks' like the
92 * 'notify' flow a key difference is that in the notify flow they don't have to return but in this flow they do.
96 protected function supportsPreApproval() {
97 if ($this->_processorName
== ts('PayPal Express') ||
$this->_processorName
== ts('PayPal Pro')) {
104 * Opportunity for the payment processor to override the entire form build.
106 * @param CRM_Core_Form $form
109 * Should form building stop at this point?
111 public function buildForm(&$form) {
112 if ($this->supportsPreApproval()) {
113 $this->addPaypalExpressCode($form);
114 if ($this->_processorName
== ts('PayPal Express')) {
115 CRM_Core_Region
::instance('billing-block-post')->add(array(
116 'template' => 'CRM/Financial/Form/PaypalExpress.tpl',
117 'name' => 'paypal_express',
120 if ($this->_processorName
== ts('PayPal Pro')) {
121 CRM_Core_Region
::instance('billing-block-pre')->add(array(
122 'template' => 'CRM/Financial/Form/PaypalPro.tpl',
130 * Billing mode button is basically synonymous with paypal express.
132 * This is probably a good example of 'odds & sods' code we
133 * need to find a way for the payment processor to assign.
135 * A tricky aspect is that the payment processor may need to set the order
137 * @param CRM_Core_Form $form
139 protected function addPaypalExpressCode(&$form) {
140 // @todo use $this->isBackOffice() instead, test.
141 if (empty($form->isBackOffice
)) {
144 * if payment method selected using ajax call then form object is of 'CRM_Financial_Form_Payment',
145 * instead of 'CRM_Contribute_Form_Contribution_Main' so it generate wrong button name
146 * and then clicking on express button it redirect to confirm screen rather than PayPal Express form
149 if ('CRM_Financial_Form_Payment' == get_class($form) && $form->_formName
) {
150 $form->_expressButtonName
= '_qf_' . $form->_formName
. '_upload_express';
153 $form->_expressButtonName
= $form->getButtonName('upload', 'express');
155 $form->assign('expressButtonName', $form->_expressButtonName
);
158 $form->_expressButtonName
,
159 $this->_paymentProcessor
['url_button'],
160 array('class' => 'crm-form-submit')
166 * Can recurring contributions be set against pledges.
168 * In practice all processors that use the baseIPN function to finish transactions or
169 * call the completetransaction api support this by looking up previous contributions in the
170 * series and, if there is a prior contribution against a pledge, and the pledge is not complete,
171 * adding the new payment to the pledge.
173 * However, only enabling for processors it has been tested against.
177 protected function supportsRecurContributionsForPledges() {
182 * Default payment instrument validation.
184 * Implement the usual Luhn algorithm via a static function in the CRM_Core_Payment_Form if it's a credit card
185 * Not a static function, because I need to check for payment_type.
187 * @param array $values
188 * @param array $errors
190 public function validatePaymentInstrument($values, &$errors) {
191 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal' && !$this->isPaypalExpress($values)) {
192 CRM_Core_Payment_Form
::validateCreditCard($values, $errors, $this->_paymentProcessor
['id']);
193 CRM_Core_Form
::validateMandatoryFields($this->getMandatoryFields(), $values, $errors);
198 * Express checkout code.
200 * Check PayPal documentation for more information
202 * @param array $params
203 * Assoc array of input parameters for this transaction.
206 * the result in an nice formatted array (or an error object)
207 * @throws \Civi\Payment\Exception\PaymentProcessorException
209 protected function setExpressCheckOut(&$params) {
212 $this->initialize($args, 'SetExpressCheckout');
214 $args['paymentAction'] = 'Sale';
215 $args['amt'] = $params['amount'];
216 $args['currencyCode'] = $params['currencyID'];
217 $args['desc'] = CRM_Utils_Array
::value('description', $params);
218 $args['invnum'] = $params['invoiceID'];
219 $args['returnURL'] = $this->getReturnSuccessUrl($params['qfKey']);
220 $args['cancelURL'] = $this->getCancelUrl($params['qfKey'], NULL);
221 $args['version'] = '56.0';
223 //LCD if recurring, collect additional data and set some values
224 if (!empty($params['is_recur'])) {
225 $args['L_BILLINGTYPE0'] = 'RecurringPayments';
226 //$args['L_BILLINGAGREEMENTDESCRIPTION0'] = 'Recurring Contribution';
227 $args['L_BILLINGAGREEMENTDESCRIPTION0'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
228 $args['L_PAYMENTTYPE0'] = 'Any';
231 // Allow further manipulation of the arguments via custom hooks ..
232 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $args);
234 $result = $this->invokeAPI($args);
236 if (is_a($result, 'CRM_Core_Error')) {
237 throw new PaymentProcessorException($result->message
);
242 return $result['token'];
246 * Get any details that may be available to the payment processor due to an approval process having happened.
248 * In some cases the browser is redirected to enter details on a processor site. Some details may be available as a
251 * @param array $storedDetails
255 public function getPreApprovalDetails($storedDetails) {
256 return empty($storedDetails['token']) ?
array() : $this->getExpressCheckoutDetails($storedDetails['token']);
260 * Get details from paypal.
262 * Check PayPal documentation for more information
264 * @param string $token
265 * The key associated with this transaction.
268 * the result in an nice formatted array (or an error object)
270 public function getExpressCheckoutDetails($token) {
273 $this->initialize($args, 'GetExpressCheckoutDetails');
274 $args['token'] = $token;
276 $args['method'] = 'GetExpressCheckoutDetails';
278 $result = $this->invokeAPI($args);
280 if (is_a($result, 'CRM_Core_Error')) {
281 throw new PaymentProcessorException(CRM_Core_Error
::getMessages($result));
287 'payer_status' => 'payerstatus',
288 'payer_id' => 'payerid',
289 'first_name' => 'firstname',
290 'middle_name' => 'middlename',
291 'last_name' => 'lastname',
292 'street_address' => 'shiptostreet',
293 'supplemental_address_1' => 'shiptostreet2',
294 'city' => 'shiptocity',
295 'postal_code' => 'shiptozip',
296 'state_province' => 'shiptostate',
297 'country' => 'shiptocountrycode',
299 return $this->mapPaypalParamsToCivicrmParams($fieldMap, $result);
303 * Do the express checkout at paypal.
305 * Check PayPal documentation for more information
307 * @param array $params
310 * The result in an nice formatted array.
312 * @throws \Civi\Payment\Exception\PaymentProcessorException
314 public function doExpressCheckout(&$params) {
315 $statuses = CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id');
316 if (!empty($params['is_recur'])) {
317 return $this->createRecurringPayments($params);
321 $this->initialize($args, 'DoExpressCheckoutPayment');
322 $args['token'] = $params['token'];
323 $args['paymentAction'] = 'Sale';
324 $args['amt'] = $params['amount'];
325 $args['currencyCode'] = $params['currencyID'];
326 $args['payerID'] = $params['payer_id'];
327 $args['invnum'] = $params['invoiceID'];
328 $args['returnURL'] = $this->getReturnSuccessUrl($params['qfKey']);
329 $args['cancelURL'] = $this->getCancelUrl($params['qfKey'], NULL);
330 $args['desc'] = $params['description'];
332 // add CiviCRM BN code
333 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
335 $result = $this->invokeAPI($args);
337 if (is_a($result, 'CRM_Core_Error')) {
338 throw new PaymentProcessorException(CRM_Core_Error
::getMessages($result));
343 $params['trxn_id'] = $result['transactionid'];
344 $params['gross_amount'] = $result['amt'];
345 $params['fee_amount'] = $result['feeamt'];
346 $params['net_amount'] = CRM_Utils_Array
::value('settleamt', $result);
347 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
348 $params['net_amount'] = number_format(($params['gross_amount'] - $params['fee_amount']), 2);
350 $params['payment_status'] = $result['paymentstatus'];
351 $params['pending_reason'] = $result['pendingreason'];
352 if (!empty($params['is_recur'])) {
353 // See comment block.
354 $params['payment_status_id'] = array_search('Pending', $statuses);
357 $params['payment_status_id'] = array_search('Completed', $statuses);
363 * Create recurring payments.
365 * @param array $params
369 public function createRecurringPayments(&$params) {
371 // @todo this function is riddled with enotices - perhaps use $this->mapPaypalParamsToCivicrmParams($fieldMap, $result)
372 $this->initialize($args, 'CreateRecurringPaymentsProfile');
374 $start_time = strtotime(date('m/d/Y'));
375 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
377 $args['token'] = $params['token'];
378 $args['paymentAction'] = 'Sale';
379 $args['amt'] = $params['amount'];
380 $args['currencyCode'] = $params['currencyID'];
381 $args['payerID'] = $params['payer_id'];
382 $args['invnum'] = $params['invoiceID'];
383 $args['returnURL'] = $params['returnURL'];
384 $args['cancelURL'] = $params['cancelURL'];
385 $args['profilestartdate'] = $start_date;
386 $args['method'] = 'CreateRecurringPaymentsProfile';
387 $args['billingfrequency'] = $params['frequency_interval'];
388 $args['billingperiod'] = ucwords($params['frequency_unit']);
389 $args['desc'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
390 //$args['desc'] = 'Recurring Contribution';
391 $args['totalbillingcycles'] = $params['installments'];
392 $args['version'] = '56.0';
393 $args['profilereference'] = "i={$params['invoiceID']}" .
395 "&c={$params['contactID']}" .
396 "&r={$params['contributionRecurID']}" .
397 "&b={$params['contributionID']}" .
398 "&p={$params['contributionPageID']}";
400 // add CiviCRM BN code
401 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
403 $result = $this->invokeAPI($args);
405 if (is_a($result, 'CRM_Core_Error')) {
410 $params['trxn_id'] = $result['transactionid'];
411 $params['gross_amount'] = $result['amt'];
412 $params['fee_amount'] = $result['feeamt'];
413 $params['net_amount'] = $result['settleamt'];
414 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
415 $params['net_amount'] = number_format(($params['gross_amount'] - $params['fee_amount']), 2);
417 $params['payment_status'] = $result['paymentstatus'];
418 $params['pending_reason'] = $result['pendingreason'];
429 public function initialize(&$args, $method) {
430 $args['user'] = $this->_paymentProcessor
['user_name'];
431 $args['pwd'] = $this->_paymentProcessor
['password'];
432 $args['version'] = 3.0;
433 $args['signature'] = $this->_paymentProcessor
['signature'];
434 $args['subject'] = CRM_Utils_Array
::value('subject', $this->_paymentProcessor
);
435 $args['method'] = $method;
439 * Process payment - this function wraps around both doTransferPayment and doDirectPayment.
441 * The function ensures an exception is thrown & moves some of this logic out of the form layer and makes the forms
444 * Payment processors should set payment_status_id. This function adds some historical defaults ie. the
445 * assumption that if a 'doDirectPayment' processors comes back it completed the transaction & in fact
446 * doTransferCheckout would not traditionally come back.
448 * doDirectPayment does not do an immediate payment for Authorize.net or Paypal so the default is assumed
451 * Once this function is fully rolled out then it will be preferred for processors to throw exceptions than to
452 * return Error objects
454 * @param array $params
456 * @param string $component
461 * @throws \Civi\Payment\Exception\PaymentProcessorException
463 public function doPayment(&$params, $component = 'contribute') {
464 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal_Express'
465 ||
($this->_paymentProcessor
['payment_processor_type'] == 'PayPal' && !empty($params['token']))
467 $this->_component
= $component;
468 return $this->doExpressCheckout($params);
471 return parent
::doPayment($params, $component);
475 * This function collects all the information from a web/api form and invokes
476 * the relevant payment processor specific functions to perform the transaction
478 * @param array $params
479 * Assoc array of input parameters for this transaction.
481 * @param string $component
483 * the result in an nice formatted array (or an error object)
485 public function doDirectPayment(&$params, $component = 'contribute') {
488 $this->initialize($args, 'DoDirectPayment');
490 $args['paymentAction'] = 'Sale';
491 $args['amt'] = $this->getAmount($params);
492 $args['currencyCode'] = $this->getCurrency($params);
493 $args['invnum'] = $params['invoiceID'];
494 $args['ipaddress'] = $params['ip_address'];
495 $args['creditCardType'] = $params['credit_card_type'];
496 $args['acct'] = $params['credit_card_number'];
497 $args['expDate'] = sprintf('%02d', $params['month']) . $params['year'];
498 $args['cvv2'] = $params['cvv2'];
499 $args['firstName'] = $params['first_name'];
500 $args['lastName'] = $params['last_name'];
501 $args['email'] = CRM_Utils_Array
::value('email', $params);
502 $args['street'] = $params['street_address'];
503 $args['city'] = $params['city'];
504 $args['state'] = $params['state_province'];
505 $args['countryCode'] = $params['country'];
506 $args['zip'] = $params['postal_code'];
507 $args['desc'] = substr(CRM_Utils_Array
::value('description', $params), 0, 127);
508 $args['custom'] = CRM_Utils_Array
::value('accountingCode', $params);
510 // add CiviCRM BN code
511 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
513 if (CRM_Utils_Array
::value('is_recur', $params) == 1) {
514 $start_time = strtotime(date('m/d/Y'));
515 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
517 $args['PaymentAction'] = 'Sale';
518 $args['billingperiod'] = ucwords($params['frequency_unit']);
519 $args['billingfrequency'] = $params['frequency_interval'];
520 $args['method'] = "CreateRecurringPaymentsProfile";
521 $args['profilestartdate'] = $start_date;
523 $params['description'] . ": " .
524 $params['amount'] . " Per " .
525 $params['frequency_interval'] . " " .
526 $params['frequency_unit'];
527 $args['amt'] = $this->getAmount($params);
528 $args['totalbillingcycles'] = CRM_Utils_Array
::value('installments', $params);
529 $args['version'] = 56.0;
530 $args['PROFILEREFERENCE'] = "" .
531 "i=" . $params['invoiceID'] . "&m=" . $component .
532 "&c=" . $params['contactID'] . "&r=" . $params['contributionRecurID'] .
533 "&b=" . $params['contributionID'] . "&p=" . $params['contributionPageID'];
536 // Allow further manipulation of the arguments via custom hooks ..
537 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $args);
539 $result = $this->invokeAPI($args);
542 if (is_a($result, 'CRM_Core_Error')) {
546 $params['recurr_profile_id'] = NULL;
548 if (CRM_Utils_Array
::value('is_recur', $params) == 1) {
549 $params['recurr_profile_id'] = $result['profileid'];
554 $params['trxn_id'] = CRM_Utils_Array
::value('transactionid', $result);
555 $params['gross_amount'] = CRM_Utils_Array
::value('amt', $result);
556 $params = array_merge($params, $this->doQuery($params));
561 * Query payment processor for details about a transaction.
563 * For paypal see : https://developer.paypal.com/webapps/developer/docs/classic/api/merchant/GetTransactionDetails_API_Operation_NVP/
565 * @param array $params
566 * Array of parameters containing one of:
567 * - trxn_id Id of an individual transaction.
568 * - processor_id Id of a recurring contribution series as stored in the civicrm_contribution_recur table.
571 * Extra parameters retrieved.
572 * Any parameters retrievable through this should be documented in the function comments at
573 * CRM_Core_Payment::doQuery. Currently
574 * - fee_amount Amount of fee paid
576 * @throws \Civi\Payment\Exception\PaymentProcessorException
578 public function doQuery($params) {
579 //CRM-18140 - trxn_id not returned for recurring paypal transaction
580 if (!empty($params['is_recur'])) {
583 elseif (empty($params['trxn_id'])) {
584 throw new \Civi\Payment\Exception\
PaymentProcessorException('transaction id not set');
587 'TRANSACTIONID' => $params['trxn_id'],
589 $this->initialize($args, 'GetTransactionDetails');
590 $result = $this->invokeAPI($args);
592 'fee_amount' => $result['feeamt'],
593 'net_amount' => $params['gross_amount'] - $result['feeamt'],
598 * This function checks to see if we have the right config values.
601 * the error message if any
603 public function checkConfig() {
605 $paymentProcessorType = CRM_Core_PseudoConstant
::paymentProcessorType(FALSE, NULL, 'name');
607 if ($this->_paymentProcessor
['payment_processor_type_id'] != CRM_Utils_Array
::key('PayPal_Standard', $paymentProcessorType)) {
608 if (empty($this->_paymentProcessor
['signature'])) {
609 $error[] = ts('Signature is not set in the Administer » System Settings » Payment Processors.');
612 if (empty($this->_paymentProcessor
['password'])) {
613 $error[] = ts('Password is not set in the Administer » System Settings » Payment Processors.');
616 if (empty($this->_paymentProcessor
['user_name'])) {
617 $error[] = ts('User Name is not set in the Administer » System Settings » Payment Processors.');
620 if (!empty($error)) {
621 return implode('<p>', $error);
629 * @return null|string
631 public function cancelSubscriptionURL() {
632 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal_Standard') {
633 return "{$this->_paymentProcessor['url_site']}cgi-bin/webscr?cmd=_subscr-find&alias=" . urlencode($this->_paymentProcessor
['user_name']);
641 * Check whether a method is present ( & supported ) by the payment processor object.
643 * @param string $method
644 * Method to check for.
648 public function isSupported($method) {
649 if ($this->_paymentProcessor
['payment_processor_type'] != 'PayPal') {
650 // since subscription methods like cancelSubscription or updateBilling is not yet implemented / supported
651 // by standard or express.
654 return parent
::isSupported($method);
658 * Paypal express replaces the submit button with it's own.
661 * Should the form button by suppressed?
663 public function isSuppressSubmitButtons() {
664 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal_Express') {
671 * @param string $message
672 * @param array $params
674 * @return array|bool|object
676 public function cancelSubscription(&$message = '', $params = array()) {
677 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal') {
679 $this->initialize($args, 'ManageRecurringPaymentsProfileStatus');
681 $args['PROFILEID'] = CRM_Utils_Array
::value('subscriptionId', $params);
682 $args['ACTION'] = 'Cancel';
683 $args['NOTE'] = CRM_Utils_Array
::value('reason', $params);
685 $result = $this->invokeAPI($args);
686 if (is_a($result, 'CRM_Core_Error')) {
689 $message = "{$result['ack']}: profileid={$result['profileid']}";
696 * Process incoming notification.
698 static public function handlePaymentNotification() {
699 $params = array_merge($_GET, $_REQUEST);
700 $q = explode('/', CRM_Utils_Array
::value('q', $params, ''));
701 $lastParam = array_pop($q);
702 if (is_numeric($lastParam)) {
703 $params['processor_id'] = $lastParam;
705 if (civicrm_api3('PaymentProcessor', 'getvalue', array(
706 'id' => $params['processor_id'],
707 'return' => 'class_name')
708 ) == 'Payment_PayPalImpl') {
709 $paypalIPN = new CRM_Core_Payment_PayPalIPN($params);
712 $paypalIPN = new CRM_Core_Payment_PayPalProIPN($params);
718 * @param string $message
719 * @param array $params
721 * @return array|bool|object
723 public function updateSubscriptionBillingInfo(&$message = '', $params = array()) {
724 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal') {
725 $config = CRM_Core_Config
::singleton();
727 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
729 $args['PROFILEID'] = $params['subscriptionId'];
730 $args['AMT'] = $this->getAmount($params);
731 $args['CURRENCYCODE'] = $config->defaultCurrency
;
732 $args['CREDITCARDTYPE'] = $params['credit_card_type'];
733 $args['ACCT'] = $params['credit_card_number'];
734 $args['EXPDATE'] = sprintf('%02d', $params['month']) . $params['year'];
735 $args['CVV2'] = $params['cvv2'];
737 $args['FIRSTNAME'] = $params['first_name'];
738 $args['LASTNAME'] = $params['last_name'];
739 $args['STREET'] = $params['street_address'];
740 $args['CITY'] = $params['city'];
741 $args['STATE'] = $params['state_province'];
742 $args['COUNTRYCODE'] = $params['postal_code'];
743 $args['ZIP'] = $params['country'];
745 $result = $this->invokeAPI($args);
746 if (is_a($result, 'CRM_Core_Error')) {
749 $message = "{$result['ack']}: profileid={$result['profileid']}";
756 * @param string $message
757 * @param array $params
759 * @return array|bool|object
761 public function changeSubscriptionAmount(&$message = '', $params = array()) {
762 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal') {
763 $config = CRM_Core_Config
::singleton();
765 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
767 $args['PROFILEID'] = $params['subscriptionId'];
768 $args['AMT'] = $this->getAmount($params);
769 $args['CURRENCYCODE'] = $config->defaultCurrency
;
770 $args['BILLINGFREQUENCY'] = $params['installments'];
772 $result = $this->invokeAPI($args);
773 CRM_Core_Error
::debug_var('$result', $result);
774 if (is_a($result, 'CRM_Core_Error')) {
777 $message = "{$result['ack']}: profileid={$result['profileid']}";
784 * Function to action pre-approval if supported
786 * @param array $params
787 * Parameters from the form
790 * - pre_approval_parameters (this will be stored on the calling form & available later)
791 * - redirect_url (if set the browser will be redirected to this.
793 public function doPreApproval(&$params) {
794 if (!$this->isPaypalExpress($params)) {
797 $this->_component
= $params['component'];
798 $token = $this->setExpressCheckOut($params);
800 'pre_approval_parameters' => array('token' => $token),
801 'redirect_url' => $this->_paymentProcessor
['url_site'] . "/cgi-bin/webscr?cmd=_express-checkout&token=$token",
806 * @param array $params
807 * @param string $component
811 public function doTransferCheckout(&$params, $component = 'contribute') {
813 $notifyParameters = array('module' => $component);
814 $notifyParameterMap = array(
815 'contactID' => 'contactID',
816 'contributionID' => 'contributionID',
817 'eventID' => 'eventID',
818 'participantID' => 'participantID',
819 'membershipID' => 'membershipID',
820 'related_contact' => 'relatedContactID',
821 'onbehalf_dupe_alert' => 'onBehalfDupeAlert',
822 'accountingCode' => 'accountingCode',
823 'contributionRecurID' => 'contributionRecurID',
824 'contributionPageID' => 'contributionPageID',
826 foreach ($notifyParameterMap as $paramsName => $notifyName) {
827 if (!empty($params[$paramsName])) {
828 $notifyParameters[$notifyName] = $params[$paramsName];
831 $notifyURL = $this->getNotifyUrl();
833 $config = CRM_Core_Config
::singleton();
834 $url = ($component == 'event') ?
'civicrm/event/register' : 'civicrm/contribute/transact';
835 $cancel = ($component == 'event') ?
'_qf_Register_display' : '_qf_Main_display';
837 $cancelUrlString = "$cancel=1&cancel=1&qfKey={$params['qfKey']}";
838 if (!empty($params['is_recur'])) {
839 $cancelUrlString .= "&isRecur=1&recurId={$params['contributionRecurID']}&contribId={$params['contributionID']}";
842 $cancelURL = CRM_Utils_System
::url(
848 $paypalParams = array(
849 'business' => $this->_paymentProcessor
['user_name'],
850 'notify_url' => $notifyURL,
851 'item_name' => $this->getPaymentDescription($params, 127),
853 'undefined_quantity' => 0,
854 'cancel_return' => $cancelURL,
857 'return' => $this->getReturnSuccessUrl($params['qfKey']),
859 'currency_code' => $params['currencyID'],
860 'invoice' => $params['invoiceID'],
861 'lc' => substr($config->lcMessages
, -2),
862 'charset' => function_exists('mb_internal_encoding') ?
mb_internal_encoding() : 'UTF-8',
863 'custom' => json_encode($notifyParameters),
864 'bn' => 'CiviCRM_SP',
867 // add name and address if available, CRM-3130
869 'first_name' => 'first_name',
870 'last_name' => 'last_name',
871 'street_address' => 'address1',
872 'country' => 'country',
873 'preferred_language' => 'lc',
875 'state_province' => 'state',
876 'postal_code' => 'zip',
880 foreach (array_keys($params) as $p) {
881 // get the base name without the location type suffixed to it
882 $parts = explode('-', $p);
883 $name = count($parts) > 1 ?
$parts[0] : $p;
884 if (isset($otherVars[$name])) {
885 $value = $params[$p];
887 if ($name == 'state_province') {
888 $stateName = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($value);
891 if ($name == 'country') {
892 $countryName = CRM_Core_PseudoConstant
::countryIsoCode($value);
893 $value = $countryName;
895 // ensure value is not an array
897 if (!is_array($value)) {
898 $paypalParams[$otherVars[$name]] = $value;
904 // if recurring donations, add a few more items
905 if (!empty($params['is_recur'])) {
906 if (!$params['contributionRecurID']) {
907 CRM_Core_Error
::fatal(ts('Recurring contribution, but no database id'));
910 $paypalParams +
= array(
911 'cmd' => '_xclick-subscriptions',
912 'a3' => $this->getAmount($params),
913 'p3' => $params['frequency_interval'],
914 't3' => ucfirst(substr($params['frequency_unit'], 0, 1)),
917 'srt' => CRM_Utils_Array
::value('installments', $params),
923 $paypalParams +
= array(
925 'amount' => $params['amount'],
929 // Allow further manipulation of the arguments via custom hooks ..
930 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $paypalParams);
933 foreach ($paypalParams as $key => $value) {
934 if ($value === NULL) {
938 $value = urlencode($value);
939 if ($key == 'return' ||
940 $key == 'cancel_return' ||
943 $value = str_replace('%2F', '/', $value);
945 $uri .= "&{$key}={$value}";
948 $uri = substr($uri, 1);
949 $url = $this->_paymentProcessor
['url_site'];
950 $sub = empty($params['is_recur']) ?
'cgi-bin/webscr' : 'subscriptions';
951 $paypalURL = "{$url}{$sub}?$uri";
953 CRM_Utils_System
::redirect($paypalURL);
957 * Hash_call: Function to perform the API call to PayPal using API signature.
959 * @methodName is name of API method.
960 * @nvpStr is nvp string.
961 * returns an associative array containing the response from the server.
966 * @return array|object
969 public function invokeAPI($args, $url = NULL) {
972 if (empty($this->_paymentProcessor
['url_api'])) {
973 CRM_Core_Error
::fatal(ts('Please set the API URL. Please refer to the documentation for more details'));
976 $url = $this->_paymentProcessor
['url_api'] . 'nvp';
979 if (!function_exists('curl_init')) {
980 CRM_Core_Error
::fatal("curl functions NOT available.");
983 //setting the curl parameters.
985 curl_setopt($ch, CURLOPT_URL
, $url);
986 curl_setopt($ch, CURLOPT_VERBOSE
, 0);
988 //turning off the server and peer verification(TrustManager Concept).
989 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, Civi
::settings()->get('verifySSL'));
990 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST
, Civi
::settings()->get('verifySSL') ?
2 : 0);
992 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, 1);
993 curl_setopt($ch, CURLOPT_POST
, 1);
996 foreach ($args as $n => $v) {
997 $p[] = "$n=" . urlencode($v);
1000 //NVPRequest for submitting to server
1001 $nvpreq = implode('&', $p);
1003 //setting the nvpreq as POST FIELD to curl
1004 curl_setopt($ch, CURLOPT_POSTFIELDS
, $nvpreq);
1006 //getting response from server
1007 $response = curl_exec($ch);
1009 //converting NVPResponse to an Associative Array
1010 $result = self
::deformat($response);
1012 if (curl_errno($ch)) {
1013 $e = CRM_Core_Error
::singleton();
1014 $e->push(curl_errno($ch),
1024 if (strtolower($result['ack']) != 'success' &&
1025 strtolower($result['ack']) != 'successwithwarning'
1027 throw new PaymentProcessorException("{$result['l_shortmessage0']} {$result['l_longmessage0']}");
1028 $e = CRM_Core_Error
::singleton();
1029 $e->push($result['l_errorcode0'],
1031 "{$result['l_shortmessage0']} {$result['l_longmessage0']}"
1040 * This function will take NVPString and convert it to an Associative Array.
1042 * It will decode the response. It is useful to search for a particular key and displaying arrays.
1044 * @param string $str
1048 public static function deformat($str) {
1051 while (strlen($str)) {
1053 $keyPos = strpos($str, '=');
1055 // position of value
1056 $valPos = strpos($str, '&') ?
strpos($str, '&') : strlen($str);
1058 /*getting the Key and Value values and storing in a Associative Array*/
1060 $key = substr($str, 0, $keyPos);
1061 $val = substr($str, $keyPos +
1, $valPos - $keyPos - 1);
1063 //decoding the respose
1064 $result[strtolower(urldecode($key))] = urldecode($val);
1065 $str = substr($str, $valPos +
1, strlen($str));
1072 * Get array of fields that should be displayed on the payment form.
1075 * @throws CiviCRM_API3_Exception
1077 public function getPaymentFormFields() {
1078 if ($this->_processorName
== ts('PayPal Pro')) {
1079 return $this->getCreditCardFormFields();
1087 * Map the paypal params to CiviCRM params using a field map.
1089 * @param array $fieldMap
1090 * @param array $paypalParams
1094 protected function mapPaypalParamsToCivicrmParams($fieldMap, $paypalParams) {
1096 foreach ($fieldMap as $civicrmField => $paypalField) {
1097 $params[$civicrmField] = isset($paypalParams[$paypalField]) ?
$paypalParams[$paypalField] : NULL;
1103 * Is this being processed by payment express.
1105 * Either because it is payment express or because is pro with paypal express in use.
1107 * @param array $params
1111 protected function isPaypalExpress($params) {
1112 if ($this->_processorName
== ts('PayPal Express')) {
1116 // This would occur postProcess.
1117 if (!empty($params['token'])) {
1120 if (isset($params['button']) && stristr($params['button'], 'express')) {
1124 // The contribution form passes a 'button' but the event form might still set one of these fields.
1125 // @todo more standardisation & get paypal fully out of the form layer.
1126 $possibleExpressFields = array(
1127 '_qf_Register_upload_express_x',
1128 '_qf_Payment_upload_express_x',
1130 if (array_intersect_key($params, array_fill_keys($possibleExpressFields, 1))) {