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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2015
35 * Class CRM_Core_Payment_PayPalImpl for paypal pro, paypal standard & paypal express.
37 class CRM_Core_Payment_PayPalImpl
extends CRM_Core_Payment
{
38 const CHARSET
= 'iso-8859-1';
40 protected $_mode = NULL;
46 * The mode of operation: live or test.
48 * @param $paymentProcessor
50 * @return \CRM_Core_Payment_PayPalImpl
52 public function __construct($mode, &$paymentProcessor) {
54 $this->_paymentProcessor
= $paymentProcessor;
55 $this->_processorName
= ts('PayPal Pro');
56 $paymentProcessorType = CRM_Core_PseudoConstant
::paymentProcessorType(FALSE, NULL, 'name');
58 if ($this->_paymentProcessor
['payment_processor_type_id'] == CRM_Utils_Array
::key('PayPal_Standard', $paymentProcessorType)) {
59 $this->_processorName
= ts('PayPal Standard');
62 elseif ($this->_paymentProcessor
['payment_processor_type_id'] == CRM_Utils_Array
::key('PayPal_Express', $paymentProcessorType)) {
63 $this->_processorName
= ts('PayPal Express');
69 * Are back office payments supported - e.g paypal standard won't permit you to enter a credit card associated with someone else's login
72 protected function supportsBackOffice() {
73 if ($this->_processorName
== ts('PayPal Pro')) {
80 * Does this processor support pre-approval.
82 * This would generally look like a redirect to enter credentials which can then be used in a later payment call.
84 * Currently Paypal express supports this, with a redirect to paypal after the 'Main' form is submitted in the
85 * contribution page. This token can then be processed at the confirm phase. Although this flow 'looks' like the
86 * 'notify' flow a key difference is that in the notify flow they don't have to return but in this flow they do.
90 protected function supportsPreApproval() {
91 if ($this->_processorName
== ts('PayPal Express')) {
98 * Opportunity for the payment processor to override the entire form build.
100 * @param CRM_Core_Form $form
103 * Should form building stop at this point?
105 public function buildForm(&$form) {
106 if ($this->_processorName
== 'PayPal Express' ||
$this->_processorName
== 'PayPal Pro') {
107 $this->addPaypalExpressCode($form);
108 if ($this->_processorName
== 'PayPal Express') {
109 CRM_Core_Region
::instance('billing-block-post')->add(array(
110 'template' => 'CRM/Financial/Form/PaypalExpress.tpl',
111 'name' => 'paypal_express',
114 if ($this->_processorName
== 'PayPal Pro') {
115 CRM_Core_Region
::instance('billing-block-pre')->add(array(
116 'template' => 'CRM/Financial/Form/PaypalPro.tpl',
124 * Billing mode button is basically synonymous with paypal express - this is probably a good example of 'odds & sods' code we
125 * 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
127 * @param CRM_Core_Form $form
129 protected function addPaypalExpressCode(&$form) {
130 if (empty($form->isBackOffice
)) {
131 $form->_expressButtonName
= $form->getButtonName('upload', 'express');
132 $form->assign('expressButtonName', $form->_expressButtonName
);
135 $form->_expressButtonName
,
136 $this->_paymentProcessor
['url_button'],
137 array('class' => 'crm-form-submit')
143 * Can recurring contributions be set against pledges.
145 * In practice all processors that use the baseIPN function to finish transactions or
146 * call the completetransaction api support this by looking up previous contributions in the
147 * series and, if there is a prior contribution against a pledge, and the pledge is not complete,
148 * adding the new payment to the pledge.
150 * However, only enabling for processors it has been tested against.
154 protected function supportsRecurContributionsForPledges() {
159 * Default payment instrument validation.
161 * Implement the usual Luhn algorithm via a static function in the CRM_Core_Payment_Form if it's a credit card
162 * Not a static function, because I need to check for payment_type.
164 * @param array $values
165 * @param array $errors
167 public function validatePaymentInstrument($values, &$errors) {
168 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal_Pro') {
169 CRM_Core_Payment_Form
::validateCreditCard($values, $errors);
174 * Express checkout code. Check PayPal documentation for more information
176 * @param array $params
177 * Assoc array of input parameters for this transaction.
180 * the result in an nice formatted array (or an error object)
182 protected function setExpressCheckOut(&$params) {
185 $this->initialize($args, 'SetExpressCheckout');
187 $args['paymentAction'] = 'Sale';
188 $args['amt'] = $params['amount'];
189 $args['currencyCode'] = $params['currencyID'];
190 $args['desc'] = CRM_Utils_Array
::value('description', $params);
191 $args['invnum'] = $params['invoiceID'];
192 $args['returnURL'] = $this->getReturnSuccessUrl($params['qfKey']);
193 $args['cancelURL'] = $this->getCancelUrl($params['qfKey'], NULL);
194 $args['version'] = '56.0';
196 //LCD if recurring, collect additional data and set some values
197 if (!empty($params['is_recur'])) {
198 $args['L_BILLINGTYPE0'] = 'RecurringPayments';
199 //$args['L_BILLINGAGREEMENTDESCRIPTION0'] = 'Recurring Contribution';
200 $args['L_BILLINGAGREEMENTDESCRIPTION0'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
201 $args['L_PAYMENTTYPE0'] = 'Any';
204 // Allow further manipulation of the arguments via custom hooks ..
205 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $args);
207 $result = $this->invokeAPI($args);
209 if (is_a($result, 'CRM_Core_Error')) {
215 return $result['token'];
219 * Get any details that may be available to the payment processor due to an approval process having happened.
221 * In some cases the browser is redirected to enter details on a processor site. Some details may be available as a
224 * @param array $storedDetails
228 public function getPreApprovalDetails($storedDetails) {
229 return $this->getExpressCheckoutDetails($storedDetails['token']);
233 * Get details from paypal. Check PayPal documentation for more information
235 * @param string $token
236 * The key associated with this transaction.
239 * the result in an nice formatted array (or an error object)
241 public function getExpressCheckoutDetails($token) {
244 $this->initialize($args, 'GetExpressCheckoutDetails');
245 $args['token'] = $token;
247 $args['method'] = 'GetExpressCheckoutDetails';
249 $result = $this->invokeAPI($args);
251 if (is_a($result, 'CRM_Core_Error')) {
258 'payer_status' => 'payerstatus',
259 'payer_id' => 'payerid',
260 'first_name' => 'firstname',
261 'middle_name' => 'middlename',
262 'last_name' => 'lastname',
263 'street_address' => 'shiptostreet',
264 'supplemental_address_1' => 'shiptostreet2',
265 'city' => 'shiptocity',
266 'postal_code' => 'shiptozip',
267 'state_province' => 'shiptostate',
268 'country' => 'shiptocountrycode',
270 return $this->mapPaypalParamsToCivicrmParams($fieldMap, $result);
274 * Do the express checkout at paypal. Check PayPal documentation for more information
276 * @param array $params
278 * @internal param string $token the key associated with this transaction
281 * the result in an nice formatted array (or an error object)
283 public function doExpressCheckout(&$params) {
284 $statuses = CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id');
285 if (!empty($params['is_recur'])) {
286 return $this->createRecurringPayments($params);
290 $this->initialize($args, 'DoExpressCheckoutPayment');
291 $args['token'] = $params['token'];
292 $args['paymentAction'] = 'Sale';
293 $args['amt'] = $params['amount'];
294 $args['currencyCode'] = $params['currencyID'];
295 $args['payerID'] = $params['payer_id'];
296 $args['invnum'] = $params['invoiceID'];
297 $args['returnURL'] = $this->getReturnSuccessUrl($params['qfKey']);
298 $args['cancelURL'] = $this->getCancelUrl($params['qfKey'], NULL);
299 $args['desc'] = $params['description'];
301 // add CiviCRM BN code
302 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
304 $result = $this->invokeAPI($args);
306 if (is_a($result, 'CRM_Core_Error')) {
307 throw new PaymentProcessorException(CRM_Core_Error
::getMessages($result));
312 $params['trxn_id'] = $result['transactionid'];
313 $params['gross_amount'] = $result['amt'];
314 $params['fee_amount'] = $result['feeamt'];
315 $params['net_amount'] = CRM_Utils_Array
::value('settleamt', $result);
316 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
317 $params['net_amount'] = $params['gross_amount'] - $params['fee_amount'];
319 $params['payment_status'] = $result['paymentstatus'];
320 $params['pending_reason'] = $result['pendingreason'];
321 if (!empty($params['is_recur'])) {
322 // See comment block.
323 $result['payment_status_id'] = array_search('Pending', $statuses);
326 $result['payment_status_id'] = array_search('Completed', $statuses);
331 //LCD add new function for handling recurring payments for PayPal Express
333 * @param array $params
337 public function createRecurringPayments(&$params) {
339 // @todo this function is riddled with enotices - perhaps use $this->mapPaypalParamsToCivicrmParams($fieldMap, $result)
340 $this->initialize($args, 'CreateRecurringPaymentsProfile');
342 $start_time = strtotime(date('m/d/Y'));
343 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
345 $args['token'] = $params['token'];
346 $args['paymentAction'] = 'Sale';
347 $args['amt'] = $params['amount'];
348 $args['currencyCode'] = $params['currencyID'];
349 $args['payerID'] = $params['payer_id'];
350 $args['invnum'] = $params['invoiceID'];
351 $args['returnURL'] = $params['returnURL'];
352 $args['cancelURL'] = $params['cancelURL'];
353 $args['profilestartdate'] = $start_date;
354 $args['method'] = 'CreateRecurringPaymentsProfile';
355 $args['billingfrequency'] = $params['frequency_interval'];
356 $args['billingperiod'] = ucwords($params['frequency_unit']);
357 $args['desc'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
358 //$args['desc'] = 'Recurring Contribution';
359 $args['totalbillingcycles'] = $params['installments'];
360 $args['version'] = '56.0';
361 $args['profilereference'] = "i={$params['invoiceID']}" .
363 "&c={$params['contactID']}" .
364 "&r={$params['contributionRecurID']}" .
365 "&b={$params['contributionID']}" .
366 "&p={$params['contributionPageID']}";
368 // add CiviCRM BN code
369 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
371 $result = $this->invokeAPI($args);
373 if (is_a($result, 'CRM_Core_Error')) {
378 $params['trxn_id'] = $result['transactionid'];
379 $params['gross_amount'] = $result['amt'];
380 $params['fee_amount'] = $result['feeamt'];
381 $params['net_amount'] = $result['settleamt'];
382 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
383 $params['net_amount'] = $params['gross_amount'] - $params['fee_amount'];
385 $params['payment_status'] = $result['paymentstatus'];
386 $params['pending_reason'] = $result['pendingreason'];
395 public function initialize(&$args, $method) {
396 $args['user'] = $this->_paymentProcessor
['user_name'];
397 $args['pwd'] = $this->_paymentProcessor
['password'];
398 $args['version'] = 3.0;
399 $args['signature'] = $this->_paymentProcessor
['signature'];
400 $args['subject'] = CRM_Utils_Array
::value('subject', $this->_paymentProcessor
);
401 $args['method'] = $method;
405 * Process payment - this function wraps around both doTransferPayment and doDirectPayment.
407 * The function ensures an exception is thrown & moves some of this logic out of the form layer and makes the forms
410 * Payment processors should set payment_status_id. This function adds some historical defaults ie. the
411 * assumption that if a 'doDirectPayment' processors comes back it completed the transaction & in fact
412 * doTransferCheckout would not traditionally come back.
414 * doDirectPayment does not do an immediate payment for Authorize.net or Paypal so the default is assumed
417 * Once this function is fully rolled out then it will be preferred for processors to throw exceptions than to
418 * return Error objects
420 * @param array $params
422 * @param string $component
427 * @throws \Civi\Payment\Exception\PaymentProcessorException
429 public function doPayment(&$params, $component = 'contribute') {
430 if ($this->_paymentProcessor
['payment_processor_type'] != 'PayPal_Express') {
431 return parent
::doPayment($params, $component);
433 $this->_component
= $component;
434 return $this->doExpressCheckout($params);
438 * This function collects all the information from a web/api form and invokes
439 * the relevant payment processor specific functions to perform the transaction
441 * @param array $params
442 * Assoc array of input parameters for this transaction.
444 * @param string $component
446 * the result in an nice formatted array (or an error object)
448 public function doDirectPayment(&$params, $component = 'contribute') {
451 $this->initialize($args, 'DoDirectPayment');
453 $args['paymentAction'] = 'Sale';
454 $args['amt'] = $params['amount'];
455 $args['currencyCode'] = $params['currencyID'];
456 $args['invnum'] = $params['invoiceID'];
457 $args['ipaddress'] = $params['ip_address'];
458 $args['creditCardType'] = $params['credit_card_type'];
459 $args['acct'] = $params['credit_card_number'];
460 $args['expDate'] = sprintf('%02d', $params['month']) . $params['year'];
461 $args['cvv2'] = $params['cvv2'];
462 $args['firstName'] = $params['first_name'];
463 $args['lastName'] = $params['last_name'];
464 $args['email'] = CRM_Utils_Array
::value('email', $params);
465 $args['street'] = $params['street_address'];
466 $args['city'] = $params['city'];
467 $args['state'] = $params['state_province'];
468 $args['countryCode'] = $params['country'];
469 $args['zip'] = $params['postal_code'];
470 $args['desc'] = substr(CRM_Utils_Array
::value('description', $params), 0, 127);
471 $args['custom'] = CRM_Utils_Array
::value('accountingCode', $params);
473 // add CiviCRM BN code
474 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
476 if (CRM_Utils_Array
::value('is_recur', $params) == 1) {
477 $start_time = strtotime(date('m/d/Y'));
478 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
480 $args['PaymentAction'] = 'Sale';
481 $args['billingperiod'] = ucwords($params['frequency_unit']);
482 $args['billingfrequency'] = $params['frequency_interval'];
483 $args['method'] = "CreateRecurringPaymentsProfile";
484 $args['profilestartdate'] = $start_date;
486 $params['description'] . ": " .
487 $params['amount'] . " Per " .
488 $params['frequency_interval'] . " " .
489 $params['frequency_unit'];
490 $args['amt'] = $params['amount'];
491 $args['totalbillingcycles'] = $params['installments'];
492 $args['version'] = 56.0;
493 $args['PROFILEREFERENCE'] = "" .
494 "i=" . $params['invoiceID'] . "&m=" . $component .
495 "&c=" . $params['contactID'] . "&r=" . $params['contributionRecurID'] .
496 "&b=" . $params['contributionID'] . "&p=" . $params['contributionPageID'];
499 // Allow further manipulation of the arguments via custom hooks ..
500 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $args);
502 $result = $this->invokeAPI($args);
505 if (is_a($result, 'CRM_Core_Error')) {
509 $params['recurr_profile_id'] = NULL;
511 if (CRM_Utils_Array
::value('is_recur', $params) == 1) {
512 $params['recurr_profile_id'] = $result['profileid'];
517 $params['trxn_id'] = CRM_Utils_Array
::value('transactionid', $result);
518 $params['gross_amount'] = CRM_Utils_Array
::value('amt', $result);
519 $params = array_merge($params, $this->doQuery($params));
524 * Query payment processor for details about a transaction.
526 * For paypal see : https://developer.paypal.com/webapps/developer/docs/classic/api/merchant/GetTransactionDetails_API_Operation_NVP/
528 * @param array $params
529 * Array of parameters containing one of:
530 * - trxn_id Id of an individual transaction.
531 * - processor_id Id of a recurring contribution series as stored in the civicrm_contribution_recur table.
534 * Extra parameters retrieved.
535 * Any parameters retrievable through this should be documented in the function comments at
536 * CRM_Core_Payment::doQuery. Currently
537 * - fee_amount Amount of fee paid
539 * @throws \Civi\Payment\Exception\PaymentProcessorException
541 public function doQuery($params) {
542 if (empty($params['trxn_id'])) {
543 throw new \Civi\Payment\Exception\
PaymentProcessorException('transaction id not set');
546 'TRANSACTIONID' => $params['trxn_id'],
548 $this->initialize($args, 'GetTransactionDetails');
549 $result = $this->invokeAPI($args);
551 'fee_amount' => $result['feeamt'],
556 * This function checks to see if we have the right config values.
559 * the error message if any
561 public function checkConfig() {
563 $paymentProcessorType = CRM_Core_PseudoConstant
::paymentProcessorType(FALSE, NULL, 'name');
565 if ($this->_paymentProcessor
['payment_processor_type_id'] != CRM_Utils_Array
::key('PayPal_Standard', $paymentProcessorType)) {
566 if (empty($this->_paymentProcessor
['signature'])) {
567 $error[] = ts('Signature is not set in the Administer » System Settings » Payment Processors.');
570 if (empty($this->_paymentProcessor
['password'])) {
571 $error[] = ts('Password is not set in the Administer » System Settings » Payment Processors.');
574 if (!$this->_paymentProcessor
['user_name']) {
575 $error[] = ts('User Name is not set in the Administer » System Settings » Payment Processors.');
578 if (!empty($error)) {
579 return implode('<p>', $error);
587 * @return null|string
589 public function cancelSubscriptionURL() {
590 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal_Standard') {
591 return "{$this->_paymentProcessor['url_site']}cgi-bin/webscr?cmd=_subscr-find&alias=" . urlencode($this->_paymentProcessor
['user_name']);
599 * Check whether a method is present ( & supported ) by the payment processor object.
601 * @param string $method
602 * Method to check for.
606 public function isSupported($method = 'cancelSubscription') {
607 if ($this->_paymentProcessor
['payment_processor_type'] != 'PayPal') {
608 // since subscription methods like cancelSubscription or updateBilling is not yet implemented / supported
609 // by standard or express.
612 return parent
::isSupported($method);
616 * Paypal express replaces the submit button with it's own.
619 * Should the form button by suppressed?
621 public function isSuppressSubmitButtons() {
622 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal_Express') {
629 * @param string $message
630 * @param array $params
632 * @return array|bool|object
634 public function cancelSubscription(&$message = '', $params = array()) {
635 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal') {
637 $this->initialize($args, 'ManageRecurringPaymentsProfileStatus');
639 $args['PROFILEID'] = CRM_Utils_Array
::value('subscriptionId', $params);
640 $args['ACTION'] = 'Cancel';
641 $args['NOTE'] = CRM_Utils_Array
::value('reason', $params);
643 $result = $this->invokeAPI($args);
644 if (is_a($result, 'CRM_Core_Error')) {
647 $message = "{$result['ack']}: profileid={$result['profileid']}";
654 * Process incoming notification.
656 * This is only supported for paypal pro at the moment & no specific plans to add this path to core
657 * for paypal standard as the goal must be to separate the 2.
659 * We don't need to handle paypal standard using this path as there has never been any historic support
660 * for paypal standard to call civicrm/payment/ipn as a path.
662 static public function handlePaymentNotification() {
663 $paypalIPN = new CRM_Core_Payment_PayPalProIPN($_REQUEST);
668 * @param string $message
669 * @param array $params
671 * @return array|bool|object
673 public function updateSubscriptionBillingInfo(&$message = '', $params = array()) {
674 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal') {
675 $config = CRM_Core_Config
::singleton();
677 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
679 $args['PROFILEID'] = $params['subscriptionId'];
680 $args['AMT'] = $params['amount'];
681 $args['CURRENCYCODE'] = $config->defaultCurrency
;
682 $args['CREDITCARDTYPE'] = $params['credit_card_type'];
683 $args['ACCT'] = $params['credit_card_number'];
684 $args['EXPDATE'] = sprintf('%02d', $params['month']) . $params['year'];
685 $args['CVV2'] = $params['cvv2'];
687 $args['FIRSTNAME'] = $params['first_name'];
688 $args['LASTNAME'] = $params['last_name'];
689 $args['STREET'] = $params['street_address'];
690 $args['CITY'] = $params['city'];
691 $args['STATE'] = $params['state_province'];
692 $args['COUNTRYCODE'] = $params['postal_code'];
693 $args['ZIP'] = $params['country'];
695 $result = $this->invokeAPI($args);
696 if (is_a($result, 'CRM_Core_Error')) {
699 $message = "{$result['ack']}: profileid={$result['profileid']}";
706 * @param string $message
707 * @param array $params
709 * @return array|bool|object
711 public function changeSubscriptionAmount(&$message = '', $params = array()) {
712 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal') {
713 $config = CRM_Core_Config
::singleton();
715 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
717 $args['PROFILEID'] = $params['subscriptionId'];
718 $args['AMT'] = $params['amount'];
719 $args['CURRENCYCODE'] = $config->defaultCurrency
;
720 $args['BILLINGFREQUENCY'] = $params['installments'];
722 $result = $this->invokeAPI($args);
723 CRM_Core_Error
::debug_var('$result', $result);
724 if (is_a($result, 'CRM_Core_Error')) {
727 $message = "{$result['ack']}: profileid={$result['profileid']}";
734 * Function to action pre-approval if supported
736 * @param array $params
737 * Parameters from the form
740 * - pre_approval_parameters (this will be stored on the calling form & available later)
741 * - redirect_url (if set the browser will be redirected to this.
743 public function doPreApproval(&$params) {
744 $this->_component
= $params['component'];
745 $token = $this->setExpressCheckOut($params);
747 'pre_approval_parameters' => array('token' => $token),
748 'redirect_url' => $this->_paymentProcessor
['url_site'] . "/cgi-bin/webscr?cmd=_express-checkout&token=$token",
753 * @param array $params
754 * @param string $component
758 public function doTransferCheckout(&$params, $component = 'contribute') {
759 $config = CRM_Core_Config
::singleton();
761 if ($component != 'contribute' && $component != 'event') {
762 CRM_Core_Error
::fatal(ts('Component is invalid'));
765 $notifyURL = $config->userFrameworkResourceURL
. "extern/ipn.php?reset=1&contactID={$params['contactID']}" . "&contributionID={$params['contributionID']}" . "&module={$component}";
767 if ($component == 'event') {
768 $notifyURL .= "&eventID={$params['eventID']}&participantID={$params['participantID']}";
771 $membershipID = CRM_Utils_Array
::value('membershipID', $params);
773 $notifyURL .= "&membershipID=$membershipID";
775 $relatedContactID = CRM_Utils_Array
::value('related_contact', $params);
776 if ($relatedContactID) {
777 $notifyURL .= "&relatedContactID=$relatedContactID";
779 $onBehalfDupeAlert = CRM_Utils_Array
::value('onbehalf_dupe_alert', $params);
780 if ($onBehalfDupeAlert) {
781 $notifyURL .= "&onBehalfDupeAlert=$onBehalfDupeAlert";
786 $url = ($component == 'event') ?
'civicrm/event/register' : 'civicrm/contribute/transact';
787 $cancel = ($component == 'event') ?
'_qf_Register_display' : '_qf_Main_display';
788 $returnURL = CRM_Utils_System
::url($url,
789 "_qf_ThankYou_display=1&qfKey={$params['qfKey']}",
793 $cancelUrlString = "$cancel=1&cancel=1&qfKey={$params['qfKey']}";
794 if (!empty($params['is_recur'])) {
795 $cancelUrlString .= "&isRecur=1&recurId={$params['contributionRecurID']}&contribId={$params['contributionID']}";
798 $cancelURL = CRM_Utils_System
::url(
804 // ensure that the returnURL is absolute.
805 if (substr($returnURL, 0, 4) != 'http') {
806 $fixUrl = CRM_Utils_System
::url("civicrm/admin/setting/url", '&reset=1');
807 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)));
810 $paypalParams = array(
811 'business' => $this->_paymentProcessor
['user_name'],
812 'notify_url' => $notifyURL,
813 'item_name' => $params['item_name'],
815 'undefined_quantity' => 0,
816 'cancel_return' => $cancelURL,
819 'return' => $returnURL,
821 'currency_code' => $params['currencyID'],
822 'invoice' => $params['invoiceID'],
823 'lc' => substr($config->lcMessages
, -2),
824 'charset' => function_exists('mb_internal_encoding') ?
mb_internal_encoding() : 'UTF-8',
825 'custom' => CRM_Utils_Array
::value('accountingCode', $params),
826 'bn' => 'CiviCRM_SP',
829 // add name and address if available, CRM-3130
831 'first_name' => 'first_name',
832 'last_name' => 'last_name',
833 'street_address' => 'address1',
834 'country' => 'country',
835 'preferred_language' => 'lc',
837 'state_province' => 'state',
838 'postal_code' => 'zip',
842 foreach (array_keys($params) as $p) {
843 // get the base name without the location type suffixed to it
844 $parts = explode('-', $p);
845 $name = count($parts) > 1 ?
$parts[0] : $p;
846 if (isset($otherVars[$name])) {
847 $value = $params[$p];
849 if ($name == 'state_province') {
850 $stateName = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($value);
853 if ($name == 'country') {
854 $countryName = CRM_Core_PseudoConstant
::countryIsoCode($value);
855 $value = $countryName;
857 // ensure value is not an array
859 if (!is_array($value)) {
860 $paypalParams[$otherVars[$name]] = $value;
866 // if recurring donations, add a few more items
867 if (!empty($params['is_recur'])) {
868 if ($params['contributionRecurID']) {
869 $notifyURL .= "&contributionRecurID={$params['contributionRecurID']}&contributionPageID={$params['contributionPageID']}";
870 $paypalParams['notify_url'] = $notifyURL;
873 CRM_Core_Error
::fatal(ts('Recurring contribution, but no database id'));
876 $paypalParams +
= array(
877 'cmd' => '_xclick-subscriptions',
878 'a3' => $params['amount'],
879 'p3' => $params['frequency_interval'],
880 't3' => ucfirst(substr($params['frequency_unit'], 0, 1)),
883 'srt' => CRM_Utils_Array
::value('installments', $params),
889 $paypalParams +
= array(
891 'amount' => $params['amount'],
895 // Allow further manipulation of the arguments via custom hooks ..
896 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $paypalParams);
899 foreach ($paypalParams as $key => $value) {
900 if ($value === NULL) {
904 $value = urlencode($value);
905 if ($key == 'return' ||
906 $key == 'cancel_return' ||
909 $value = str_replace('%2F', '/', $value);
911 $uri .= "&{$key}={$value}";
914 $uri = substr($uri, 1);
915 $url = $this->_paymentProcessor
['url_site'];
916 $sub = empty($params['is_recur']) ?
'cgi-bin/webscr' : 'subscriptions';
917 $paypalURL = "{$url}{$sub}?$uri";
919 CRM_Utils_System
::redirect($paypalURL);
923 * Hash_call: Function to perform the API call to PayPal using API signature
924 * @methodName is name of API method.
925 * @nvpStr is nvp string.
926 * returns an associtive array containing the response from the server.
928 public function invokeAPI($args, $url = NULL) {
931 if (empty($this->_paymentProcessor
['url_api'])) {
932 CRM_Core_Error
::fatal(ts('Please set the API URL. Please refer to the documentation for more details'));
935 $url = $this->_paymentProcessor
['url_api'] . 'nvp';
938 if (!function_exists('curl_init')) {
939 CRM_Core_Error
::fatal("curl functions NOT available.");
942 //setting the curl parameters.
944 curl_setopt($ch, CURLOPT_URL
, $url);
945 curl_setopt($ch, CURLOPT_VERBOSE
, 1);
947 //turning off the server and peer verification(TrustManager Concept).
948 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'verifySSL'));
949 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST
, CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'verifySSL') ?
2 : 0);
951 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, 1);
952 curl_setopt($ch, CURLOPT_POST
, 1);
955 foreach ($args as $n => $v) {
956 $p[] = "$n=" . urlencode($v);
959 //NVPRequest for submitting to server
960 $nvpreq = implode('&', $p);
962 //setting the nvpreq as POST FIELD to curl
963 curl_setopt($ch, CURLOPT_POSTFIELDS
, $nvpreq);
965 //getting response from server
966 $response = curl_exec($ch);
968 //converting NVPResponse to an Associative Array
969 $result = self
::deformat($response);
971 if (curl_errno($ch)) {
972 $e = CRM_Core_Error
::singleton();
973 $e->push(curl_errno($ch),
983 if (strtolower($result['ack']) != 'success' &&
984 strtolower($result['ack']) != 'successwithwarning'
986 $e = CRM_Core_Error
::singleton();
987 $e->push($result['l_errorcode0'],
989 "{$result['l_shortmessage0']} {$result['l_longmessage0']}"
998 * This function will take NVPString and convert it to an Associative Array and it will decode the response.
999 * It is useful to search for a particular key and displaying arrays.
1000 * @nvpstr is NVPString.
1001 * @nvpArray is Associative Array.
1003 public static function deformat($str) {
1006 while (strlen($str)) {
1008 $keyPos = strpos($str, '=');
1010 // position of value
1011 $valPos = strpos($str, '&') ?
strpos($str, '&') : strlen($str);
1013 /*getting the Key and Value values and storing in a Associative Array*/
1015 $key = substr($str, 0, $keyPos);
1016 $val = substr($str, $keyPos +
1, $valPos - $keyPos - 1);
1018 //decoding the respose
1019 $result[strtolower(urldecode($key))] = urldecode($val);
1020 $str = substr($str, $valPos +
1, strlen($str));
1027 * Get array of fields that should be displayed on the payment form.
1030 * @throws CiviCRM_API3_Exception
1032 public function getPaymentFormFields() {
1033 if ($this->_processorName
== ts('PayPal Pro')) {
1034 return $this->getCreditCardFormFields();
1042 * Map the paypal params to CiviCRM params using a field map.
1044 * @param array $fieldMap
1045 * @param array $paypalParams
1049 protected function mapPaypalParamsToCivicrmParams($fieldMap, $paypalParams) {
1051 foreach ($fieldMap as $civicrmField => $paypalField) {
1052 $params[$civicrmField] = isset($paypalParams[$paypalField]) ?
$paypalParams[$paypalField] : NULL;