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->_processorName
== 'PayPal Express' ||
$this->_processorName
== 'PayPal Pro') {
113 $this->addPaypalExpressCode($form);
114 if ($this->_processorName
== '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
== '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 if (empty($form->isBackOffice
)) {
141 $form->_expressButtonName
= $form->getButtonName('upload', 'express');
142 $form->assign('expressButtonName', $form->_expressButtonName
);
145 $form->_expressButtonName
,
146 $this->_paymentProcessor
['url_button'],
147 array('class' => 'crm-form-submit')
153 * Can recurring contributions be set against pledges.
155 * In practice all processors that use the baseIPN function to finish transactions or
156 * call the completetransaction api support this by looking up previous contributions in the
157 * series and, if there is a prior contribution against a pledge, and the pledge is not complete,
158 * adding the new payment to the pledge.
160 * However, only enabling for processors it has been tested against.
164 protected function supportsRecurContributionsForPledges() {
169 * Default payment instrument validation.
171 * Implement the usual Luhn algorithm via a static function in the CRM_Core_Payment_Form if it's a credit card
172 * Not a static function, because I need to check for payment_type.
174 * @param array $values
175 * @param array $errors
177 public function validatePaymentInstrument($values, &$errors) {
178 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal' && !$this->isPaypalExpress($values)) {
179 CRM_Core_Payment_Form
::validateCreditCard($values, $errors, $this->_paymentProcessor
['id']);
180 CRM_Core_Form
::validateMandatoryFields($this->getMandatoryFields(), $values, $errors);
185 * Express checkout code.
187 * Check PayPal documentation for more information
189 * @param array $params
190 * Assoc array of input parameters for this transaction.
193 * the result in an nice formatted array (or an error object)
194 * @throws \Civi\Payment\Exception\PaymentProcessorException
196 protected function setExpressCheckOut(&$params) {
199 $this->initialize($args, 'SetExpressCheckout');
201 $args['paymentAction'] = 'Sale';
202 $args['amt'] = $params['amount'];
203 $args['currencyCode'] = $params['currencyID'];
204 $args['desc'] = CRM_Utils_Array
::value('description', $params);
205 $args['invnum'] = $params['invoiceID'];
206 $args['returnURL'] = $this->getReturnSuccessUrl($params['qfKey']);
207 $args['cancelURL'] = $this->getCancelUrl($params['qfKey'], NULL);
208 $args['version'] = '56.0';
210 //LCD if recurring, collect additional data and set some values
211 if (!empty($params['is_recur'])) {
212 $args['L_BILLINGTYPE0'] = 'RecurringPayments';
213 //$args['L_BILLINGAGREEMENTDESCRIPTION0'] = 'Recurring Contribution';
214 $args['L_BILLINGAGREEMENTDESCRIPTION0'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
215 $args['L_PAYMENTTYPE0'] = 'Any';
218 // Allow further manipulation of the arguments via custom hooks ..
219 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $args);
221 $result = $this->invokeAPI($args);
223 if (is_a($result, 'CRM_Core_Error')) {
224 throw new PaymentProcessorException($result->message
);
229 return $result['token'];
233 * Get any details that may be available to the payment processor due to an approval process having happened.
235 * In some cases the browser is redirected to enter details on a processor site. Some details may be available as a
238 * @param array $storedDetails
242 public function getPreApprovalDetails($storedDetails) {
243 return empty($storedDetails['token']) ?
array() : $this->getExpressCheckoutDetails($storedDetails['token']);
247 * Get details from paypal.
249 * Check PayPal documentation for more information
251 * @param string $token
252 * The key associated with this transaction.
255 * the result in an nice formatted array (or an error object)
257 public function getExpressCheckoutDetails($token) {
260 $this->initialize($args, 'GetExpressCheckoutDetails');
261 $args['token'] = $token;
263 $args['method'] = 'GetExpressCheckoutDetails';
265 $result = $this->invokeAPI($args);
267 if (is_a($result, 'CRM_Core_Error')) {
268 throw new PaymentProcessorException(CRM_Core_Error
::getMessages($result));
274 'payer_status' => 'payerstatus',
275 'payer_id' => 'payerid',
276 'first_name' => 'firstname',
277 'middle_name' => 'middlename',
278 'last_name' => 'lastname',
279 'street_address' => 'shiptostreet',
280 'supplemental_address_1' => 'shiptostreet2',
281 'city' => 'shiptocity',
282 'postal_code' => 'shiptozip',
283 'state_province' => 'shiptostate',
284 'country' => 'shiptocountrycode',
286 return $this->mapPaypalParamsToCivicrmParams($fieldMap, $result);
290 * Do the express checkout at paypal.
292 * Check PayPal documentation for more information
294 * @param array $params
297 * The result in an nice formatted array.
299 * @throws \Civi\Payment\Exception\PaymentProcessorException
301 public function doExpressCheckout(&$params) {
302 $statuses = CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id');
303 if (!empty($params['is_recur'])) {
304 return $this->createRecurringPayments($params);
308 $this->initialize($args, 'DoExpressCheckoutPayment');
309 $args['token'] = $params['token'];
310 $args['paymentAction'] = 'Sale';
311 $args['amt'] = $params['amount'];
312 $args['currencyCode'] = $params['currencyID'];
313 $args['payerID'] = $params['payer_id'];
314 $args['invnum'] = $params['invoiceID'];
315 $args['returnURL'] = $this->getReturnSuccessUrl($params['qfKey']);
316 $args['cancelURL'] = $this->getCancelUrl($params['qfKey'], NULL);
317 $args['desc'] = $params['description'];
319 // add CiviCRM BN code
320 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
322 $result = $this->invokeAPI($args);
324 if (is_a($result, 'CRM_Core_Error')) {
325 throw new PaymentProcessorException(CRM_Core_Error
::getMessages($result));
330 $params['trxn_id'] = $result['transactionid'];
331 $params['gross_amount'] = $result['amt'];
332 $params['fee_amount'] = $result['feeamt'];
333 $params['net_amount'] = CRM_Utils_Array
::value('settleamt', $result);
334 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
335 $params['net_amount'] = number_format(($params['gross_amount'] - $params['fee_amount']), 2);
337 $params['payment_status'] = $result['paymentstatus'];
338 $params['pending_reason'] = $result['pendingreason'];
339 if (!empty($params['is_recur'])) {
340 // See comment block.
341 $params['payment_status_id'] = array_search('Pending', $statuses);
344 $params['payment_status_id'] = array_search('Completed', $statuses);
350 * Create recurring payments.
352 * @param array $params
356 public function createRecurringPayments(&$params) {
358 // @todo this function is riddled with enotices - perhaps use $this->mapPaypalParamsToCivicrmParams($fieldMap, $result)
359 $this->initialize($args, 'CreateRecurringPaymentsProfile');
361 $start_time = strtotime(date('m/d/Y'));
362 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
364 $args['token'] = $params['token'];
365 $args['paymentAction'] = 'Sale';
366 $args['amt'] = $params['amount'];
367 $args['currencyCode'] = $params['currencyID'];
368 $args['payerID'] = $params['payer_id'];
369 $args['invnum'] = $params['invoiceID'];
370 $args['returnURL'] = $params['returnURL'];
371 $args['cancelURL'] = $params['cancelURL'];
372 $args['profilestartdate'] = $start_date;
373 $args['method'] = 'CreateRecurringPaymentsProfile';
374 $args['billingfrequency'] = $params['frequency_interval'];
375 $args['billingperiod'] = ucwords($params['frequency_unit']);
376 $args['desc'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
377 //$args['desc'] = 'Recurring Contribution';
378 $args['totalbillingcycles'] = $params['installments'];
379 $args['version'] = '56.0';
380 $args['profilereference'] = "i={$params['invoiceID']}" .
382 "&c={$params['contactID']}" .
383 "&r={$params['contributionRecurID']}" .
384 "&b={$params['contributionID']}" .
385 "&p={$params['contributionPageID']}";
387 // add CiviCRM BN code
388 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
390 $result = $this->invokeAPI($args);
392 if (is_a($result, 'CRM_Core_Error')) {
397 $params['trxn_id'] = $result['transactionid'];
398 $params['gross_amount'] = $result['amt'];
399 $params['fee_amount'] = $result['feeamt'];
400 $params['net_amount'] = $result['settleamt'];
401 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
402 $params['net_amount'] = number_format(($params['gross_amount'] - $params['fee_amount']), 2);
404 $params['payment_status'] = $result['paymentstatus'];
405 $params['pending_reason'] = $result['pendingreason'];
416 public function initialize(&$args, $method) {
417 $args['user'] = $this->_paymentProcessor
['user_name'];
418 $args['pwd'] = $this->_paymentProcessor
['password'];
419 $args['version'] = 3.0;
420 $args['signature'] = $this->_paymentProcessor
['signature'];
421 $args['subject'] = CRM_Utils_Array
::value('subject', $this->_paymentProcessor
);
422 $args['method'] = $method;
426 * Process payment - this function wraps around both doTransferPayment and doDirectPayment.
428 * The function ensures an exception is thrown & moves some of this logic out of the form layer and makes the forms
431 * Payment processors should set payment_status_id. This function adds some historical defaults ie. the
432 * assumption that if a 'doDirectPayment' processors comes back it completed the transaction & in fact
433 * doTransferCheckout would not traditionally come back.
435 * doDirectPayment does not do an immediate payment for Authorize.net or Paypal so the default is assumed
438 * Once this function is fully rolled out then it will be preferred for processors to throw exceptions than to
439 * return Error objects
441 * @param array $params
443 * @param string $component
448 * @throws \Civi\Payment\Exception\PaymentProcessorException
450 public function doPayment(&$params, $component = 'contribute') {
451 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal_Express'
452 ||
($this->_paymentProcessor
['payment_processor_type'] == 'PayPal' && !empty($params['token']))
454 $this->_component
= $component;
455 return $this->doExpressCheckout($params);
458 return parent
::doPayment($params, $component);
462 * This function collects all the information from a web/api form and invokes
463 * the relevant payment processor specific functions to perform the transaction
465 * @param array $params
466 * Assoc array of input parameters for this transaction.
468 * @param string $component
470 * the result in an nice formatted array (or an error object)
472 public function doDirectPayment(&$params, $component = 'contribute') {
475 $this->initialize($args, 'DoDirectPayment');
477 $args['paymentAction'] = 'Sale';
478 $args['amt'] = $params['amount'];
479 $args['currencyCode'] = $params['currencyID'];
480 $args['invnum'] = $params['invoiceID'];
481 $args['ipaddress'] = $params['ip_address'];
482 $args['creditCardType'] = $params['credit_card_type'];
483 $args['acct'] = $params['credit_card_number'];
484 $args['expDate'] = sprintf('%02d', $params['month']) . $params['year'];
485 $args['cvv2'] = $params['cvv2'];
486 $args['firstName'] = $params['first_name'];
487 $args['lastName'] = $params['last_name'];
488 $args['email'] = CRM_Utils_Array
::value('email', $params);
489 $args['street'] = $params['street_address'];
490 $args['city'] = $params['city'];
491 $args['state'] = $params['state_province'];
492 $args['countryCode'] = $params['country'];
493 $args['zip'] = $params['postal_code'];
494 $args['desc'] = substr(CRM_Utils_Array
::value('description', $params), 0, 127);
495 $args['custom'] = CRM_Utils_Array
::value('accountingCode', $params);
497 // add CiviCRM BN code
498 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
500 if (CRM_Utils_Array
::value('is_recur', $params) == 1) {
501 $start_time = strtotime(date('m/d/Y'));
502 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
504 $args['PaymentAction'] = 'Sale';
505 $args['billingperiod'] = ucwords($params['frequency_unit']);
506 $args['billingfrequency'] = $params['frequency_interval'];
507 $args['method'] = "CreateRecurringPaymentsProfile";
508 $args['profilestartdate'] = $start_date;
510 $params['description'] . ": " .
511 $params['amount'] . " Per " .
512 $params['frequency_interval'] . " " .
513 $params['frequency_unit'];
514 $args['amt'] = $params['amount'];
515 $args['totalbillingcycles'] = CRM_Utils_Array
::value('installments', $params);
516 $args['version'] = 56.0;
517 $args['PROFILEREFERENCE'] = "" .
518 "i=" . $params['invoiceID'] . "&m=" . $component .
519 "&c=" . $params['contactID'] . "&r=" . $params['contributionRecurID'] .
520 "&b=" . $params['contributionID'] . "&p=" . $params['contributionPageID'];
523 // Allow further manipulation of the arguments via custom hooks ..
524 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $args);
526 $result = $this->invokeAPI($args);
529 if (is_a($result, 'CRM_Core_Error')) {
533 $params['recurr_profile_id'] = NULL;
535 if (CRM_Utils_Array
::value('is_recur', $params) == 1) {
536 $params['recurr_profile_id'] = $result['profileid'];
541 $params['trxn_id'] = CRM_Utils_Array
::value('transactionid', $result);
542 $params['gross_amount'] = CRM_Utils_Array
::value('amt', $result);
543 $params = array_merge($params, $this->doQuery($params));
548 * Query payment processor for details about a transaction.
550 * For paypal see : https://developer.paypal.com/webapps/developer/docs/classic/api/merchant/GetTransactionDetails_API_Operation_NVP/
552 * @param array $params
553 * Array of parameters containing one of:
554 * - trxn_id Id of an individual transaction.
555 * - processor_id Id of a recurring contribution series as stored in the civicrm_contribution_recur table.
558 * Extra parameters retrieved.
559 * Any parameters retrievable through this should be documented in the function comments at
560 * CRM_Core_Payment::doQuery. Currently
561 * - fee_amount Amount of fee paid
563 * @throws \Civi\Payment\Exception\PaymentProcessorException
565 public function doQuery($params) {
566 //CRM-18140 - trxn_id not returned for recurring paypal transaction
567 if (!empty($params['is_recur'])) {
570 elseif (empty($params['trxn_id'])) {
571 throw new \Civi\Payment\Exception\
PaymentProcessorException('transaction id not set');
574 'TRANSACTIONID' => $params['trxn_id'],
576 $this->initialize($args, 'GetTransactionDetails');
577 $result = $this->invokeAPI($args);
579 'fee_amount' => $result['feeamt'],
580 'net_amount' => $params['gross_amount'] - $result['feeamt'],
585 * This function checks to see if we have the right config values.
588 * the error message if any
590 public function checkConfig() {
592 $paymentProcessorType = CRM_Core_PseudoConstant
::paymentProcessorType(FALSE, NULL, 'name');
594 if ($this->_paymentProcessor
['payment_processor_type_id'] != CRM_Utils_Array
::key('PayPal_Standard', $paymentProcessorType)) {
595 if (empty($this->_paymentProcessor
['signature'])) {
596 $error[] = ts('Signature is not set in the Administer » System Settings » Payment Processors.');
599 if (empty($this->_paymentProcessor
['password'])) {
600 $error[] = ts('Password is not set in the Administer » System Settings » Payment Processors.');
603 if (empty($this->_paymentProcessor
['user_name'])) {
604 $error[] = ts('User Name is not set in the Administer » System Settings » Payment Processors.');
607 if (!empty($error)) {
608 return implode('<p>', $error);
616 * @return null|string
618 public function cancelSubscriptionURL() {
619 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal_Standard') {
620 return "{$this->_paymentProcessor['url_site']}cgi-bin/webscr?cmd=_subscr-find&alias=" . urlencode($this->_paymentProcessor
['user_name']);
628 * Check whether a method is present ( & supported ) by the payment processor object.
630 * @param string $method
631 * Method to check for.
635 public function isSupported($method) {
636 if ($this->_paymentProcessor
['payment_processor_type'] != 'PayPal') {
637 // since subscription methods like cancelSubscription or updateBilling is not yet implemented / supported
638 // by standard or express.
641 return parent
::isSupported($method);
645 * Paypal express replaces the submit button with it's own.
648 * Should the form button by suppressed?
650 public function isSuppressSubmitButtons() {
651 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal_Express') {
658 * @param string $message
659 * @param array $params
661 * @return array|bool|object
663 public function cancelSubscription(&$message = '', $params = array()) {
664 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal') {
666 $this->initialize($args, 'ManageRecurringPaymentsProfileStatus');
668 $args['PROFILEID'] = CRM_Utils_Array
::value('subscriptionId', $params);
669 $args['ACTION'] = 'Cancel';
670 $args['NOTE'] = CRM_Utils_Array
::value('reason', $params);
672 $result = $this->invokeAPI($args);
673 if (is_a($result, 'CRM_Core_Error')) {
676 $message = "{$result['ack']}: profileid={$result['profileid']}";
683 * Process incoming notification.
685 static public function handlePaymentNotification() {
686 $params = array_merge($_GET, $_REQUEST);
687 $q = explode('/', CRM_Utils_Array
::value('q', $params, ''));
688 $lastParam = array_pop($q);
689 if (is_numeric($lastParam)) {
690 $params['processor_id'] = $lastParam;
692 if (civicrm_api3('PaymentProcessor', 'getvalue', array(
693 'id' => $params['processor_id'],
694 'return' => 'class_name')
695 ) == 'Payment_PayPalImpl') {
696 $paypalIPN = new CRM_Core_Payment_PayPalIPN($params);
699 $paypalIPN = new CRM_Core_Payment_PayPalProIPN($params);
705 * @param string $message
706 * @param array $params
708 * @return array|bool|object
710 public function updateSubscriptionBillingInfo(&$message = '', $params = array()) {
711 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal') {
712 $config = CRM_Core_Config
::singleton();
714 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
716 $args['PROFILEID'] = $params['subscriptionId'];
717 $args['AMT'] = $params['amount'];
718 $args['CURRENCYCODE'] = $config->defaultCurrency
;
719 $args['CREDITCARDTYPE'] = $params['credit_card_type'];
720 $args['ACCT'] = $params['credit_card_number'];
721 $args['EXPDATE'] = sprintf('%02d', $params['month']) . $params['year'];
722 $args['CVV2'] = $params['cvv2'];
724 $args['FIRSTNAME'] = $params['first_name'];
725 $args['LASTNAME'] = $params['last_name'];
726 $args['STREET'] = $params['street_address'];
727 $args['CITY'] = $params['city'];
728 $args['STATE'] = $params['state_province'];
729 $args['COUNTRYCODE'] = $params['postal_code'];
730 $args['ZIP'] = $params['country'];
732 $result = $this->invokeAPI($args);
733 if (is_a($result, 'CRM_Core_Error')) {
736 $message = "{$result['ack']}: profileid={$result['profileid']}";
743 * @param string $message
744 * @param array $params
746 * @return array|bool|object
748 public function changeSubscriptionAmount(&$message = '', $params = array()) {
749 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal') {
750 $config = CRM_Core_Config
::singleton();
752 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
754 $args['PROFILEID'] = $params['subscriptionId'];
755 $args['AMT'] = $params['amount'];
756 $args['CURRENCYCODE'] = $config->defaultCurrency
;
757 $args['BILLINGFREQUENCY'] = $params['installments'];
759 $result = $this->invokeAPI($args);
760 CRM_Core_Error
::debug_var('$result', $result);
761 if (is_a($result, 'CRM_Core_Error')) {
764 $message = "{$result['ack']}: profileid={$result['profileid']}";
771 * Function to action pre-approval if supported
773 * @param array $params
774 * Parameters from the form
777 * - pre_approval_parameters (this will be stored on the calling form & available later)
778 * - redirect_url (if set the browser will be redirected to this.
780 public function doPreApproval(&$params) {
781 if (!$this->isPaypalExpress($params)) {
784 $this->_component
= $params['component'];
785 $token = $this->setExpressCheckOut($params);
787 'pre_approval_parameters' => array('token' => $token),
788 'redirect_url' => $this->_paymentProcessor
['url_site'] . "/cgi-bin/webscr?cmd=_express-checkout&token=$token",
793 * @param array $params
794 * @param string $component
798 public function doTransferCheckout(&$params, $component = 'contribute') {
800 $notifyParameters = array('module' => $component);
801 $notifyParameterMap = array(
802 'contactID' => 'contactID',
803 'contributionID' => 'contributionID',
804 'eventID' => 'eventID',
805 'participantID' => 'participantID',
806 'membershipID' => 'membershipID',
807 'related_contact' => 'relatedContactID',
808 'onbehalf_dupe_alert' => 'onBehalfDupeAlert',
809 'accountingCode' => 'accountingCode',
810 'contributionRecurID' => 'contributionRecurID',
811 'contributionPageID' => 'contributionPageID',
813 foreach ($notifyParameterMap as $paramsName => $notifyName) {
814 if (!empty($params[$paramsName])) {
815 $notifyParameters[$notifyName] = $params[$paramsName];
818 $notifyURL = $this->getNotifyUrl();
820 $config = CRM_Core_Config
::singleton();
821 $url = ($component == 'event') ?
'civicrm/event/register' : 'civicrm/contribute/transact';
822 $cancel = ($component == 'event') ?
'_qf_Register_display' : '_qf_Main_display';
824 $cancelUrlString = "$cancel=1&cancel=1&qfKey={$params['qfKey']}";
825 if (!empty($params['is_recur'])) {
826 $cancelUrlString .= "&isRecur=1&recurId={$params['contributionRecurID']}&contribId={$params['contributionID']}";
829 $cancelURL = CRM_Utils_System
::url(
835 $paypalParams = array(
836 'business' => $this->_paymentProcessor
['user_name'],
837 'notify_url' => $notifyURL,
838 'item_name' => $this->getPaymentDescription($params, 127),
840 'undefined_quantity' => 0,
841 'cancel_return' => $cancelURL,
844 'return' => $this->getReturnSuccessUrl($params['qfKey']),
846 'currency_code' => $params['currencyID'],
847 'invoice' => $params['invoiceID'],
848 'lc' => substr($config->lcMessages
, -2),
849 'charset' => function_exists('mb_internal_encoding') ?
mb_internal_encoding() : 'UTF-8',
850 'custom' => json_encode($notifyParameters),
851 'bn' => 'CiviCRM_SP',
854 // add name and address if available, CRM-3130
856 'first_name' => 'first_name',
857 'last_name' => 'last_name',
858 'street_address' => 'address1',
859 'country' => 'country',
860 'preferred_language' => 'lc',
862 'state_province' => 'state',
863 'postal_code' => 'zip',
867 foreach (array_keys($params) as $p) {
868 // get the base name without the location type suffixed to it
869 $parts = explode('-', $p);
870 $name = count($parts) > 1 ?
$parts[0] : $p;
871 if (isset($otherVars[$name])) {
872 $value = $params[$p];
874 if ($name == 'state_province') {
875 $stateName = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($value);
878 if ($name == 'country') {
879 $countryName = CRM_Core_PseudoConstant
::countryIsoCode($value);
880 $value = $countryName;
882 // ensure value is not an array
884 if (!is_array($value)) {
885 $paypalParams[$otherVars[$name]] = $value;
891 // if recurring donations, add a few more items
892 if (!empty($params['is_recur'])) {
893 if (!$params['contributionRecurID']) {
894 CRM_Core_Error
::fatal(ts('Recurring contribution, but no database id'));
897 $paypalParams +
= array(
898 'cmd' => '_xclick-subscriptions',
899 'a3' => $params['amount'],
900 'p3' => $params['frequency_interval'],
901 't3' => ucfirst(substr($params['frequency_unit'], 0, 1)),
904 'srt' => CRM_Utils_Array
::value('installments', $params),
910 $paypalParams +
= array(
912 'amount' => $params['amount'],
916 // Allow further manipulation of the arguments via custom hooks ..
917 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $paypalParams);
920 foreach ($paypalParams as $key => $value) {
921 if ($value === NULL) {
925 $value = urlencode($value);
926 if ($key == 'return' ||
927 $key == 'cancel_return' ||
930 $value = str_replace('%2F', '/', $value);
932 $uri .= "&{$key}={$value}";
935 $uri = substr($uri, 1);
936 $url = $this->_paymentProcessor
['url_site'];
937 $sub = empty($params['is_recur']) ?
'cgi-bin/webscr' : 'subscriptions';
938 $paypalURL = "{$url}{$sub}?$uri";
940 CRM_Utils_System
::redirect($paypalURL);
944 * Hash_call: Function to perform the API call to PayPal using API signature.
946 * @methodName is name of API method.
947 * @nvpStr is nvp string.
948 * returns an associative array containing the response from the server.
953 * @return array|object
956 public function invokeAPI($args, $url = NULL) {
959 if (empty($this->_paymentProcessor
['url_api'])) {
960 CRM_Core_Error
::fatal(ts('Please set the API URL. Please refer to the documentation for more details'));
963 $url = $this->_paymentProcessor
['url_api'] . 'nvp';
966 if (!function_exists('curl_init')) {
967 CRM_Core_Error
::fatal("curl functions NOT available.");
970 //setting the curl parameters.
972 curl_setopt($ch, CURLOPT_URL
, $url);
973 curl_setopt($ch, CURLOPT_VERBOSE
, 0);
975 //turning off the server and peer verification(TrustManager Concept).
976 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, Civi
::settings()->get('verifySSL'));
977 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST
, Civi
::settings()->get('verifySSL') ?
2 : 0);
979 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, 1);
980 curl_setopt($ch, CURLOPT_POST
, 1);
983 foreach ($args as $n => $v) {
984 $p[] = "$n=" . urlencode($v);
987 //NVPRequest for submitting to server
988 $nvpreq = implode('&', $p);
990 //setting the nvpreq as POST FIELD to curl
991 curl_setopt($ch, CURLOPT_POSTFIELDS
, $nvpreq);
993 //getting response from server
994 $response = curl_exec($ch);
996 //converting NVPResponse to an Associative Array
997 $result = self
::deformat($response);
999 if (curl_errno($ch)) {
1000 $e = CRM_Core_Error
::singleton();
1001 $e->push(curl_errno($ch),
1011 if (strtolower($result['ack']) != 'success' &&
1012 strtolower($result['ack']) != 'successwithwarning'
1014 throw new PaymentProcessorException("{$result['l_shortmessage0']} {$result['l_longmessage0']}");
1015 $e = CRM_Core_Error
::singleton();
1016 $e->push($result['l_errorcode0'],
1018 "{$result['l_shortmessage0']} {$result['l_longmessage0']}"
1027 * This function will take NVPString and convert it to an Associative Array.
1029 * It will decode the response. It is useful to search for a particular key and displaying arrays.
1031 * @param string $str
1035 public static function deformat($str) {
1038 while (strlen($str)) {
1040 $keyPos = strpos($str, '=');
1042 // position of value
1043 $valPos = strpos($str, '&') ?
strpos($str, '&') : strlen($str);
1045 /*getting the Key and Value values and storing in a Associative Array*/
1047 $key = substr($str, 0, $keyPos);
1048 $val = substr($str, $keyPos +
1, $valPos - $keyPos - 1);
1050 //decoding the respose
1051 $result[strtolower(urldecode($key))] = urldecode($val);
1052 $str = substr($str, $valPos +
1, strlen($str));
1059 * Get array of fields that should be displayed on the payment form.
1062 * @throws CiviCRM_API3_Exception
1064 public function getPaymentFormFields() {
1065 if ($this->_processorName
== ts('PayPal Pro')) {
1066 return $this->getCreditCardFormFields();
1074 * Map the paypal params to CiviCRM params using a field map.
1076 * @param array $fieldMap
1077 * @param array $paypalParams
1081 protected function mapPaypalParamsToCivicrmParams($fieldMap, $paypalParams) {
1083 foreach ($fieldMap as $civicrmField => $paypalField) {
1084 $params[$civicrmField] = isset($paypalParams[$paypalField]) ?
$paypalParams[$paypalField] : NULL;
1090 * Is this being processed by payment express.
1092 * Either because it is payment express or because is pro with paypal express in use.
1094 * @param array $params
1098 protected function isPaypalExpress($params) {
1099 if ($this->_processorName
== ts('PayPal Express')) {
1103 // This would occur postProcess.
1104 if (!empty($params['token'])) {
1107 if (isset($params['button']) && stristr($params['button'], 'express')) {
1111 // The contribution form passes a 'button' but the event form might still set one of these fields.
1112 // @todo more standardisation & get paypal fully out of the form layer.
1113 $possibleExpressFields = array(
1114 '_qf_Register_upload_express_x',
1115 '_qf_Payment_upload_express_x',
1117 if (array_intersect_key($params, array_fill_keys($possibleExpressFields, 1))) {