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) {
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')) {
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'];
325 //LCD add new function for handling recurring payments for PayPal Express
327 * @param array $params
331 public function createRecurringPayments(&$params) {
333 // @todo this function is riddled with enotices - perhaps use $this->mapPaypalParamsToCivicrmParams($fieldMap, $result)
334 $this->initialize($args, 'CreateRecurringPaymentsProfile');
336 $start_time = strtotime(date('m/d/Y'));
337 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
339 $args['token'] = $params['token'];
340 $args['paymentAction'] = 'Sale';
341 $args['amt'] = $params['amount'];
342 $args['currencyCode'] = $params['currencyID'];
343 $args['payerID'] = $params['payer_id'];
344 $args['invnum'] = $params['invoiceID'];
345 $args['returnURL'] = $params['returnURL'];
346 $args['cancelURL'] = $params['cancelURL'];
347 $args['profilestartdate'] = $start_date;
348 $args['method'] = 'CreateRecurringPaymentsProfile';
349 $args['billingfrequency'] = $params['frequency_interval'];
350 $args['billingperiod'] = ucwords($params['frequency_unit']);
351 $args['desc'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
352 //$args['desc'] = 'Recurring Contribution';
353 $args['totalbillingcycles'] = $params['installments'];
354 $args['version'] = '56.0';
355 $args['profilereference'] = "i={$params['invoiceID']}" .
357 "&c={$params['contactID']}" .
358 "&r={$params['contributionRecurID']}" .
359 "&b={$params['contributionID']}" .
360 "&p={$params['contributionPageID']}";
362 // add CiviCRM BN code
363 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
365 $result = $this->invokeAPI($args);
367 if (is_a($result, 'CRM_Core_Error')) {
372 $params['trxn_id'] = $result['transactionid'];
373 $params['gross_amount'] = $result['amt'];
374 $params['fee_amount'] = $result['feeamt'];
375 $params['net_amount'] = $result['settleamt'];
376 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
377 $params['net_amount'] = $params['gross_amount'] - $params['fee_amount'];
379 $params['payment_status'] = $result['paymentstatus'];
380 $params['pending_reason'] = $result['pendingreason'];
389 public function initialize(&$args, $method) {
390 $args['user'] = $this->_paymentProcessor
['user_name'];
391 $args['pwd'] = $this->_paymentProcessor
['password'];
392 $args['version'] = 3.0;
393 $args['signature'] = $this->_paymentProcessor
['signature'];
394 $args['subject'] = CRM_Utils_Array
::value('subject', $this->_paymentProcessor
);
395 $args['method'] = $method;
399 * This function collects all the information from a web/api form and invokes
400 * the relevant payment processor specific functions to perform the transaction
402 * @param array $params
403 * Assoc array of input parameters for this transaction.
405 * @param string $component
407 * the result in an nice formatted array (or an error object)
409 public function doDirectPayment(&$params, $component = 'contribute') {
412 $this->initialize($args, 'DoDirectPayment');
414 $args['paymentAction'] = 'Sale';
415 $args['amt'] = $params['amount'];
416 $args['currencyCode'] = $params['currencyID'];
417 $args['invnum'] = $params['invoiceID'];
418 $args['ipaddress'] = $params['ip_address'];
419 $args['creditCardType'] = $params['credit_card_type'];
420 $args['acct'] = $params['credit_card_number'];
421 $args['expDate'] = sprintf('%02d', $params['month']) . $params['year'];
422 $args['cvv2'] = $params['cvv2'];
423 $args['firstName'] = $params['first_name'];
424 $args['lastName'] = $params['last_name'];
425 $args['email'] = CRM_Utils_Array
::value('email', $params);
426 $args['street'] = $params['street_address'];
427 $args['city'] = $params['city'];
428 $args['state'] = $params['state_province'];
429 $args['countryCode'] = $params['country'];
430 $args['zip'] = $params['postal_code'];
431 $args['desc'] = substr(CRM_Utils_Array
::value('description', $params), 0, 127);
432 $args['custom'] = CRM_Utils_Array
::value('accountingCode', $params);
434 // add CiviCRM BN code
435 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
437 if (CRM_Utils_Array
::value('is_recur', $params) == 1) {
438 $start_time = strtotime(date('m/d/Y'));
439 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
441 $args['PaymentAction'] = 'Sale';
442 $args['billingperiod'] = ucwords($params['frequency_unit']);
443 $args['billingfrequency'] = $params['frequency_interval'];
444 $args['method'] = "CreateRecurringPaymentsProfile";
445 $args['profilestartdate'] = $start_date;
447 $params['description'] . ": " .
448 $params['amount'] . " Per " .
449 $params['frequency_interval'] . " " .
450 $params['frequency_unit'];
451 $args['amt'] = $params['amount'];
452 $args['totalbillingcycles'] = $params['installments'];
453 $args['version'] = 56.0;
454 $args['PROFILEREFERENCE'] = "" .
455 "i=" . $params['invoiceID'] . "&m=" . $component .
456 "&c=" . $params['contactID'] . "&r=" . $params['contributionRecurID'] .
457 "&b=" . $params['contributionID'] . "&p=" . $params['contributionPageID'];
460 // Allow further manipulation of the arguments via custom hooks ..
461 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $args);
463 $result = $this->invokeAPI($args);
466 if (is_a($result, 'CRM_Core_Error')) {
470 $params['recurr_profile_id'] = NULL;
472 if (CRM_Utils_Array
::value('is_recur', $params) == 1) {
473 $params['recurr_profile_id'] = $result['profileid'];
478 $params['trxn_id'] = CRM_Utils_Array
::value('transactionid', $result);
479 $params['gross_amount'] = CRM_Utils_Array
::value('amt', $result);
484 * This function checks to see if we have the right config values.
487 * the error message if any
489 public function checkConfig() {
491 $paymentProcessorType = CRM_Core_PseudoConstant
::paymentProcessorType(FALSE, NULL, 'name');
493 if ($this->_paymentProcessor
['payment_processor_type_id'] != CRM_Utils_Array
::key('PayPal_Standard', $paymentProcessorType)) {
494 if (empty($this->_paymentProcessor
['signature'])) {
495 $error[] = ts('Signature is not set in the Administer » System Settings » Payment Processors.');
498 if (empty($this->_paymentProcessor
['password'])) {
499 $error[] = ts('Password is not set in the Administer » System Settings » Payment Processors.');
502 if (!$this->_paymentProcessor
['user_name']) {
503 $error[] = ts('User Name is not set in the Administer » System Settings » Payment Processors.');
506 if (!empty($error)) {
507 return implode('<p>', $error);
515 * @return null|string
517 public function cancelSubscriptionURL() {
518 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal_Standard') {
519 return "{$this->_paymentProcessor['url_site']}cgi-bin/webscr?cmd=_subscr-find&alias=" . urlencode($this->_paymentProcessor
['user_name']);
527 * Check whether a method is present ( & supported ) by the payment processor object.
529 * @param string $method
530 * Method to check for.
534 public function isSupported($method = 'cancelSubscription') {
535 if ($this->_paymentProcessor
['payment_processor_type'] != 'PayPal') {
536 // since subscription methods like cancelSubscription or updateBilling is not yet implemented / supported
537 // by standard or express.
540 return parent
::isSupported($method);
544 * Paypal express replaces the submit button with it's own.
547 * Should the form button by suppressed?
549 public function isSuppressSubmitButtons() {
550 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal_Express') {
557 * @param string $message
558 * @param array $params
560 * @return array|bool|object
562 public function cancelSubscription(&$message = '', $params = array()) {
563 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal') {
565 $this->initialize($args, 'ManageRecurringPaymentsProfileStatus');
567 $args['PROFILEID'] = CRM_Utils_Array
::value('subscriptionId', $params);
568 $args['ACTION'] = 'Cancel';
569 $args['NOTE'] = CRM_Utils_Array
::value('reason', $params);
571 $result = $this->invokeAPI($args);
572 if (is_a($result, 'CRM_Core_Error')) {
575 $message = "{$result['ack']}: profileid={$result['profileid']}";
582 * Process incoming notification.
584 * This is only supported for paypal pro at the moment & no specific plans to add this path to core
585 * for paypal standard as the goal must be to separate the 2.
587 * We don't need to handle paypal standard using this path as there has never been any historic support
588 * for paypal standard to call civicrm/payment/ipn as a path.
590 static public function handlePaymentNotification() {
591 $paypalIPN = new CRM_Core_Payment_PayPalProIPN($_REQUEST);
596 * @param string $message
597 * @param array $params
599 * @return array|bool|object
601 public function updateSubscriptionBillingInfo(&$message = '', $params = array()) {
602 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal') {
603 $config = CRM_Core_Config
::singleton();
605 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
607 $args['PROFILEID'] = $params['subscriptionId'];
608 $args['AMT'] = $params['amount'];
609 $args['CURRENCYCODE'] = $config->defaultCurrency
;
610 $args['CREDITCARDTYPE'] = $params['credit_card_type'];
611 $args['ACCT'] = $params['credit_card_number'];
612 $args['EXPDATE'] = sprintf('%02d', $params['month']) . $params['year'];
613 $args['CVV2'] = $params['cvv2'];
615 $args['FIRSTNAME'] = $params['first_name'];
616 $args['LASTNAME'] = $params['last_name'];
617 $args['STREET'] = $params['street_address'];
618 $args['CITY'] = $params['city'];
619 $args['STATE'] = $params['state_province'];
620 $args['COUNTRYCODE'] = $params['postal_code'];
621 $args['ZIP'] = $params['country'];
623 $result = $this->invokeAPI($args);
624 if (is_a($result, 'CRM_Core_Error')) {
627 $message = "{$result['ack']}: profileid={$result['profileid']}";
634 * @param string $message
635 * @param array $params
637 * @return array|bool|object
639 public function changeSubscriptionAmount(&$message = '', $params = array()) {
640 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal') {
641 $config = CRM_Core_Config
::singleton();
643 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
645 $args['PROFILEID'] = $params['subscriptionId'];
646 $args['AMT'] = $params['amount'];
647 $args['CURRENCYCODE'] = $config->defaultCurrency
;
648 $args['BILLINGFREQUENCY'] = $params['installments'];
650 $result = $this->invokeAPI($args);
651 CRM_Core_Error
::debug_var('$result', $result);
652 if (is_a($result, 'CRM_Core_Error')) {
655 $message = "{$result['ack']}: profileid={$result['profileid']}";
662 * Function to action pre-approval if supported
664 * @param array $params
665 * Parameters from the form
668 * - pre_approval_parameters (this will be stored on the calling form & available later)
669 * - redirect_url (if set the browser will be redirected to this.
671 public function doPreApproval(&$params) {
672 $this->_component
= $params['component'];
673 $token = $this->setExpressCheckOut($params);
675 'pre_approval_parameters' => array('token' => $token),
676 'redirect_url' => $this->_paymentProcessor
['url_site'] . "/cgi-bin/webscr?cmd=_express-checkout&token=$token",
681 * @param array $params
682 * @param string $component
686 public function doTransferCheckout(&$params, $component = 'contribute') {
687 $config = CRM_Core_Config
::singleton();
689 if ($component != 'contribute' && $component != 'event') {
690 CRM_Core_Error
::fatal(ts('Component is invalid'));
693 $notifyURL = $config->userFrameworkResourceURL
. "extern/ipn.php?reset=1&contactID={$params['contactID']}" . "&contributionID={$params['contributionID']}" . "&module={$component}";
695 if ($component == 'event') {
696 $notifyURL .= "&eventID={$params['eventID']}&participantID={$params['participantID']}";
699 $membershipID = CRM_Utils_Array
::value('membershipID', $params);
701 $notifyURL .= "&membershipID=$membershipID";
703 $relatedContactID = CRM_Utils_Array
::value('related_contact', $params);
704 if ($relatedContactID) {
705 $notifyURL .= "&relatedContactID=$relatedContactID";
707 $onBehalfDupeAlert = CRM_Utils_Array
::value('onbehalf_dupe_alert', $params);
708 if ($onBehalfDupeAlert) {
709 $notifyURL .= "&onBehalfDupeAlert=$onBehalfDupeAlert";
714 $url = ($component == 'event') ?
'civicrm/event/register' : 'civicrm/contribute/transact';
715 $cancel = ($component == 'event') ?
'_qf_Register_display' : '_qf_Main_display';
716 $returnURL = CRM_Utils_System
::url($url,
717 "_qf_ThankYou_display=1&qfKey={$params['qfKey']}",
721 $cancelUrlString = "$cancel=1&cancel=1&qfKey={$params['qfKey']}";
722 if (!empty($params['is_recur'])) {
723 $cancelUrlString .= "&isRecur=1&recurId={$params['contributionRecurID']}&contribId={$params['contributionID']}";
726 $cancelURL = CRM_Utils_System
::url(
732 // ensure that the returnURL is absolute.
733 if (substr($returnURL, 0, 4) != 'http') {
734 $fixUrl = CRM_Utils_System
::url("civicrm/admin/setting/url", '&reset=1');
735 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)));
738 $paypalParams = array(
739 'business' => $this->_paymentProcessor
['user_name'],
740 'notify_url' => $notifyURL,
741 'item_name' => $params['item_name'],
743 'undefined_quantity' => 0,
744 'cancel_return' => $cancelURL,
747 'return' => $returnURL,
749 'currency_code' => $params['currencyID'],
750 'invoice' => $params['invoiceID'],
751 'lc' => substr($config->lcMessages
, -2),
752 'charset' => function_exists('mb_internal_encoding') ?
mb_internal_encoding() : 'UTF-8',
753 'custom' => CRM_Utils_Array
::value('accountingCode', $params),
754 'bn' => 'CiviCRM_SP',
757 // add name and address if available, CRM-3130
759 'first_name' => 'first_name',
760 'last_name' => 'last_name',
761 'street_address' => 'address1',
762 'country' => 'country',
763 'preferred_language' => 'lc',
765 'state_province' => 'state',
766 'postal_code' => 'zip',
770 foreach (array_keys($params) as $p) {
771 // get the base name without the location type suffixed to it
772 $parts = explode('-', $p);
773 $name = count($parts) > 1 ?
$parts[0] : $p;
774 if (isset($otherVars[$name])) {
775 $value = $params[$p];
777 if ($name == 'state_province') {
778 $stateName = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($value);
781 if ($name == 'country') {
782 $countryName = CRM_Core_PseudoConstant
::countryIsoCode($value);
783 $value = $countryName;
785 // ensure value is not an array
787 if (!is_array($value)) {
788 $paypalParams[$otherVars[$name]] = $value;
794 // if recurring donations, add a few more items
795 if (!empty($params['is_recur'])) {
796 if ($params['contributionRecurID']) {
797 $notifyURL .= "&contributionRecurID={$params['contributionRecurID']}&contributionPageID={$params['contributionPageID']}";
798 $paypalParams['notify_url'] = $notifyURL;
801 CRM_Core_Error
::fatal(ts('Recurring contribution, but no database id'));
804 $paypalParams +
= array(
805 'cmd' => '_xclick-subscriptions',
806 'a3' => $params['amount'],
807 'p3' => $params['frequency_interval'],
808 't3' => ucfirst(substr($params['frequency_unit'], 0, 1)),
811 'srt' => CRM_Utils_Array
::value('installments', $params),
817 $paypalParams +
= array(
819 'amount' => $params['amount'],
823 // Allow further manipulation of the arguments via custom hooks ..
824 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $paypalParams);
827 foreach ($paypalParams as $key => $value) {
828 if ($value === NULL) {
832 $value = urlencode($value);
833 if ($key == 'return' ||
834 $key == 'cancel_return' ||
837 $value = str_replace('%2F', '/', $value);
839 $uri .= "&{$key}={$value}";
842 $uri = substr($uri, 1);
843 $url = $this->_paymentProcessor
['url_site'];
844 $sub = empty($params['is_recur']) ?
'cgi-bin/webscr' : 'subscriptions';
845 $paypalURL = "{$url}{$sub}?$uri";
847 CRM_Utils_System
::redirect($paypalURL);
851 * Hash_call: Function to perform the API call to PayPal using API signature
852 * @methodName is name of API method.
853 * @nvpStr is nvp string.
854 * returns an associtive array containing the response from the server.
856 public function invokeAPI($args, $url = NULL) {
859 if (empty($this->_paymentProcessor
['url_api'])) {
860 CRM_Core_Error
::fatal(ts('Please set the API URL. Please refer to the documentation for more details'));
863 $url = $this->_paymentProcessor
['url_api'] . 'nvp';
866 if (!function_exists('curl_init')) {
867 CRM_Core_Error
::fatal("curl functions NOT available.");
870 //setting the curl parameters.
872 curl_setopt($ch, CURLOPT_URL
, $url);
873 curl_setopt($ch, CURLOPT_VERBOSE
, 1);
875 //turning off the server and peer verification(TrustManager Concept).
876 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'verifySSL'));
877 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST
, CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'verifySSL') ?
2 : 0);
879 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, 1);
880 curl_setopt($ch, CURLOPT_POST
, 1);
883 foreach ($args as $n => $v) {
884 $p[] = "$n=" . urlencode($v);
887 //NVPRequest for submitting to server
888 $nvpreq = implode('&', $p);
890 //setting the nvpreq as POST FIELD to curl
891 curl_setopt($ch, CURLOPT_POSTFIELDS
, $nvpreq);
893 //getting response from server
894 $response = curl_exec($ch);
896 //converting NVPResponse to an Associative Array
897 $result = self
::deformat($response);
899 if (curl_errno($ch)) {
900 $e = CRM_Core_Error
::singleton();
901 $e->push(curl_errno($ch),
911 if (strtolower($result['ack']) != 'success' &&
912 strtolower($result['ack']) != 'successwithwarning'
914 $e = CRM_Core_Error
::singleton();
915 $e->push($result['l_errorcode0'],
917 "{$result['l_shortmessage0']} {$result['l_longmessage0']}"
926 * This function will take NVPString and convert it to an Associative Array and it will decode the response.
927 * It is useful to search for a particular key and displaying arrays.
928 * @nvpstr is NVPString.
929 * @nvpArray is Associative Array.
931 public static function deformat($str) {
934 while (strlen($str)) {
936 $keyPos = strpos($str, '=');
939 $valPos = strpos($str, '&') ?
strpos($str, '&') : strlen($str);
941 /*getting the Key and Value values and storing in a Associative Array*/
943 $key = substr($str, 0, $keyPos);
944 $val = substr($str, $keyPos +
1, $valPos - $keyPos - 1);
946 //decoding the respose
947 $result[strtolower(urldecode($key))] = urldecode($val);
948 $str = substr($str, $valPos +
1, strlen($str));
955 * Get array of fields that should be displayed on the payment form.
958 * @throws CiviCRM_API3_Exception
960 public function getPaymentFormFields() {
961 if ($this->_processorName
== ts('PayPal Pro')) {
962 return $this->getCreditCardFormFields();
970 * Map the paypal params to CiviCRM params using a field map.
972 * @param array $fieldMap
973 * @param array $paypalParams
977 protected function mapPaypalParamsToCivicrmParams($fieldMap, $paypalParams) {
979 foreach ($fieldMap as $civicrmField => $paypalField) {
980 $params[$civicrmField] = isset($paypalParams[$paypalField]) ?
$paypalParams[$paypalField] : NULL;