3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
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 $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 - e.g paypal standard won't permit you to enter a credit card associated with someone else's login
74 protected function supportsBackOffice() {
75 if ($this->_processorName
== ts('PayPal Pro')) {
82 * Does this processor support pre-approval.
84 * This would generally look like a redirect to enter credentials which can then be used in a later payment call.
86 * Currently Paypal express supports this, with a redirect to paypal after the 'Main' form is submitted in the
87 * contribution page. This token can then be processed at the confirm phase. Although this flow 'looks' like the
88 * 'notify' flow a key difference is that in the notify flow they don't have to return but in this flow they do.
92 protected function supportsPreApproval() {
93 if ($this->_processorName
== ts('PayPal Express') ||
$this->_processorName
== ts('PayPal Pro')) {
100 * Opportunity for the payment processor to override the entire form build.
102 * @param CRM_Core_Form $form
105 * Should form building stop at this point?
107 public function buildForm(&$form) {
108 if ($this->_processorName
== 'PayPal Express' ||
$this->_processorName
== 'PayPal Pro') {
109 $this->addPaypalExpressCode($form);
110 if ($this->_processorName
== 'PayPal Express') {
111 CRM_Core_Region
::instance('billing-block-post')->add(array(
112 'template' => 'CRM/Financial/Form/PaypalExpress.tpl',
113 'name' => 'paypal_express',
116 if ($this->_processorName
== 'PayPal Pro') {
117 CRM_Core_Region
::instance('billing-block-pre')->add(array(
118 'template' => 'CRM/Financial/Form/PaypalPro.tpl',
126 * Billing mode button is basically synonymous with paypal express - this is probably a good example of 'odds & sods' code we
127 * need to find a way for the payment processor to assign. A tricky aspect is that the payment processor may need to set the order
129 * @param CRM_Core_Form $form
131 protected function addPaypalExpressCode(&$form) {
132 if (empty($form->isBackOffice
)) {
133 $form->_expressButtonName
= $form->getButtonName('upload', 'express');
134 $form->assign('expressButtonName', $form->_expressButtonName
);
137 $form->_expressButtonName
,
138 $this->_paymentProcessor
['url_button'],
139 array('class' => 'crm-form-submit')
145 * Can recurring contributions be set against pledges.
147 * In practice all processors that use the baseIPN function to finish transactions or
148 * call the completetransaction api support this by looking up previous contributions in the
149 * series and, if there is a prior contribution against a pledge, and the pledge is not complete,
150 * adding the new payment to the pledge.
152 * However, only enabling for processors it has been tested against.
156 protected function supportsRecurContributionsForPledges() {
161 * Default payment instrument validation.
163 * Implement the usual Luhn algorithm via a static function in the CRM_Core_Payment_Form if it's a credit card
164 * Not a static function, because I need to check for payment_type.
166 * @param array $values
167 * @param array $errors
169 public function validatePaymentInstrument($values, &$errors) {
170 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal_Pro') {
171 CRM_Core_Payment_Form
::validateCreditCard($values, $errors);
176 * Express checkout code. Check PayPal documentation for more information
178 * @param array $params
179 * Assoc array of input parameters for this transaction.
182 * the result in an nice formatted array (or an error object)
184 protected function setExpressCheckOut(&$params) {
187 $this->initialize($args, 'SetExpressCheckout');
189 $args['paymentAction'] = 'Sale';
190 $args['amt'] = $params['amount'];
191 $args['currencyCode'] = $params['currencyID'];
192 $args['desc'] = CRM_Utils_Array
::value('description', $params);
193 $args['invnum'] = $params['invoiceID'];
194 $args['returnURL'] = $this->getReturnSuccessUrl($params['qfKey']);
195 $args['cancelURL'] = $this->getCancelUrl($params['qfKey'], NULL);
196 $args['version'] = '56.0';
198 //LCD if recurring, collect additional data and set some values
199 if (!empty($params['is_recur'])) {
200 $args['L_BILLINGTYPE0'] = 'RecurringPayments';
201 //$args['L_BILLINGAGREEMENTDESCRIPTION0'] = 'Recurring Contribution';
202 $args['L_BILLINGAGREEMENTDESCRIPTION0'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
203 $args['L_PAYMENTTYPE0'] = 'Any';
206 // Allow further manipulation of the arguments via custom hooks ..
207 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $args);
209 $result = $this->invokeAPI($args);
211 if (is_a($result, 'CRM_Core_Error')) {
217 return $result['token'];
221 * Get any details that may be available to the payment processor due to an approval process having happened.
223 * In some cases the browser is redirected to enter details on a processor site. Some details may be available as a
226 * @param array $storedDetails
230 public function getPreApprovalDetails($storedDetails) {
231 return empty($storedDetails['token']) ?
array() : $this->getExpressCheckoutDetails($storedDetails['token']);
235 * Get details from paypal. Check PayPal documentation for more information
237 * @param string $token
238 * The key associated with this transaction.
241 * the result in an nice formatted array (or an error object)
243 public function getExpressCheckoutDetails($token) {
246 $this->initialize($args, 'GetExpressCheckoutDetails');
247 $args['token'] = $token;
249 $args['method'] = 'GetExpressCheckoutDetails';
251 $result = $this->invokeAPI($args);
253 if (is_a($result, 'CRM_Core_Error')) {
260 'payer_status' => 'payerstatus',
261 'payer_id' => 'payerid',
262 'first_name' => 'firstname',
263 'middle_name' => 'middlename',
264 'last_name' => 'lastname',
265 'street_address' => 'shiptostreet',
266 'supplemental_address_1' => 'shiptostreet2',
267 'city' => 'shiptocity',
268 'postal_code' => 'shiptozip',
269 'state_province' => 'shiptostate',
270 'country' => 'shiptocountrycode',
272 return $this->mapPaypalParamsToCivicrmParams($fieldMap, $result);
276 * Do the express checkout at paypal. Check PayPal documentation for more information
278 * @param array $params
280 * @internal param string $token the key associated with this transaction
283 * the result in an nice formatted array (or an error object)
285 public function doExpressCheckout(&$params) {
286 $statuses = CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id');
287 if (!empty($params['is_recur'])) {
288 return $this->createRecurringPayments($params);
292 $this->initialize($args, 'DoExpressCheckoutPayment');
293 $args['token'] = $params['token'];
294 $args['paymentAction'] = 'Sale';
295 $args['amt'] = $params['amount'];
296 $args['currencyCode'] = $params['currencyID'];
297 $args['payerID'] = $params['payer_id'];
298 $args['invnum'] = $params['invoiceID'];
299 $args['returnURL'] = $this->getReturnSuccessUrl($params['qfKey']);
300 $args['cancelURL'] = $this->getCancelUrl($params['qfKey'], NULL);
301 $args['desc'] = $params['description'];
303 // add CiviCRM BN code
304 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
306 $result = $this->invokeAPI($args);
308 if (is_a($result, 'CRM_Core_Error')) {
309 throw new PaymentProcessorException(CRM_Core_Error
::getMessages($result));
314 $params['trxn_id'] = $result['transactionid'];
315 $params['gross_amount'] = $result['amt'];
316 $params['fee_amount'] = $result['feeamt'];
317 $params['net_amount'] = CRM_Utils_Array
::value('settleamt', $result);
318 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
319 $params['net_amount'] = $params['gross_amount'] - $params['fee_amount'];
321 $params['payment_status'] = $result['paymentstatus'];
322 $params['pending_reason'] = $result['pendingreason'];
323 if (!empty($params['is_recur'])) {
324 // See comment block.
325 $result['payment_status_id'] = array_search('Pending', $statuses);
328 $result['payment_status_id'] = array_search('Completed', $statuses);
333 //LCD add new function for handling recurring payments for PayPal Express
335 * @param array $params
339 public function createRecurringPayments(&$params) {
341 // @todo this function is riddled with enotices - perhaps use $this->mapPaypalParamsToCivicrmParams($fieldMap, $result)
342 $this->initialize($args, 'CreateRecurringPaymentsProfile');
344 $start_time = strtotime(date('m/d/Y'));
345 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
347 $args['token'] = $params['token'];
348 $args['paymentAction'] = 'Sale';
349 $args['amt'] = $params['amount'];
350 $args['currencyCode'] = $params['currencyID'];
351 $args['payerID'] = $params['payer_id'];
352 $args['invnum'] = $params['invoiceID'];
353 $args['returnURL'] = $params['returnURL'];
354 $args['cancelURL'] = $params['cancelURL'];
355 $args['profilestartdate'] = $start_date;
356 $args['method'] = 'CreateRecurringPaymentsProfile';
357 $args['billingfrequency'] = $params['frequency_interval'];
358 $args['billingperiod'] = ucwords($params['frequency_unit']);
359 $args['desc'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
360 //$args['desc'] = 'Recurring Contribution';
361 $args['totalbillingcycles'] = $params['installments'];
362 $args['version'] = '56.0';
363 $args['profilereference'] = "i={$params['invoiceID']}" .
365 "&c={$params['contactID']}" .
366 "&r={$params['contributionRecurID']}" .
367 "&b={$params['contributionID']}" .
368 "&p={$params['contributionPageID']}";
370 // add CiviCRM BN code
371 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
373 $result = $this->invokeAPI($args);
375 if (is_a($result, 'CRM_Core_Error')) {
380 $params['trxn_id'] = $result['transactionid'];
381 $params['gross_amount'] = $result['amt'];
382 $params['fee_amount'] = $result['feeamt'];
383 $params['net_amount'] = $result['settleamt'];
384 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
385 $params['net_amount'] = $params['gross_amount'] - $params['fee_amount'];
387 $params['payment_status'] = $result['paymentstatus'];
388 $params['pending_reason'] = $result['pendingreason'];
397 public function initialize(&$args, $method) {
398 $args['user'] = $this->_paymentProcessor
['user_name'];
399 $args['pwd'] = $this->_paymentProcessor
['password'];
400 $args['version'] = 3.0;
401 $args['signature'] = $this->_paymentProcessor
['signature'];
402 $args['subject'] = CRM_Utils_Array
::value('subject', $this->_paymentProcessor
);
403 $args['method'] = $method;
407 * Process payment - this function wraps around both doTransferPayment and doDirectPayment.
409 * The function ensures an exception is thrown & moves some of this logic out of the form layer and makes the forms
412 * Payment processors should set payment_status_id. This function adds some historical defaults ie. the
413 * assumption that if a 'doDirectPayment' processors comes back it completed the transaction & in fact
414 * doTransferCheckout would not traditionally come back.
416 * doDirectPayment does not do an immediate payment for Authorize.net or Paypal so the default is assumed
419 * Once this function is fully rolled out then it will be preferred for processors to throw exceptions than to
420 * return Error objects
422 * @param array $params
424 * @param string $component
429 * @throws \Civi\Payment\Exception\PaymentProcessorException
431 public function doPayment(&$params, $component = 'contribute') {
432 if ($this->_paymentProcessor
['payment_processor_type'] != 'PayPal_Express'
433 && (!empty($params['credit_card_number']) && empty($params['token']))
435 return parent
::doPayment($params, $component);
437 $this->_component
= $component;
438 return $this->doExpressCheckout($params);
442 * This function collects all the information from a web/api form and invokes
443 * the relevant payment processor specific functions to perform the transaction
445 * @param array $params
446 * Assoc array of input parameters for this transaction.
448 * @param string $component
450 * the result in an nice formatted array (or an error object)
452 public function doDirectPayment(&$params, $component = 'contribute') {
455 $this->initialize($args, 'DoDirectPayment');
457 $args['paymentAction'] = 'Sale';
458 $args['amt'] = $params['amount'];
459 $args['currencyCode'] = $params['currencyID'];
460 $args['invnum'] = $params['invoiceID'];
461 $args['ipaddress'] = $params['ip_address'];
462 $args['creditCardType'] = $params['credit_card_type'];
463 $args['acct'] = $params['credit_card_number'];
464 $args['expDate'] = sprintf('%02d', $params['month']) . $params['year'];
465 $args['cvv2'] = $params['cvv2'];
466 $args['firstName'] = $params['first_name'];
467 $args['lastName'] = $params['last_name'];
468 $args['email'] = CRM_Utils_Array
::value('email', $params);
469 $args['street'] = $params['street_address'];
470 $args['city'] = $params['city'];
471 $args['state'] = $params['state_province'];
472 $args['countryCode'] = $params['country'];
473 $args['zip'] = $params['postal_code'];
474 $args['desc'] = substr(CRM_Utils_Array
::value('description', $params), 0, 127);
475 $args['custom'] = CRM_Utils_Array
::value('accountingCode', $params);
477 // add CiviCRM BN code
478 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
480 if (CRM_Utils_Array
::value('is_recur', $params) == 1) {
481 $start_time = strtotime(date('m/d/Y'));
482 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
484 $args['PaymentAction'] = 'Sale';
485 $args['billingperiod'] = ucwords($params['frequency_unit']);
486 $args['billingfrequency'] = $params['frequency_interval'];
487 $args['method'] = "CreateRecurringPaymentsProfile";
488 $args['profilestartdate'] = $start_date;
490 $params['description'] . ": " .
491 $params['amount'] . " Per " .
492 $params['frequency_interval'] . " " .
493 $params['frequency_unit'];
494 $args['amt'] = $params['amount'];
495 $args['totalbillingcycles'] = $params['installments'];
496 $args['version'] = 56.0;
497 $args['PROFILEREFERENCE'] = "" .
498 "i=" . $params['invoiceID'] . "&m=" . $component .
499 "&c=" . $params['contactID'] . "&r=" . $params['contributionRecurID'] .
500 "&b=" . $params['contributionID'] . "&p=" . $params['contributionPageID'];
503 // Allow further manipulation of the arguments via custom hooks ..
504 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $args);
506 $result = $this->invokeAPI($args);
509 if (is_a($result, 'CRM_Core_Error')) {
513 $params['recurr_profile_id'] = NULL;
515 if (CRM_Utils_Array
::value('is_recur', $params) == 1) {
516 $params['recurr_profile_id'] = $result['profileid'];
521 $params['trxn_id'] = CRM_Utils_Array
::value('transactionid', $result);
522 $params['gross_amount'] = CRM_Utils_Array
::value('amt', $result);
523 $params = array_merge($params, $this->doQuery($params));
528 * Query payment processor for details about a transaction.
530 * For paypal see : https://developer.paypal.com/webapps/developer/docs/classic/api/merchant/GetTransactionDetails_API_Operation_NVP/
532 * @param array $params
533 * Array of parameters containing one of:
534 * - trxn_id Id of an individual transaction.
535 * - processor_id Id of a recurring contribution series as stored in the civicrm_contribution_recur table.
538 * Extra parameters retrieved.
539 * Any parameters retrievable through this should be documented in the function comments at
540 * CRM_Core_Payment::doQuery. Currently
541 * - fee_amount Amount of fee paid
543 * @throws \Civi\Payment\Exception\PaymentProcessorException
545 public function doQuery($params) {
546 if (empty($params['trxn_id'])) {
547 throw new \Civi\Payment\Exception\
PaymentProcessorException('transaction id not set');
550 'TRANSACTIONID' => $params['trxn_id'],
552 $this->initialize($args, 'GetTransactionDetails');
553 $result = $this->invokeAPI($args);
555 'fee_amount' => $result['feeamt'],
560 * This function checks to see if we have the right config values.
563 * the error message if any
565 public function checkConfig() {
567 $paymentProcessorType = CRM_Core_PseudoConstant
::paymentProcessorType(FALSE, NULL, 'name');
569 if ($this->_paymentProcessor
['payment_processor_type_id'] != CRM_Utils_Array
::key('PayPal_Standard', $paymentProcessorType)) {
570 if (empty($this->_paymentProcessor
['signature'])) {
571 $error[] = ts('Signature is not set in the Administer » System Settings » Payment Processors.');
574 if (empty($this->_paymentProcessor
['password'])) {
575 $error[] = ts('Password is not set in the Administer » System Settings » Payment Processors.');
578 if (empty($this->_paymentProcessor
['user_name'])) {
579 $error[] = ts('User Name is not set in the Administer » System Settings » Payment Processors.');
582 if (!empty($error)) {
583 return implode('<p>', $error);
591 * @return null|string
593 public function cancelSubscriptionURL() {
594 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal_Standard') {
595 return "{$this->_paymentProcessor['url_site']}cgi-bin/webscr?cmd=_subscr-find&alias=" . urlencode($this->_paymentProcessor
['user_name']);
603 * Check whether a method is present ( & supported ) by the payment processor object.
605 * @param string $method
606 * Method to check for.
610 public function isSupported($method = 'cancelSubscription') {
611 if ($this->_paymentProcessor
['payment_processor_type'] != 'PayPal') {
612 // since subscription methods like cancelSubscription or updateBilling is not yet implemented / supported
613 // by standard or express.
616 return parent
::isSupported($method);
620 * Paypal express replaces the submit button with it's own.
623 * Should the form button by suppressed?
625 public function isSuppressSubmitButtons() {
626 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal_Express') {
633 * @param string $message
634 * @param array $params
636 * @return array|bool|object
638 public function cancelSubscription(&$message = '', $params = array()) {
639 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal') {
641 $this->initialize($args, 'ManageRecurringPaymentsProfileStatus');
643 $args['PROFILEID'] = CRM_Utils_Array
::value('subscriptionId', $params);
644 $args['ACTION'] = 'Cancel';
645 $args['NOTE'] = CRM_Utils_Array
::value('reason', $params);
647 $result = $this->invokeAPI($args);
648 if (is_a($result, 'CRM_Core_Error')) {
651 $message = "{$result['ack']}: profileid={$result['profileid']}";
658 * Process incoming notification.
660 * This is only supported for paypal pro at the moment & no specific plans to add this path to core
661 * for paypal standard as the goal must be to separate the 2.
663 * We don't need to handle paypal standard using this path as there has never been any historic support
664 * for paypal standard to call civicrm/payment/ipn as a path.
666 static public function handlePaymentNotification() {
667 $paypalIPN = new CRM_Core_Payment_PayPalProIPN($_REQUEST);
672 * @param string $message
673 * @param array $params
675 * @return array|bool|object
677 public function updateSubscriptionBillingInfo(&$message = '', $params = array()) {
678 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal') {
679 $config = CRM_Core_Config
::singleton();
681 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
683 $args['PROFILEID'] = $params['subscriptionId'];
684 $args['AMT'] = $params['amount'];
685 $args['CURRENCYCODE'] = $config->defaultCurrency
;
686 $args['CREDITCARDTYPE'] = $params['credit_card_type'];
687 $args['ACCT'] = $params['credit_card_number'];
688 $args['EXPDATE'] = sprintf('%02d', $params['month']) . $params['year'];
689 $args['CVV2'] = $params['cvv2'];
691 $args['FIRSTNAME'] = $params['first_name'];
692 $args['LASTNAME'] = $params['last_name'];
693 $args['STREET'] = $params['street_address'];
694 $args['CITY'] = $params['city'];
695 $args['STATE'] = $params['state_province'];
696 $args['COUNTRYCODE'] = $params['postal_code'];
697 $args['ZIP'] = $params['country'];
699 $result = $this->invokeAPI($args);
700 if (is_a($result, 'CRM_Core_Error')) {
703 $message = "{$result['ack']}: profileid={$result['profileid']}";
710 * @param string $message
711 * @param array $params
713 * @return array|bool|object
715 public function changeSubscriptionAmount(&$message = '', $params = array()) {
716 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal') {
717 $config = CRM_Core_Config
::singleton();
719 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
721 $args['PROFILEID'] = $params['subscriptionId'];
722 $args['AMT'] = $params['amount'];
723 $args['CURRENCYCODE'] = $config->defaultCurrency
;
724 $args['BILLINGFREQUENCY'] = $params['installments'];
726 $result = $this->invokeAPI($args);
727 CRM_Core_Error
::debug_var('$result', $result);
728 if (is_a($result, 'CRM_Core_Error')) {
731 $message = "{$result['ack']}: profileid={$result['profileid']}";
738 * Function to action pre-approval if supported
740 * @param array $params
741 * Parameters from the form
744 * - pre_approval_parameters (this will be stored on the calling form & available later)
745 * - redirect_url (if set the browser will be redirected to this.
747 public function doPreApproval(&$params) {
748 if (!isset($params['button']) ||
!stristr($params['button'], 'express')) {
751 $this->_component
= $params['component'];
752 $token = $this->setExpressCheckOut($params);
754 'pre_approval_parameters' => array('token' => $token),
755 'redirect_url' => $this->_paymentProcessor
['url_site'] . "/cgi-bin/webscr?cmd=_express-checkout&token=$token",
760 * @param array $params
761 * @param string $component
765 public function doTransferCheckout(&$params, $component = 'contribute') {
766 $config = CRM_Core_Config
::singleton();
768 if ($component != 'contribute' && $component != 'event') {
769 CRM_Core_Error
::fatal(ts('Component is invalid'));
772 $notifyURL = $config->userFrameworkResourceURL
. "extern/ipn.php?reset=1&contactID={$params['contactID']}" . "&contributionID={$params['contributionID']}" . "&module={$component}";
774 if ($component == 'event') {
775 $notifyURL .= "&eventID={$params['eventID']}&participantID={$params['participantID']}";
778 $membershipID = CRM_Utils_Array
::value('membershipID', $params);
780 $notifyURL .= "&membershipID=$membershipID";
782 $relatedContactID = CRM_Utils_Array
::value('related_contact', $params);
783 if ($relatedContactID) {
784 $notifyURL .= "&relatedContactID=$relatedContactID";
786 $onBehalfDupeAlert = CRM_Utils_Array
::value('onbehalf_dupe_alert', $params);
787 if ($onBehalfDupeAlert) {
788 $notifyURL .= "&onBehalfDupeAlert=$onBehalfDupeAlert";
793 $url = ($component == 'event') ?
'civicrm/event/register' : 'civicrm/contribute/transact';
794 $cancel = ($component == 'event') ?
'_qf_Register_display' : '_qf_Main_display';
795 $returnURL = CRM_Utils_System
::url($url,
796 "_qf_ThankYou_display=1&qfKey={$params['qfKey']}",
800 $cancelUrlString = "$cancel=1&cancel=1&qfKey={$params['qfKey']}";
801 if (!empty($params['is_recur'])) {
802 $cancelUrlString .= "&isRecur=1&recurId={$params['contributionRecurID']}&contribId={$params['contributionID']}";
805 $cancelURL = CRM_Utils_System
::url(
811 // ensure that the returnURL is absolute.
812 if (substr($returnURL, 0, 4) != 'http') {
813 $fixUrl = CRM_Utils_System
::url("civicrm/admin/setting/url", '&reset=1');
814 CRM_Core_Error
::fatal(ts('Sending a relative URL to PayPalIPN is erroneous. Please make your resource URL (in <a href="%1">Administer » System Settings » Resource URLs</a> ) complete.', array(1 => $fixUrl)));
817 $paypalParams = array(
818 'business' => $this->_paymentProcessor
['user_name'],
819 'notify_url' => $notifyURL,
820 'item_name' => $params['item_name'],
822 'undefined_quantity' => 0,
823 'cancel_return' => $cancelURL,
826 'return' => $returnURL,
828 'currency_code' => $params['currencyID'],
829 'invoice' => $params['invoiceID'],
830 'lc' => substr($config->lcMessages
, -2),
831 'charset' => function_exists('mb_internal_encoding') ?
mb_internal_encoding() : 'UTF-8',
832 'custom' => CRM_Utils_Array
::value('accountingCode', $params),
833 'bn' => 'CiviCRM_SP',
836 // add name and address if available, CRM-3130
838 'first_name' => 'first_name',
839 'last_name' => 'last_name',
840 'street_address' => 'address1',
841 'country' => 'country',
842 'preferred_language' => 'lc',
844 'state_province' => 'state',
845 'postal_code' => 'zip',
849 foreach (array_keys($params) as $p) {
850 // get the base name without the location type suffixed to it
851 $parts = explode('-', $p);
852 $name = count($parts) > 1 ?
$parts[0] : $p;
853 if (isset($otherVars[$name])) {
854 $value = $params[$p];
856 if ($name == 'state_province') {
857 $stateName = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($value);
860 if ($name == 'country') {
861 $countryName = CRM_Core_PseudoConstant
::countryIsoCode($value);
862 $value = $countryName;
864 // ensure value is not an array
866 if (!is_array($value)) {
867 $paypalParams[$otherVars[$name]] = $value;
873 // if recurring donations, add a few more items
874 if (!empty($params['is_recur'])) {
875 if ($params['contributionRecurID']) {
876 $notifyURL .= "&contributionRecurID={$params['contributionRecurID']}&contributionPageID={$params['contributionPageID']}";
877 $paypalParams['notify_url'] = $notifyURL;
880 CRM_Core_Error
::fatal(ts('Recurring contribution, but no database id'));
883 $paypalParams +
= array(
884 'cmd' => '_xclick-subscriptions',
885 'a3' => $params['amount'],
886 'p3' => $params['frequency_interval'],
887 't3' => ucfirst(substr($params['frequency_unit'], 0, 1)),
890 'srt' => CRM_Utils_Array
::value('installments', $params),
896 $paypalParams +
= array(
898 'amount' => $params['amount'],
902 // Allow further manipulation of the arguments via custom hooks ..
903 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $paypalParams);
906 foreach ($paypalParams as $key => $value) {
907 if ($value === NULL) {
911 $value = urlencode($value);
912 if ($key == 'return' ||
913 $key == 'cancel_return' ||
916 $value = str_replace('%2F', '/', $value);
918 $uri .= "&{$key}={$value}";
921 $uri = substr($uri, 1);
922 $url = $this->_paymentProcessor
['url_site'];
923 $sub = empty($params['is_recur']) ?
'cgi-bin/webscr' : 'subscriptions';
924 $paypalURL = "{$url}{$sub}?$uri";
926 CRM_Utils_System
::redirect($paypalURL);
930 * Hash_call: Function to perform the API call to PayPal using API signature
931 * @methodName is name of API method.
932 * @nvpStr is nvp string.
933 * returns an associtive array containing the response from the server.
935 public function invokeAPI($args, $url = NULL) {
938 if (empty($this->_paymentProcessor
['url_api'])) {
939 CRM_Core_Error
::fatal(ts('Please set the API URL. Please refer to the documentation for more details'));
942 $url = $this->_paymentProcessor
['url_api'] . 'nvp';
945 if (!function_exists('curl_init')) {
946 CRM_Core_Error
::fatal("curl functions NOT available.");
949 //setting the curl parameters.
951 curl_setopt($ch, CURLOPT_URL
, $url);
952 curl_setopt($ch, CURLOPT_VERBOSE
, 1);
954 //turning off the server and peer verification(TrustManager Concept).
955 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'verifySSL'));
956 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST
, CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'verifySSL') ?
2 : 0);
958 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, 1);
959 curl_setopt($ch, CURLOPT_POST
, 1);
962 foreach ($args as $n => $v) {
963 $p[] = "$n=" . urlencode($v);
966 //NVPRequest for submitting to server
967 $nvpreq = implode('&', $p);
969 //setting the nvpreq as POST FIELD to curl
970 curl_setopt($ch, CURLOPT_POSTFIELDS
, $nvpreq);
972 //getting response from server
973 $response = curl_exec($ch);
975 //converting NVPResponse to an Associative Array
976 $result = self
::deformat($response);
978 if (curl_errno($ch)) {
979 $e = CRM_Core_Error
::singleton();
980 $e->push(curl_errno($ch),
990 if (strtolower($result['ack']) != 'success' &&
991 strtolower($result['ack']) != 'successwithwarning'
993 $e = CRM_Core_Error
::singleton();
994 $e->push($result['l_errorcode0'],
996 "{$result['l_shortmessage0']} {$result['l_longmessage0']}"
1005 * This function will take NVPString and convert it to an Associative Array and it will decode the response.
1006 * It is useful to search for a particular key and displaying arrays.
1007 * @nvpstr is NVPString.
1008 * @nvpArray is Associative Array.
1010 public static function deformat($str) {
1013 while (strlen($str)) {
1015 $keyPos = strpos($str, '=');
1017 // position of value
1018 $valPos = strpos($str, '&') ?
strpos($str, '&') : strlen($str);
1020 /*getting the Key and Value values and storing in a Associative Array*/
1022 $key = substr($str, 0, $keyPos);
1023 $val = substr($str, $keyPos +
1, $valPos - $keyPos - 1);
1025 //decoding the respose
1026 $result[strtolower(urldecode($key))] = urldecode($val);
1027 $str = substr($str, $valPos +
1, strlen($str));
1034 * Get array of fields that should be displayed on the payment form.
1037 * @throws CiviCRM_API3_Exception
1039 public function getPaymentFormFields() {
1040 if ($this->_processorName
== ts('PayPal Pro')) {
1041 return $this->getCreditCardFormFields();
1049 * Map the paypal params to CiviCRM params using a field map.
1051 * @param array $fieldMap
1052 * @param array $paypalParams
1056 protected function mapPaypalParamsToCivicrmParams($fieldMap, $paypalParams) {
1058 foreach ($fieldMap as $civicrmField => $paypalField) {
1059 $params[$civicrmField] = isset($paypalParams[$paypalField]) ?
$paypalParams[$paypalField] : NULL;