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 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);
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)
195 protected function setExpressCheckOut(&$params) {
198 $this->initialize($args, 'SetExpressCheckout');
200 $args['paymentAction'] = 'Sale';
201 $args['amt'] = $params['amount'];
202 $args['currencyCode'] = $params['currencyID'];
203 $args['desc'] = CRM_Utils_Array
::value('description', $params);
204 $args['invnum'] = $params['invoiceID'];
205 $args['returnURL'] = $this->getReturnSuccessUrl($params['qfKey']);
206 $args['cancelURL'] = $this->getCancelUrl($params['qfKey'], NULL);
207 $args['version'] = '56.0';
209 //LCD if recurring, collect additional data and set some values
210 if (!empty($params['is_recur'])) {
211 $args['L_BILLINGTYPE0'] = 'RecurringPayments';
212 //$args['L_BILLINGAGREEMENTDESCRIPTION0'] = 'Recurring Contribution';
213 $args['L_BILLINGAGREEMENTDESCRIPTION0'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
214 $args['L_PAYMENTTYPE0'] = 'Any';
217 // Allow further manipulation of the arguments via custom hooks ..
218 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $args);
220 $result = $this->invokeAPI($args);
222 if (is_a($result, 'CRM_Core_Error')) {
228 return $result['token'];
232 * Get any details that may be available to the payment processor due to an approval process having happened.
234 * In some cases the browser is redirected to enter details on a processor site. Some details may be available as a
237 * @param array $storedDetails
241 public function getPreApprovalDetails($storedDetails) {
242 return empty($storedDetails['token']) ?
array() : $this->getExpressCheckoutDetails($storedDetails['token']);
246 * Get details from paypal.
248 * Check PayPal documentation for more information
250 * @param string $token
251 * The key associated with this transaction.
254 * the result in an nice formatted array (or an error object)
256 public function getExpressCheckoutDetails($token) {
259 $this->initialize($args, 'GetExpressCheckoutDetails');
260 $args['token'] = $token;
262 $args['method'] = 'GetExpressCheckoutDetails';
264 $result = $this->invokeAPI($args);
266 if (is_a($result, 'CRM_Core_Error')) {
273 'payer_status' => 'payerstatus',
274 'payer_id' => 'payerid',
275 'first_name' => 'firstname',
276 'middle_name' => 'middlename',
277 'last_name' => 'lastname',
278 'street_address' => 'shiptostreet',
279 'supplemental_address_1' => 'shiptostreet2',
280 'city' => 'shiptocity',
281 'postal_code' => 'shiptozip',
282 'state_province' => 'shiptostate',
283 'country' => 'shiptocountrycode',
285 return $this->mapPaypalParamsToCivicrmParams($fieldMap, $result);
289 * Do the express checkout at paypal.
291 * Check PayPal documentation for more information
293 * @param array $params
296 * The result in an nice formatted array.
298 * @throws \Civi\Payment\Exception\PaymentProcessorException
300 public function doExpressCheckout(&$params) {
301 $statuses = CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id');
302 if (!empty($params['is_recur'])) {
303 return $this->createRecurringPayments($params);
307 $this->initialize($args, 'DoExpressCheckoutPayment');
308 $args['token'] = $params['token'];
309 $args['paymentAction'] = 'Sale';
310 $args['amt'] = $params['amount'];
311 $args['currencyCode'] = $params['currencyID'];
312 $args['payerID'] = $params['payer_id'];
313 $args['invnum'] = $params['invoiceID'];
314 $args['returnURL'] = $this->getReturnSuccessUrl($params['qfKey']);
315 $args['cancelURL'] = $this->getCancelUrl($params['qfKey'], NULL);
316 $args['desc'] = $params['description'];
318 // add CiviCRM BN code
319 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
321 $result = $this->invokeAPI($args);
323 if (is_a($result, 'CRM_Core_Error')) {
324 throw new PaymentProcessorException(CRM_Core_Error
::getMessages($result));
329 $params['trxn_id'] = $result['transactionid'];
330 $params['gross_amount'] = $result['amt'];
331 $params['fee_amount'] = $result['feeamt'];
332 $params['net_amount'] = CRM_Utils_Array
::value('settleamt', $result);
333 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
334 $params['net_amount'] = number_format(($params['gross_amount'] - $params['fee_amount']), 2);
336 $params['payment_status'] = $result['paymentstatus'];
337 $params['pending_reason'] = $result['pendingreason'];
338 if (!empty($params['is_recur'])) {
339 // See comment block.
340 $result['payment_status_id'] = array_search('Pending', $statuses);
343 $result['payment_status_id'] = array_search('Completed', $statuses);
349 * Create recurring payments.
351 * @param array $params
355 public function createRecurringPayments(&$params) {
357 // @todo this function is riddled with enotices - perhaps use $this->mapPaypalParamsToCivicrmParams($fieldMap, $result)
358 $this->initialize($args, 'CreateRecurringPaymentsProfile');
360 $start_time = strtotime(date('m/d/Y'));
361 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
363 $args['token'] = $params['token'];
364 $args['paymentAction'] = 'Sale';
365 $args['amt'] = $params['amount'];
366 $args['currencyCode'] = $params['currencyID'];
367 $args['payerID'] = $params['payer_id'];
368 $args['invnum'] = $params['invoiceID'];
369 $args['returnURL'] = $params['returnURL'];
370 $args['cancelURL'] = $params['cancelURL'];
371 $args['profilestartdate'] = $start_date;
372 $args['method'] = 'CreateRecurringPaymentsProfile';
373 $args['billingfrequency'] = $params['frequency_interval'];
374 $args['billingperiod'] = ucwords($params['frequency_unit']);
375 $args['desc'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
376 //$args['desc'] = 'Recurring Contribution';
377 $args['totalbillingcycles'] = $params['installments'];
378 $args['version'] = '56.0';
379 $args['profilereference'] = "i={$params['invoiceID']}" .
381 "&c={$params['contactID']}" .
382 "&r={$params['contributionRecurID']}" .
383 "&b={$params['contributionID']}" .
384 "&p={$params['contributionPageID']}";
386 // add CiviCRM BN code
387 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
389 $result = $this->invokeAPI($args);
391 if (is_a($result, 'CRM_Core_Error')) {
396 $params['trxn_id'] = $result['transactionid'];
397 $params['gross_amount'] = $result['amt'];
398 $params['fee_amount'] = $result['feeamt'];
399 $params['net_amount'] = $result['settleamt'];
400 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
401 $params['net_amount'] = number_format(($params['gross_amount'] - $params['fee_amount']), 2);
403 $params['payment_status'] = $result['paymentstatus'];
404 $params['pending_reason'] = $result['pendingreason'];
415 public function initialize(&$args, $method) {
416 $args['user'] = $this->_paymentProcessor
['user_name'];
417 $args['pwd'] = $this->_paymentProcessor
['password'];
418 $args['version'] = 3.0;
419 $args['signature'] = $this->_paymentProcessor
['signature'];
420 $args['subject'] = CRM_Utils_Array
::value('subject', $this->_paymentProcessor
);
421 $args['method'] = $method;
425 * Process payment - this function wraps around both doTransferPayment and doDirectPayment.
427 * The function ensures an exception is thrown & moves some of this logic out of the form layer and makes the forms
430 * Payment processors should set payment_status_id. This function adds some historical defaults ie. the
431 * assumption that if a 'doDirectPayment' processors comes back it completed the transaction & in fact
432 * doTransferCheckout would not traditionally come back.
434 * doDirectPayment does not do an immediate payment for Authorize.net or Paypal so the default is assumed
437 * Once this function is fully rolled out then it will be preferred for processors to throw exceptions than to
438 * return Error objects
440 * @param array $params
442 * @param string $component
447 * @throws \Civi\Payment\Exception\PaymentProcessorException
449 public function doPayment(&$params, $component = 'contribute') {
450 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal_Express'
451 ||
($this->_paymentProcessor
['payment_processor_type'] == 'PayPal' && !empty($params['token']))
453 $this->_component
= $component;
454 return $this->doExpressCheckout($params);
457 return parent
::doPayment($params, $component);
461 * This function collects all the information from a web/api form and invokes
462 * the relevant payment processor specific functions to perform the transaction
464 * @param array $params
465 * Assoc array of input parameters for this transaction.
467 * @param string $component
469 * the result in an nice formatted array (or an error object)
471 public function doDirectPayment(&$params, $component = 'contribute') {
474 $this->initialize($args, 'DoDirectPayment');
476 $args['paymentAction'] = 'Sale';
477 $args['amt'] = $params['amount'];
478 $args['currencyCode'] = $params['currencyID'];
479 $args['invnum'] = $params['invoiceID'];
480 $args['ipaddress'] = $params['ip_address'];
481 $args['creditCardType'] = $params['credit_card_type'];
482 $args['acct'] = $params['credit_card_number'];
483 $args['expDate'] = sprintf('%02d', $params['month']) . $params['year'];
484 $args['cvv2'] = $params['cvv2'];
485 $args['firstName'] = $params['first_name'];
486 $args['lastName'] = $params['last_name'];
487 $args['email'] = CRM_Utils_Array
::value('email', $params);
488 $args['street'] = $params['street_address'];
489 $args['city'] = $params['city'];
490 $args['state'] = $params['state_province'];
491 $args['countryCode'] = $params['country'];
492 $args['zip'] = $params['postal_code'];
493 $args['desc'] = substr(CRM_Utils_Array
::value('description', $params), 0, 127);
494 $args['custom'] = CRM_Utils_Array
::value('accountingCode', $params);
496 // add CiviCRM BN code
497 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
499 if (CRM_Utils_Array
::value('is_recur', $params) == 1) {
500 $start_time = strtotime(date('m/d/Y'));
501 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
503 $args['PaymentAction'] = 'Sale';
504 $args['billingperiod'] = ucwords($params['frequency_unit']);
505 $args['billingfrequency'] = $params['frequency_interval'];
506 $args['method'] = "CreateRecurringPaymentsProfile";
507 $args['profilestartdate'] = $start_date;
509 $params['description'] . ": " .
510 $params['amount'] . " Per " .
511 $params['frequency_interval'] . " " .
512 $params['frequency_unit'];
513 $args['amt'] = $params['amount'];
514 $args['totalbillingcycles'] = $params['installments'];
515 $args['version'] = 56.0;
516 $args['PROFILEREFERENCE'] = "" .
517 "i=" . $params['invoiceID'] . "&m=" . $component .
518 "&c=" . $params['contactID'] . "&r=" . $params['contributionRecurID'] .
519 "&b=" . $params['contributionID'] . "&p=" . $params['contributionPageID'];
522 // Allow further manipulation of the arguments via custom hooks ..
523 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $args);
525 $result = $this->invokeAPI($args);
528 if (is_a($result, 'CRM_Core_Error')) {
532 $params['recurr_profile_id'] = NULL;
534 if (CRM_Utils_Array
::value('is_recur', $params) == 1) {
535 $params['recurr_profile_id'] = $result['profileid'];
540 $params['trxn_id'] = CRM_Utils_Array
::value('transactionid', $result);
541 $params['gross_amount'] = CRM_Utils_Array
::value('amt', $result);
542 $params = array_merge($params, $this->doQuery($params));
547 * Query payment processor for details about a transaction.
549 * For paypal see : https://developer.paypal.com/webapps/developer/docs/classic/api/merchant/GetTransactionDetails_API_Operation_NVP/
551 * @param array $params
552 * Array of parameters containing one of:
553 * - trxn_id Id of an individual transaction.
554 * - processor_id Id of a recurring contribution series as stored in the civicrm_contribution_recur table.
557 * Extra parameters retrieved.
558 * Any parameters retrievable through this should be documented in the function comments at
559 * CRM_Core_Payment::doQuery. Currently
560 * - fee_amount Amount of fee paid
562 * @throws \Civi\Payment\Exception\PaymentProcessorException
564 public function doQuery($params) {
565 if (empty($params['trxn_id'])) {
566 throw new \Civi\Payment\Exception\
PaymentProcessorException('transaction id not set');
569 'TRANSACTIONID' => $params['trxn_id'],
571 $this->initialize($args, 'GetTransactionDetails');
572 $result = $this->invokeAPI($args);
574 'fee_amount' => $result['feeamt'],
575 'net_amount' => $params['gross_amount'] - $result['feeamt'],
580 * This function checks to see if we have the right config values.
583 * the error message if any
585 public function checkConfig() {
587 $paymentProcessorType = CRM_Core_PseudoConstant
::paymentProcessorType(FALSE, NULL, 'name');
589 if ($this->_paymentProcessor
['payment_processor_type_id'] != CRM_Utils_Array
::key('PayPal_Standard', $paymentProcessorType)) {
590 if (empty($this->_paymentProcessor
['signature'])) {
591 $error[] = ts('Signature is not set in the Administer » System Settings » Payment Processors.');
594 if (empty($this->_paymentProcessor
['password'])) {
595 $error[] = ts('Password is not set in the Administer » System Settings » Payment Processors.');
598 if (empty($this->_paymentProcessor
['user_name'])) {
599 $error[] = ts('User Name is not set in the Administer » System Settings » Payment Processors.');
602 if (!empty($error)) {
603 return implode('<p>', $error);
611 * @return null|string
613 public function cancelSubscriptionURL() {
614 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal_Standard') {
615 return "{$this->_paymentProcessor['url_site']}cgi-bin/webscr?cmd=_subscr-find&alias=" . urlencode($this->_paymentProcessor
['user_name']);
623 * Check whether a method is present ( & supported ) by the payment processor object.
625 * @param string $method
626 * Method to check for.
630 public function isSupported($method = 'cancelSubscription') {
631 if ($this->_paymentProcessor
['payment_processor_type'] != 'PayPal') {
632 // since subscription methods like cancelSubscription or updateBilling is not yet implemented / supported
633 // by standard or express.
636 return parent
::isSupported($method);
640 * Paypal express replaces the submit button with it's own.
643 * Should the form button by suppressed?
645 public function isSuppressSubmitButtons() {
646 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal_Express') {
653 * @param string $message
654 * @param array $params
656 * @return array|bool|object
658 public function cancelSubscription(&$message = '', $params = array()) {
659 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal') {
661 $this->initialize($args, 'ManageRecurringPaymentsProfileStatus');
663 $args['PROFILEID'] = CRM_Utils_Array
::value('subscriptionId', $params);
664 $args['ACTION'] = 'Cancel';
665 $args['NOTE'] = CRM_Utils_Array
::value('reason', $params);
667 $result = $this->invokeAPI($args);
668 if (is_a($result, 'CRM_Core_Error')) {
671 $message = "{$result['ack']}: profileid={$result['profileid']}";
678 * Process incoming notification.
680 * This is only supported for paypal pro at the moment & no specific plans to add this path to core
681 * for paypal standard as the goal must be to separate the 2.
683 * We don't need to handle paypal standard using this path as there has never been any historic support
684 * for paypal standard to call civicrm/payment/ipn as a path.
686 static public function handlePaymentNotification() {
687 $paypalIPN = new CRM_Core_Payment_PayPalProIPN($_REQUEST);
692 * @param string $message
693 * @param array $params
695 * @return array|bool|object
697 public function updateSubscriptionBillingInfo(&$message = '', $params = array()) {
698 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal') {
699 $config = CRM_Core_Config
::singleton();
701 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
703 $args['PROFILEID'] = $params['subscriptionId'];
704 $args['AMT'] = $params['amount'];
705 $args['CURRENCYCODE'] = $config->defaultCurrency
;
706 $args['CREDITCARDTYPE'] = $params['credit_card_type'];
707 $args['ACCT'] = $params['credit_card_number'];
708 $args['EXPDATE'] = sprintf('%02d', $params['month']) . $params['year'];
709 $args['CVV2'] = $params['cvv2'];
711 $args['FIRSTNAME'] = $params['first_name'];
712 $args['LASTNAME'] = $params['last_name'];
713 $args['STREET'] = $params['street_address'];
714 $args['CITY'] = $params['city'];
715 $args['STATE'] = $params['state_province'];
716 $args['COUNTRYCODE'] = $params['postal_code'];
717 $args['ZIP'] = $params['country'];
719 $result = $this->invokeAPI($args);
720 if (is_a($result, 'CRM_Core_Error')) {
723 $message = "{$result['ack']}: profileid={$result['profileid']}";
730 * @param string $message
731 * @param array $params
733 * @return array|bool|object
735 public function changeSubscriptionAmount(&$message = '', $params = array()) {
736 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal') {
737 $config = CRM_Core_Config
::singleton();
739 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
741 $args['PROFILEID'] = $params['subscriptionId'];
742 $args['AMT'] = $params['amount'];
743 $args['CURRENCYCODE'] = $config->defaultCurrency
;
744 $args['BILLINGFREQUENCY'] = $params['installments'];
746 $result = $this->invokeAPI($args);
747 CRM_Core_Error
::debug_var('$result', $result);
748 if (is_a($result, 'CRM_Core_Error')) {
751 $message = "{$result['ack']}: profileid={$result['profileid']}";
758 * Function to action pre-approval if supported
760 * @param array $params
761 * Parameters from the form
764 * - pre_approval_parameters (this will be stored on the calling form & available later)
765 * - redirect_url (if set the browser will be redirected to this.
767 public function doPreApproval(&$params) {
768 if (!$this->isPaypalExpress($params)) {
771 $this->_component
= $params['component'];
772 $token = $this->setExpressCheckOut($params);
774 'pre_approval_parameters' => array('token' => $token),
775 'redirect_url' => $this->_paymentProcessor
['url_site'] . "/cgi-bin/webscr?cmd=_express-checkout&token=$token",
780 * @param array $params
781 * @param string $component
785 public function doTransferCheckout(&$params, $component = 'contribute') {
786 $config = CRM_Core_Config
::singleton();
788 if ($component != 'contribute' && $component != 'event') {
789 CRM_Core_Error
::fatal(ts('Component is invalid'));
792 $notifyURL = $config->userFrameworkResourceURL
. "extern/ipn.php?reset=1&contactID={$params['contactID']}" . "&contributionID={$params['contributionID']}" . "&module={$component}";
794 if ($component == 'event') {
795 $notifyURL .= "&eventID={$params['eventID']}&participantID={$params['participantID']}";
798 $membershipID = CRM_Utils_Array
::value('membershipID', $params);
800 $notifyURL .= "&membershipID=$membershipID";
802 $relatedContactID = CRM_Utils_Array
::value('related_contact', $params);
803 if ($relatedContactID) {
804 $notifyURL .= "&relatedContactID=$relatedContactID";
806 $onBehalfDupeAlert = CRM_Utils_Array
::value('onbehalf_dupe_alert', $params);
807 if ($onBehalfDupeAlert) {
808 $notifyURL .= "&onBehalfDupeAlert=$onBehalfDupeAlert";
813 $url = ($component == 'event') ?
'civicrm/event/register' : 'civicrm/contribute/transact';
814 $cancel = ($component == 'event') ?
'_qf_Register_display' : '_qf_Main_display';
815 $returnURL = CRM_Utils_System
::url($url,
816 "_qf_ThankYou_display=1&qfKey={$params['qfKey']}",
820 $cancelUrlString = "$cancel=1&cancel=1&qfKey={$params['qfKey']}";
821 if (!empty($params['is_recur'])) {
822 $cancelUrlString .= "&isRecur=1&recurId={$params['contributionRecurID']}&contribId={$params['contributionID']}";
825 $cancelURL = CRM_Utils_System
::url(
831 // ensure that the returnURL is absolute.
832 if (substr($returnURL, 0, 4) != 'http') {
833 $fixUrl = CRM_Utils_System
::url("civicrm/admin/setting/url", '&reset=1');
834 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)));
837 $paypalParams = array(
838 'business' => $this->_paymentProcessor
['user_name'],
839 'notify_url' => $notifyURL,
840 'item_name' => $this->getPaymentDescription(),
842 'undefined_quantity' => 0,
843 'cancel_return' => $cancelURL,
846 'return' => $returnURL,
848 'currency_code' => $params['currencyID'],
849 'invoice' => $params['invoiceID'],
850 'lc' => substr($config->lcMessages
, -2),
851 'charset' => function_exists('mb_internal_encoding') ?
mb_internal_encoding() : 'UTF-8',
852 'custom' => CRM_Utils_Array
::value('accountingCode', $params),
853 'bn' => 'CiviCRM_SP',
856 // add name and address if available, CRM-3130
858 'first_name' => 'first_name',
859 'last_name' => 'last_name',
860 'street_address' => 'address1',
861 'country' => 'country',
862 'preferred_language' => 'lc',
864 'state_province' => 'state',
865 'postal_code' => 'zip',
869 foreach (array_keys($params) as $p) {
870 // get the base name without the location type suffixed to it
871 $parts = explode('-', $p);
872 $name = count($parts) > 1 ?
$parts[0] : $p;
873 if (isset($otherVars[$name])) {
874 $value = $params[$p];
876 if ($name == 'state_province') {
877 $stateName = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($value);
880 if ($name == 'country') {
881 $countryName = CRM_Core_PseudoConstant
::countryIsoCode($value);
882 $value = $countryName;
884 // ensure value is not an array
886 if (!is_array($value)) {
887 $paypalParams[$otherVars[$name]] = $value;
893 // if recurring donations, add a few more items
894 if (!empty($params['is_recur'])) {
895 if ($params['contributionRecurID']) {
896 $notifyURL .= "&contributionRecurID={$params['contributionRecurID']}&contributionPageID={$params['contributionPageID']}";
897 $paypalParams['notify_url'] = $notifyURL;
900 CRM_Core_Error
::fatal(ts('Recurring contribution, but no database id'));
903 $paypalParams +
= array(
904 'cmd' => '_xclick-subscriptions',
905 'a3' => $params['amount'],
906 'p3' => $params['frequency_interval'],
907 't3' => ucfirst(substr($params['frequency_unit'], 0, 1)),
910 'srt' => CRM_Utils_Array
::value('installments', $params),
916 $paypalParams +
= array(
918 'amount' => $params['amount'],
922 // Allow further manipulation of the arguments via custom hooks ..
923 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $paypalParams);
926 foreach ($paypalParams as $key => $value) {
927 if ($value === NULL) {
931 $value = urlencode($value);
932 if ($key == 'return' ||
933 $key == 'cancel_return' ||
936 $value = str_replace('%2F', '/', $value);
938 $uri .= "&{$key}={$value}";
941 $uri = substr($uri, 1);
942 $url = $this->_paymentProcessor
['url_site'];
943 $sub = empty($params['is_recur']) ?
'cgi-bin/webscr' : 'subscriptions';
944 $paypalURL = "{$url}{$sub}?$uri";
946 CRM_Utils_System
::redirect($paypalURL);
950 * Hash_call: Function to perform the API call to PayPal using API signature
951 * @methodName is name of API method.
952 * @nvpStr is nvp string.
953 * returns an associtive array containing the response from the server.
955 public function invokeAPI($args, $url = NULL) {
958 if (empty($this->_paymentProcessor
['url_api'])) {
959 CRM_Core_Error
::fatal(ts('Please set the API URL. Please refer to the documentation for more details'));
962 $url = $this->_paymentProcessor
['url_api'] . 'nvp';
965 if (!function_exists('curl_init')) {
966 CRM_Core_Error
::fatal("curl functions NOT available.");
969 //setting the curl parameters.
971 curl_setopt($ch, CURLOPT_URL
, $url);
972 curl_setopt($ch, CURLOPT_VERBOSE
, 1);
974 //turning off the server and peer verification(TrustManager Concept).
975 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'verifySSL'));
976 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST
, CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'verifySSL') ?
2 : 0);
978 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, 1);
979 curl_setopt($ch, CURLOPT_POST
, 1);
982 foreach ($args as $n => $v) {
983 $p[] = "$n=" . urlencode($v);
986 //NVPRequest for submitting to server
987 $nvpreq = implode('&', $p);
989 //setting the nvpreq as POST FIELD to curl
990 curl_setopt($ch, CURLOPT_POSTFIELDS
, $nvpreq);
992 //getting response from server
993 $response = curl_exec($ch);
995 //converting NVPResponse to an Associative Array
996 $result = self
::deformat($response);
998 if (curl_errno($ch)) {
999 $e = CRM_Core_Error
::singleton();
1000 $e->push(curl_errno($ch),
1010 if (strtolower($result['ack']) != 'success' &&
1011 strtolower($result['ack']) != 'successwithwarning'
1013 $e = CRM_Core_Error
::singleton();
1014 $e->push($result['l_errorcode0'],
1016 "{$result['l_shortmessage0']} {$result['l_longmessage0']}"
1025 * This function will take NVPString and convert it to an Associative Array and it will decode the response.
1026 * It is useful to search for a particular key and displaying arrays.
1027 * @nvpstr is NVPString.
1028 * @nvpArray is Associative Array.
1030 public static function deformat($str) {
1033 while (strlen($str)) {
1035 $keyPos = strpos($str, '=');
1037 // position of value
1038 $valPos = strpos($str, '&') ?
strpos($str, '&') : strlen($str);
1040 /*getting the Key and Value values and storing in a Associative Array*/
1042 $key = substr($str, 0, $keyPos);
1043 $val = substr($str, $keyPos +
1, $valPos - $keyPos - 1);
1045 //decoding the respose
1046 $result[strtolower(urldecode($key))] = urldecode($val);
1047 $str = substr($str, $valPos +
1, strlen($str));
1054 * Get array of fields that should be displayed on the payment form.
1057 * @throws CiviCRM_API3_Exception
1059 public function getPaymentFormFields() {
1060 if ($this->_processorName
== ts('PayPal Pro')) {
1061 return $this->getCreditCardFormFields();
1069 * Map the paypal params to CiviCRM params using a field map.
1071 * @param array $fieldMap
1072 * @param array $paypalParams
1076 protected function mapPaypalParamsToCivicrmParams($fieldMap, $paypalParams) {
1078 foreach ($fieldMap as $civicrmField => $paypalField) {
1079 $params[$civicrmField] = isset($paypalParams[$paypalField]) ?
$paypalParams[$paypalField] : NULL;
1085 * Is this being processed by payment express.
1087 * Either because it is payment express or because is pro with paypal express in use.
1089 * @param array $params
1093 protected function isPaypalExpress($params) {
1094 if ($this->_processorName
== ts('PayPal Express')) {
1098 // This would occur postProcess.
1099 if (!empty($params['token'])) {
1102 if (isset($params['button']) && stristr($params['button'], 'express')) {
1106 // The contribution form passes a 'button' but the event form might still set one of these fields.
1107 // @todo more standardisation & get paypal fully out of the form layer.
1108 $possibleExpressFields = array(
1109 '_qf_Register_upload_express_x',
1110 '_qf_Payment_upload_express_x',
1112 if (array_intersect_key($params, array_fill_keys($possibleExpressFields, 1))) {