3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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
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 * Express checkout code. Check PayPal documentation for more information
161 * @param array $params
162 * Assoc array of input parameters for this transaction.
165 * the result in an nice formatted array (or an error object)
167 protected function setExpressCheckOut(&$params) {
170 $this->initialize($args, 'SetExpressCheckout');
172 $args['paymentAction'] = 'Sale';
173 $args['amt'] = $params['amount'];
174 $args['currencyCode'] = $params['currencyID'];
175 $args['desc'] = CRM_Utils_Array
::value('description', $params);
176 $args['invnum'] = $params['invoiceID'];
177 $args['returnURL'] = $this->getReturnSuccessUrl($params['qfKey']);
178 $args['cancelURL'] = $this->getCancelUrl($params['qfKey'], NULL);
179 $args['version'] = '56.0';
181 //LCD if recurring, collect additional data and set some values
182 if (!empty($params['is_recur'])) {
183 $args['L_BILLINGTYPE0'] = 'RecurringPayments';
184 //$args['L_BILLINGAGREEMENTDESCRIPTION0'] = 'Recurring Contribution';
185 $args['L_BILLINGAGREEMENTDESCRIPTION0'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
186 $args['L_PAYMENTTYPE0'] = 'Any';
189 // Allow further manipulation of the arguments via custom hooks ..
190 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $args);
192 $result = $this->invokeAPI($args);
194 if (is_a($result, 'CRM_Core_Error')) {
200 return $result['token'];
204 * Get any details that may be available to the payment processor due to an approval process having happened.
206 * In some cases the browser is redirected to enter details on a processor site. Some details may be available as a
209 * @param array $storedDetails
213 public function getPreApprovalDetails($storedDetails) {
214 return $this->getExpressCheckoutDetails($storedDetails['token']);
218 * Get details from paypal. Check PayPal documentation for more information
220 * @param string $token
221 * The key associated with this transaction.
224 * the result in an nice formatted array (or an error object)
226 public function getExpressCheckoutDetails($token) {
229 $this->initialize($args, 'GetExpressCheckoutDetails');
230 $args['token'] = $token;
232 $args['method'] = 'GetExpressCheckoutDetails';
234 $result = $this->invokeAPI($args);
236 if (is_a($result, 'CRM_Core_Error')) {
243 'payer_status' => 'payerstatus',
244 'payer_id' => 'payerid',
245 'first_name' => 'firstname',
246 'middle_name' => 'middlename',
247 'last_name' => 'lastname',
248 'street_address' => 'shiptostreet',
249 'supplemental_address_1' => 'shiptostreet2',
250 'city' => 'shiptocity',
251 'postal_code' => 'shiptozip',
252 'state_province' => 'shiptostate',
253 'country' => 'shiptocountrycode',
255 return $this->mapPaypalParamsToCivicrmParams($fieldMap, $result);
259 * Do the express checkout at paypal. Check PayPal documentation for more information
261 * @param array $params
263 * @internal param string $token the key associated with this transaction
266 * the result in an nice formatted array (or an error object)
268 public function doExpressCheckout(&$params) {
270 if (!empty($params['is_recur'])) {
271 return $this->createRecurringPayments($params);
275 $this->initialize($args, 'DoExpressCheckoutPayment');
276 $args['token'] = $params['token'];
277 $args['paymentAction'] = 'Sale';
278 $args['amt'] = $params['amount'];
279 $args['currencyCode'] = $params['currencyID'];
280 $args['payerID'] = $params['payer_id'];
281 $args['invnum'] = $params['invoiceID'];
282 $args['returnURL'] = $this->getReturnSuccessUrl($params['qfKey']);
283 $args['cancelURL'] = $this->getCancelUrl($params['qfKey'], NULL);
284 $args['desc'] = $params['description'];
286 // add CiviCRM BN code
287 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
289 $result = $this->invokeAPI($args);
291 if (is_a($result, 'CRM_Core_Error')) {
297 $params['trxn_id'] = $result['transactionid'];
298 $params['gross_amount'] = $result['amt'];
299 $params['fee_amount'] = $result['feeamt'];
300 $params['net_amount'] = CRM_Utils_Array
::value('settleamt', $result);
301 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
302 $params['net_amount'] = $params['gross_amount'] - $params['fee_amount'];
304 $params['payment_status'] = $result['paymentstatus'];
305 $params['pending_reason'] = $result['pendingreason'];
310 //LCD add new function for handling recurring payments for PayPal Express
312 * @param array $params
316 public function createRecurringPayments(&$params) {
318 // @todo this function is riddled with enotices - perhaps use $this->mapPaypalParamsToCivicrmParams($fieldMap, $result)
319 $this->initialize($args, 'CreateRecurringPaymentsProfile');
321 $start_time = strtotime(date('m/d/Y'));
322 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
324 $args['token'] = $params['token'];
325 $args['paymentAction'] = 'Sale';
326 $args['amt'] = $params['amount'];
327 $args['currencyCode'] = $params['currencyID'];
328 $args['payerID'] = $params['payer_id'];
329 $args['invnum'] = $params['invoiceID'];
330 $args['returnURL'] = $params['returnURL'];
331 $args['cancelURL'] = $params['cancelURL'];
332 $args['profilestartdate'] = $start_date;
333 $args['method'] = 'CreateRecurringPaymentsProfile';
334 $args['billingfrequency'] = $params['frequency_interval'];
335 $args['billingperiod'] = ucwords($params['frequency_unit']);
336 $args['desc'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
337 //$args['desc'] = 'Recurring Contribution';
338 $args['totalbillingcycles'] = $params['installments'];
339 $args['version'] = '56.0';
340 $args['profilereference'] = "i={$params['invoiceID']}" .
342 "&c={$params['contactID']}" .
343 "&r={$params['contributionRecurID']}" .
344 "&b={$params['contributionID']}" .
345 "&p={$params['contributionPageID']}";
347 // add CiviCRM BN code
348 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
350 $result = $this->invokeAPI($args);
352 if (is_a($result, 'CRM_Core_Error')) {
357 $params['trxn_id'] = $result['transactionid'];
358 $params['gross_amount'] = $result['amt'];
359 $params['fee_amount'] = $result['feeamt'];
360 $params['net_amount'] = $result['settleamt'];
361 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
362 $params['net_amount'] = $params['gross_amount'] - $params['fee_amount'];
364 $params['payment_status'] = $result['paymentstatus'];
365 $params['pending_reason'] = $result['pendingreason'];
374 public function initialize(&$args, $method) {
375 $args['user'] = $this->_paymentProcessor
['user_name'];
376 $args['pwd'] = $this->_paymentProcessor
['password'];
377 $args['version'] = 3.0;
378 $args['signature'] = $this->_paymentProcessor
['signature'];
379 $args['subject'] = CRM_Utils_Array
::value('subject', $this->_paymentProcessor
);
380 $args['method'] = $method;
384 * This function collects all the information from a web/api form and invokes
385 * the relevant payment processor specific functions to perform the transaction
387 * @param array $params
388 * Assoc array of input parameters for this transaction.
390 * @param string $component
392 * the result in an nice formatted array (or an error object)
394 public function doDirectPayment(&$params, $component = 'contribute') {
397 $this->initialize($args, 'DoDirectPayment');
399 $args['paymentAction'] = 'Sale';
400 $args['amt'] = $params['amount'];
401 $args['currencyCode'] = $params['currencyID'];
402 $args['invnum'] = $params['invoiceID'];
403 $args['ipaddress'] = $params['ip_address'];
404 $args['creditCardType'] = $params['credit_card_type'];
405 $args['acct'] = $params['credit_card_number'];
406 $args['expDate'] = sprintf('%02d', $params['month']) . $params['year'];
407 $args['cvv2'] = $params['cvv2'];
408 $args['firstName'] = $params['first_name'];
409 $args['lastName'] = $params['last_name'];
410 $args['email'] = CRM_Utils_Array
::value('email', $params);
411 $args['street'] = $params['street_address'];
412 $args['city'] = $params['city'];
413 $args['state'] = $params['state_province'];
414 $args['countryCode'] = $params['country'];
415 $args['zip'] = $params['postal_code'];
416 $args['desc'] = substr(CRM_Utils_Array
::value('description', $params), 0, 127);
417 $args['custom'] = CRM_Utils_Array
::value('accountingCode', $params);
419 // add CiviCRM BN code
420 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
422 if (CRM_Utils_Array
::value('is_recur', $params) == 1) {
423 $start_time = strtotime(date('m/d/Y'));
424 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
426 $args['PaymentAction'] = 'Sale';
427 $args['billingperiod'] = ucwords($params['frequency_unit']);
428 $args['billingfrequency'] = $params['frequency_interval'];
429 $args['method'] = "CreateRecurringPaymentsProfile";
430 $args['profilestartdate'] = $start_date;
432 $params['description'] . ": " .
433 $params['amount'] . " Per " .
434 $params['frequency_interval'] . " " .
435 $params['frequency_unit'];
436 $args['amt'] = $params['amount'];
437 $args['totalbillingcycles'] = $params['installments'];
438 $args['version'] = 56.0;
439 $args['PROFILEREFERENCE'] = "" .
440 "i=" . $params['invoiceID'] . "&m=" . $component .
441 "&c=" . $params['contactID'] . "&r=" . $params['contributionRecurID'] .
442 "&b=" . $params['contributionID'] . "&p=" . $params['contributionPageID'];
445 // Allow further manipulation of the arguments via custom hooks ..
446 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $args);
448 $result = $this->invokeAPI($args);
451 if (is_a($result, 'CRM_Core_Error')) {
455 $params['recurr_profile_id'] = NULL;
457 if (CRM_Utils_Array
::value('is_recur', $params) == 1) {
458 $params['recurr_profile_id'] = $result['profileid'];
463 $params['trxn_id'] = CRM_Utils_Array
::value('transactionid', $result);
464 $params['gross_amount'] = CRM_Utils_Array
::value('amt', $result);
469 * This function checks to see if we have the right config values.
472 * the error message if any
474 public function checkConfig() {
476 $paymentProcessorType = CRM_Core_PseudoConstant
::paymentProcessorType(FALSE, NULL, 'name');
478 if ($this->_paymentProcessor
['payment_processor_type_id'] != CRM_Utils_Array
::key('PayPal_Standard', $paymentProcessorType)) {
479 if (empty($this->_paymentProcessor
['signature'])) {
480 $error[] = ts('Signature is not set in the Administer » System Settings » Payment Processors.');
483 if (empty($this->_paymentProcessor
['password'])) {
484 $error[] = ts('Password is not set in the Administer » System Settings » Payment Processors.');
487 if (!$this->_paymentProcessor
['user_name']) {
488 $error[] = ts('User Name is not set in the Administer » System Settings » Payment Processors.');
491 if (!empty($error)) {
492 return implode('<p>', $error);
500 * @return null|string
502 public function cancelSubscriptionURL() {
503 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal_Standard') {
504 return "{$this->_paymentProcessor['url_site']}cgi-bin/webscr?cmd=_subscr-find&alias=" . urlencode($this->_paymentProcessor
['user_name']);
512 * Check whether a method is present ( & supported ) by the payment processor object.
514 * @param string $method
515 * Method to check for.
519 public function isSupported($method = 'cancelSubscription') {
520 if ($this->_paymentProcessor
['payment_processor_type'] != 'PayPal') {
521 // since subscription methods like cancelSubscription or updateBilling is not yet implemented / supported
522 // by standard or express.
525 return parent
::isSupported($method);
529 * Paypal express replaces the submit button with it's own.
532 * Should the form button by suppressed?
534 public function isSuppressSubmitButtons() {
535 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal_Express') {
542 * @param string $message
543 * @param array $params
545 * @return array|bool|object
547 public function cancelSubscription(&$message = '', $params = array()) {
548 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal') {
550 $this->initialize($args, 'ManageRecurringPaymentsProfileStatus');
552 $args['PROFILEID'] = CRM_Utils_Array
::value('subscriptionId', $params);
553 $args['ACTION'] = 'Cancel';
554 $args['NOTE'] = CRM_Utils_Array
::value('reason', $params);
556 $result = $this->invokeAPI($args);
557 if (is_a($result, 'CRM_Core_Error')) {
560 $message = "{$result['ack']}: profileid={$result['profileid']}";
567 * Process incoming notification.
569 * This is only supported for paypal pro at the moment & no specific plans to add this path to core
570 * for paypal standard as the goal must be to separate the 2.
572 * We don't need to handle paypal standard using this path as there has never been any historic support
573 * for paypal standard to call civicrm/payment/ipn as a path.
575 static public function handlePaymentNotification() {
576 $paypalIPN = new CRM_Core_Payment_PayPalProIPN($_REQUEST);
581 * @param string $message
582 * @param array $params
584 * @return array|bool|object
586 public function updateSubscriptionBillingInfo(&$message = '', $params = array()) {
587 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal') {
588 $config = CRM_Core_Config
::singleton();
590 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
592 $args['PROFILEID'] = $params['subscriptionId'];
593 $args['AMT'] = $params['amount'];
594 $args['CURRENCYCODE'] = $config->defaultCurrency
;
595 $args['CREDITCARDTYPE'] = $params['credit_card_type'];
596 $args['ACCT'] = $params['credit_card_number'];
597 $args['EXPDATE'] = sprintf('%02d', $params['month']) . $params['year'];
598 $args['CVV2'] = $params['cvv2'];
600 $args['FIRSTNAME'] = $params['first_name'];
601 $args['LASTNAME'] = $params['last_name'];
602 $args['STREET'] = $params['street_address'];
603 $args['CITY'] = $params['city'];
604 $args['STATE'] = $params['state_province'];
605 $args['COUNTRYCODE'] = $params['postal_code'];
606 $args['ZIP'] = $params['country'];
608 $result = $this->invokeAPI($args);
609 if (is_a($result, 'CRM_Core_Error')) {
612 $message = "{$result['ack']}: profileid={$result['profileid']}";
619 * @param string $message
620 * @param array $params
622 * @return array|bool|object
624 public function changeSubscriptionAmount(&$message = '', $params = array()) {
625 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal') {
626 $config = CRM_Core_Config
::singleton();
628 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
630 $args['PROFILEID'] = $params['subscriptionId'];
631 $args['AMT'] = $params['amount'];
632 $args['CURRENCYCODE'] = $config->defaultCurrency
;
633 $args['BILLINGFREQUENCY'] = $params['installments'];
635 $result = $this->invokeAPI($args);
636 CRM_Core_Error
::debug_var('$result', $result);
637 if (is_a($result, 'CRM_Core_Error')) {
640 $message = "{$result['ack']}: profileid={$result['profileid']}";
647 * Function to action pre-approval if supported
649 * @param array $params
650 * Parameters from the form
653 * - pre_approval_parameters (this will be stored on the calling form & available later)
654 * - redirect_url (if set the browser will be redirected to this.
656 public function doPreApproval(&$params) {
657 $this->_component
= $params['component'];
658 $token = $this->setExpressCheckOut($params);
660 'pre_approval_parameters' => array('token' => $token),
661 'redirect_url' => $this->_paymentProcessor
['url_site'] . "/cgi-bin/webscr?cmd=_express-checkout&token=$token",
666 * @param array $params
667 * @param string $component
671 public function doTransferCheckout(&$params, $component = 'contribute') {
672 $config = CRM_Core_Config
::singleton();
674 if ($component != 'contribute' && $component != 'event') {
675 CRM_Core_Error
::fatal(ts('Component is invalid'));
678 $notifyURL = $config->userFrameworkResourceURL
. "extern/ipn.php?reset=1&contactID={$params['contactID']}" . "&contributionID={$params['contributionID']}" . "&module={$component}";
680 if ($component == 'event') {
681 $notifyURL .= "&eventID={$params['eventID']}&participantID={$params['participantID']}";
684 $membershipID = CRM_Utils_Array
::value('membershipID', $params);
686 $notifyURL .= "&membershipID=$membershipID";
688 $relatedContactID = CRM_Utils_Array
::value('related_contact', $params);
689 if ($relatedContactID) {
690 $notifyURL .= "&relatedContactID=$relatedContactID";
692 $onBehalfDupeAlert = CRM_Utils_Array
::value('onbehalf_dupe_alert', $params);
693 if ($onBehalfDupeAlert) {
694 $notifyURL .= "&onBehalfDupeAlert=$onBehalfDupeAlert";
699 $url = ($component == 'event') ?
'civicrm/event/register' : 'civicrm/contribute/transact';
700 $cancel = ($component == 'event') ?
'_qf_Register_display' : '_qf_Main_display';
701 $returnURL = CRM_Utils_System
::url($url,
702 "_qf_ThankYou_display=1&qfKey={$params['qfKey']}",
706 $cancelUrlString = "$cancel=1&cancel=1&qfKey={$params['qfKey']}";
707 if (!empty($params['is_recur'])) {
708 $cancelUrlString .= "&isRecur=1&recurId={$params['contributionRecurID']}&contribId={$params['contributionID']}";
711 $cancelURL = CRM_Utils_System
::url(
717 // ensure that the returnURL is absolute.
718 if (substr($returnURL, 0, 4) != 'http') {
719 $fixUrl = CRM_Utils_System
::url("civicrm/admin/setting/url", '&reset=1');
720 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)));
723 $paypalParams = array(
724 'business' => $this->_paymentProcessor
['user_name'],
725 'notify_url' => $notifyURL,
726 'item_name' => $params['item_name'],
728 'undefined_quantity' => 0,
729 'cancel_return' => $cancelURL,
732 'return' => $returnURL,
734 'currency_code' => $params['currencyID'],
735 'invoice' => $params['invoiceID'],
736 'lc' => substr($config->lcMessages
, -2),
737 'charset' => function_exists('mb_internal_encoding') ?
mb_internal_encoding() : 'UTF-8',
738 'custom' => CRM_Utils_Array
::value('accountingCode', $params),
739 'bn' => 'CiviCRM_SP',
742 // add name and address if available, CRM-3130
744 'first_name' => 'first_name',
745 'last_name' => 'last_name',
746 'street_address' => 'address1',
747 'country' => 'country',
748 'preferred_language' => 'lc',
750 'state_province' => 'state',
751 'postal_code' => 'zip',
755 foreach (array_keys($params) as $p) {
756 // get the base name without the location type suffixed to it
757 $parts = explode('-', $p);
758 $name = count($parts) > 1 ?
$parts[0] : $p;
759 if (isset($otherVars[$name])) {
760 $value = $params[$p];
762 if ($name == 'state_province') {
763 $stateName = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($value);
766 if ($name == 'country') {
767 $countryName = CRM_Core_PseudoConstant
::countryIsoCode($value);
768 $value = $countryName;
770 // ensure value is not an array
772 if (!is_array($value)) {
773 $paypalParams[$otherVars[$name]] = $value;
779 // if recurring donations, add a few more items
780 if (!empty($params['is_recur'])) {
781 if ($params['contributionRecurID']) {
782 $notifyURL .= "&contributionRecurID={$params['contributionRecurID']}&contributionPageID={$params['contributionPageID']}";
783 $paypalParams['notify_url'] = $notifyURL;
786 CRM_Core_Error
::fatal(ts('Recurring contribution, but no database id'));
789 $paypalParams +
= array(
790 'cmd' => '_xclick-subscriptions',
791 'a3' => $params['amount'],
792 'p3' => $params['frequency_interval'],
793 't3' => ucfirst(substr($params['frequency_unit'], 0, 1)),
796 'srt' => CRM_Utils_Array
::value('installments', $params),
802 $paypalParams +
= array(
804 'amount' => $params['amount'],
808 // Allow further manipulation of the arguments via custom hooks ..
809 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $paypalParams);
812 foreach ($paypalParams as $key => $value) {
813 if ($value === NULL) {
817 $value = urlencode($value);
818 if ($key == 'return' ||
819 $key == 'cancel_return' ||
822 $value = str_replace('%2F', '/', $value);
824 $uri .= "&{$key}={$value}";
827 $uri = substr($uri, 1);
828 $url = $this->_paymentProcessor
['url_site'];
829 $sub = empty($params['is_recur']) ?
'cgi-bin/webscr' : 'subscriptions';
830 $paypalURL = "{$url}{$sub}?$uri";
832 CRM_Utils_System
::redirect($paypalURL);
836 * Hash_call: Function to perform the API call to PayPal using API signature
837 * @methodName is name of API method.
838 * @nvpStr is nvp string.
839 * returns an associtive array containing the response from the server.
841 public function invokeAPI($args, $url = NULL) {
844 if (empty($this->_paymentProcessor
['url_api'])) {
845 CRM_Core_Error
::fatal(ts('Please set the API URL. Please refer to the documentation for more details'));
848 $url = $this->_paymentProcessor
['url_api'] . 'nvp';
851 if (!function_exists('curl_init')) {
852 CRM_Core_Error
::fatal("curl functions NOT available.");
855 //setting the curl parameters.
857 curl_setopt($ch, CURLOPT_URL
, $url);
858 curl_setopt($ch, CURLOPT_VERBOSE
, 1);
860 //turning off the server and peer verification(TrustManager Concept).
861 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'verifySSL'));
862 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST
, CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'verifySSL') ?
2 : 0);
864 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, 1);
865 curl_setopt($ch, CURLOPT_POST
, 1);
868 foreach ($args as $n => $v) {
869 $p[] = "$n=" . urlencode($v);
872 //NVPRequest for submitting to server
873 $nvpreq = implode('&', $p);
875 //setting the nvpreq as POST FIELD to curl
876 curl_setopt($ch, CURLOPT_POSTFIELDS
, $nvpreq);
878 //getting response from server
879 $response = curl_exec($ch);
881 //converting NVPResponse to an Associative Array
882 $result = self
::deformat($response);
884 if (curl_errno($ch)) {
885 $e = CRM_Core_Error
::singleton();
886 $e->push(curl_errno($ch),
896 if (strtolower($result['ack']) != 'success' &&
897 strtolower($result['ack']) != 'successwithwarning'
899 $e = CRM_Core_Error
::singleton();
900 $e->push($result['l_errorcode0'],
902 "{$result['l_shortmessage0']} {$result['l_longmessage0']}"
911 * This function will take NVPString and convert it to an Associative Array and it will decode the response.
912 * It is useful to search for a particular key and displaying arrays.
913 * @nvpstr is NVPString.
914 * @nvpArray is Associative Array.
916 public static function deformat($str) {
919 while (strlen($str)) {
921 $keyPos = strpos($str, '=');
924 $valPos = strpos($str, '&') ?
strpos($str, '&') : strlen($str);
926 /*getting the Key and Value values and storing in a Associative Array*/
928 $key = substr($str, 0, $keyPos);
929 $val = substr($str, $keyPos +
1, $valPos - $keyPos - 1);
931 //decoding the respose
932 $result[strtolower(urldecode($key))] = urldecode($val);
933 $str = substr($str, $valPos +
1, strlen($str));
940 * Get array of fields that should be displayed on the payment form.
943 * @throws CiviCRM_API3_Exception
945 public function getPaymentFormFields() {
946 if ($this->_processorName
== ts('PayPal Pro')) {
947 return $this->getCreditCardFormFields();
955 * Map the paypal params to CiviCRM params using a field map.
957 * @param array $fieldMap
958 * @param array $paypalParams
962 protected function mapPaypalParamsToCivicrmParams($fieldMap, $paypalParams) {
964 foreach ($fieldMap as $civicrmField => $paypalField) {
965 $params[$civicrmField] = isset($paypalParams[$paypalField]) ?
$paypalParams[$paypalField] : NULL;