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 * Express checkout code. Check PayPal documentation for more information
145 * @param array $params
146 * Assoc array of input parameters for this transaction.
149 * the result in an nice formatted array (or an error object)
151 protected function setExpressCheckOut(&$params) {
154 $this->initialize($args, 'SetExpressCheckout');
156 $args['paymentAction'] = 'Sale';
157 $args['amt'] = $params['amount'];
158 $args['currencyCode'] = $params['currencyID'];
159 $args['desc'] = CRM_Utils_Array
::value('description', $params);
160 $args['invnum'] = $params['invoiceID'];
161 $args['returnURL'] = $this->getReturnSuccessUrl($params['qfKey']);
162 $args['cancelURL'] = $this->getCancelUrl($params['qfKey'], NULL);
163 $args['version'] = '56.0';
165 //LCD if recurring, collect additional data and set some values
166 if (!empty($params['is_recur'])) {
167 $args['L_BILLINGTYPE0'] = 'RecurringPayments';
168 //$args['L_BILLINGAGREEMENTDESCRIPTION0'] = 'Recurring Contribution';
169 $args['L_BILLINGAGREEMENTDESCRIPTION0'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
170 $args['L_PAYMENTTYPE0'] = 'Any';
173 // Allow further manipulation of the arguments via custom hooks ..
174 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $args);
176 $result = $this->invokeAPI($args);
178 if (is_a($result, 'CRM_Core_Error')) {
184 return $result['token'];
188 * Get any details that may be available to the payment processor due to an approval process having happened.
190 * In some cases the browser is redirected to enter details on a processor site. Some details may be available as a
193 * @param array $storedDetails
197 public function getPreApprovalDetails($storedDetails) {
198 return $this->getExpressCheckoutDetails($storedDetails['token']);
202 * Get details from paypal. Check PayPal documentation for more information
204 * @param string $token
205 * The key associated with this transaction.
208 * the result in an nice formatted array (or an error object)
210 public function getExpressCheckoutDetails($token) {
213 $this->initialize($args, 'GetExpressCheckoutDetails');
214 $args['token'] = $token;
216 $args['method'] = 'GetExpressCheckoutDetails';
218 $result = $this->invokeAPI($args);
220 if (is_a($result, 'CRM_Core_Error')) {
227 'payer_status' => 'payerstatus',
228 'payer_id' => 'payerid',
229 'first_name' => 'firstname',
230 'middle_name' => 'middlename',
231 'last_name' => 'lastname',
232 'street_address' => 'shiptostreet',
233 'supplemental_address_1' => 'shiptostreet2',
234 'city' => 'shiptocity',
235 'postal_code' => 'shiptozip',
236 'state_province' => 'shiptostate',
237 'country' => 'shiptocountrycode',
239 return $this->mapPaypalParamsToCivicrmParams($fieldMap, $result);
243 * Do the express checkout at paypal. Check PayPal documentation for more information
245 * @param array $params
247 * @internal param string $token the key associated with this transaction
250 * the result in an nice formatted array (or an error object)
252 public function doExpressCheckout(&$params) {
254 if (!empty($params['is_recur'])) {
255 return $this->createRecurringPayments($params);
259 $this->initialize($args, 'DoExpressCheckoutPayment');
260 $args['token'] = $params['token'];
261 $args['paymentAction'] = 'Sale';
262 $args['amt'] = $params['amount'];
263 $args['currencyCode'] = $params['currencyID'];
264 $args['payerID'] = $params['payer_id'];
265 $args['invnum'] = $params['invoiceID'];
266 $args['returnURL'] = $this->getReturnSuccessUrl($params['qfKey']);
267 $args['cancelURL'] = $this->getCancelUrl($params['qfKey'], NULL);
268 $args['desc'] = $params['description'];
270 // add CiviCRM BN code
271 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
273 $result = $this->invokeAPI($args);
275 if (is_a($result, 'CRM_Core_Error')) {
281 $params['trxn_id'] = $result['transactionid'];
282 $params['gross_amount'] = $result['amt'];
283 $params['fee_amount'] = $result['feeamt'];
284 $params['net_amount'] = CRM_Utils_Array
::value('settleamt', $result);
285 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
286 $params['net_amount'] = $params['gross_amount'] - $params['fee_amount'];
288 $params['payment_status'] = $result['paymentstatus'];
289 $params['pending_reason'] = $result['pendingreason'];
294 //LCD add new function for handling recurring payments for PayPal Express
296 * @param array $params
300 public function createRecurringPayments(&$params) {
302 // @todo this function is riddled with enotices - perhaps use $this->mapPaypalParamsToCivicrmParams($fieldMap, $result)
303 $this->initialize($args, 'CreateRecurringPaymentsProfile');
305 $start_time = strtotime(date('m/d/Y'));
306 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
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'] = $params['returnURL'];
315 $args['cancelURL'] = $params['cancelURL'];
316 $args['profilestartdate'] = $start_date;
317 $args['method'] = 'CreateRecurringPaymentsProfile';
318 $args['billingfrequency'] = $params['frequency_interval'];
319 $args['billingperiod'] = ucwords($params['frequency_unit']);
320 $args['desc'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
321 //$args['desc'] = 'Recurring Contribution';
322 $args['totalbillingcycles'] = $params['installments'];
323 $args['version'] = '56.0';
324 $args['profilereference'] = "i={$params['invoiceID']}" .
326 "&c={$params['contactID']}" .
327 "&r={$params['contributionRecurID']}" .
328 "&b={$params['contributionID']}" .
329 "&p={$params['contributionPageID']}";
331 // add CiviCRM BN code
332 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
334 $result = $this->invokeAPI($args);
336 if (is_a($result, 'CRM_Core_Error')) {
341 $params['trxn_id'] = $result['transactionid'];
342 $params['gross_amount'] = $result['amt'];
343 $params['fee_amount'] = $result['feeamt'];
344 $params['net_amount'] = $result['settleamt'];
345 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
346 $params['net_amount'] = $params['gross_amount'] - $params['fee_amount'];
348 $params['payment_status'] = $result['paymentstatus'];
349 $params['pending_reason'] = $result['pendingreason'];
358 public function initialize(&$args, $method) {
359 $args['user'] = $this->_paymentProcessor
['user_name'];
360 $args['pwd'] = $this->_paymentProcessor
['password'];
361 $args['version'] = 3.0;
362 $args['signature'] = $this->_paymentProcessor
['signature'];
363 $args['subject'] = CRM_Utils_Array
::value('subject', $this->_paymentProcessor
);
364 $args['method'] = $method;
368 * This function collects all the information from a web/api form and invokes
369 * the relevant payment processor specific functions to perform the transaction
371 * @param array $params
372 * Assoc array of input parameters for this transaction.
374 * @param string $component
376 * the result in an nice formatted array (or an error object)
378 public function doDirectPayment(&$params, $component = 'contribute') {
381 $this->initialize($args, 'DoDirectPayment');
383 $args['paymentAction'] = 'Sale';
384 $args['amt'] = $params['amount'];
385 $args['currencyCode'] = $params['currencyID'];
386 $args['invnum'] = $params['invoiceID'];
387 $args['ipaddress'] = $params['ip_address'];
388 $args['creditCardType'] = $params['credit_card_type'];
389 $args['acct'] = $params['credit_card_number'];
390 $args['expDate'] = sprintf('%02d', $params['month']) . $params['year'];
391 $args['cvv2'] = $params['cvv2'];
392 $args['firstName'] = $params['first_name'];
393 $args['lastName'] = $params['last_name'];
394 $args['email'] = CRM_Utils_Array
::value('email', $params);
395 $args['street'] = $params['street_address'];
396 $args['city'] = $params['city'];
397 $args['state'] = $params['state_province'];
398 $args['countryCode'] = $params['country'];
399 $args['zip'] = $params['postal_code'];
400 $args['desc'] = substr(CRM_Utils_Array
::value('description', $params), 0, 127);
401 $args['custom'] = CRM_Utils_Array
::value('accountingCode', $params);
403 // add CiviCRM BN code
404 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
406 if (CRM_Utils_Array
::value('is_recur', $params) == 1) {
407 $start_time = strtotime(date('m/d/Y'));
408 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
410 $args['PaymentAction'] = 'Sale';
411 $args['billingperiod'] = ucwords($params['frequency_unit']);
412 $args['billingfrequency'] = $params['frequency_interval'];
413 $args['method'] = "CreateRecurringPaymentsProfile";
414 $args['profilestartdate'] = $start_date;
416 $params['description'] . ": " .
417 $params['amount'] . " Per " .
418 $params['frequency_interval'] . " " .
419 $params['frequency_unit'];
420 $args['amt'] = $params['amount'];
421 $args['totalbillingcycles'] = $params['installments'];
422 $args['version'] = 56.0;
423 $args['PROFILEREFERENCE'] = "" .
424 "i=" . $params['invoiceID'] . "&m=" . $component .
425 "&c=" . $params['contactID'] . "&r=" . $params['contributionRecurID'] .
426 "&b=" . $params['contributionID'] . "&p=" . $params['contributionPageID'];
429 // Allow further manipulation of the arguments via custom hooks ..
430 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $args);
432 $result = $this->invokeAPI($args);
435 if (is_a($result, 'CRM_Core_Error')) {
439 $params['recurr_profile_id'] = NULL;
441 if (CRM_Utils_Array
::value('is_recur', $params) == 1) {
442 $params['recurr_profile_id'] = $result['profileid'];
447 $params['trxn_id'] = CRM_Utils_Array
::value('transactionid', $result);
448 $params['gross_amount'] = CRM_Utils_Array
::value('amt', $result);
453 * This function checks to see if we have the right config values.
456 * the error message if any
458 public function checkConfig() {
460 $paymentProcessorType = CRM_Core_PseudoConstant
::paymentProcessorType(FALSE, NULL, 'name');
462 if ($this->_paymentProcessor
['payment_processor_type_id'] != CRM_Utils_Array
::key('PayPal_Standard', $paymentProcessorType)) {
463 if (empty($this->_paymentProcessor
['signature'])) {
464 $error[] = ts('Signature is not set in the Administer » System Settings » Payment Processors.');
467 if (empty($this->_paymentProcessor
['password'])) {
468 $error[] = ts('Password is not set in the Administer » System Settings » Payment Processors.');
471 if (!$this->_paymentProcessor
['user_name']) {
472 $error[] = ts('User Name is not set in the Administer » System Settings » Payment Processors.');
475 if (!empty($error)) {
476 return implode('<p>', $error);
484 * @return null|string
486 public function cancelSubscriptionURL() {
487 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal_Standard') {
488 return "{$this->_paymentProcessor['url_site']}cgi-bin/webscr?cmd=_subscr-find&alias=" . urlencode($this->_paymentProcessor
['user_name']);
496 * Check whether a method is present ( & supported ) by the payment processor object.
498 * @param string $method
499 * Method to check for.
503 public function isSupported($method = 'cancelSubscription') {
504 if ($this->_paymentProcessor
['payment_processor_type'] != 'PayPal') {
505 // since subscription methods like cancelSubscription or updateBilling is not yet implemented / supported
506 // by standard or express.
509 return parent
::isSupported($method);
513 * Paypal express replaces the submit button with it's own.
516 * Should the form button by suppressed?
518 public function isSuppressSubmitButtons() {
519 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal_Express') {
526 * @param string $message
527 * @param array $params
529 * @return array|bool|object
531 public function cancelSubscription(&$message = '', $params = array()) {
532 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal') {
534 $this->initialize($args, 'ManageRecurringPaymentsProfileStatus');
536 $args['PROFILEID'] = CRM_Utils_Array
::value('subscriptionId', $params);
537 $args['ACTION'] = 'Cancel';
538 $args['NOTE'] = CRM_Utils_Array
::value('reason', $params);
540 $result = $this->invokeAPI($args);
541 if (is_a($result, 'CRM_Core_Error')) {
544 $message = "{$result['ack']}: profileid={$result['profileid']}";
551 * Process incoming notification.
553 * This is only supported for paypal pro at the moment & no specific plans to add this path to core
554 * for paypal standard as the goal must be to separate the 2.
556 * We don't need to handle paypal standard using this path as there has never been any historic support
557 * for paypal standard to call civicrm/payment/ipn as a path.
559 static public function handlePaymentNotification() {
560 $paypalIPN = new CRM_Core_Payment_PayPalProIPN($_REQUEST);
565 * @param string $message
566 * @param array $params
568 * @return array|bool|object
570 public function updateSubscriptionBillingInfo(&$message = '', $params = array()) {
571 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal') {
572 $config = CRM_Core_Config
::singleton();
574 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
576 $args['PROFILEID'] = $params['subscriptionId'];
577 $args['AMT'] = $params['amount'];
578 $args['CURRENCYCODE'] = $config->defaultCurrency
;
579 $args['CREDITCARDTYPE'] = $params['credit_card_type'];
580 $args['ACCT'] = $params['credit_card_number'];
581 $args['EXPDATE'] = sprintf('%02d', $params['month']) . $params['year'];
582 $args['CVV2'] = $params['cvv2'];
584 $args['FIRSTNAME'] = $params['first_name'];
585 $args['LASTNAME'] = $params['last_name'];
586 $args['STREET'] = $params['street_address'];
587 $args['CITY'] = $params['city'];
588 $args['STATE'] = $params['state_province'];
589 $args['COUNTRYCODE'] = $params['postal_code'];
590 $args['ZIP'] = $params['country'];
592 $result = $this->invokeAPI($args);
593 if (is_a($result, 'CRM_Core_Error')) {
596 $message = "{$result['ack']}: profileid={$result['profileid']}";
603 * @param string $message
604 * @param array $params
606 * @return array|bool|object
608 public function changeSubscriptionAmount(&$message = '', $params = array()) {
609 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal') {
610 $config = CRM_Core_Config
::singleton();
612 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
614 $args['PROFILEID'] = $params['subscriptionId'];
615 $args['AMT'] = $params['amount'];
616 $args['CURRENCYCODE'] = $config->defaultCurrency
;
617 $args['BILLINGFREQUENCY'] = $params['installments'];
619 $result = $this->invokeAPI($args);
620 CRM_Core_Error
::debug_var('$result', $result);
621 if (is_a($result, 'CRM_Core_Error')) {
624 $message = "{$result['ack']}: profileid={$result['profileid']}";
631 * Function to action pre-approval if supported
633 * @param array $params
634 * Parameters from the form
637 * - pre_approval_parameters (this will be stored on the calling form & available later)
638 * - redirect_url (if set the browser will be redirected to this.
640 public function doPreApproval(&$params) {
641 $token = $this->setExpressCheckOut($params);
643 'pre_approval_parameters' => array('token' => $token),
644 'redirect_url' => $this->_paymentProcessor
['url_site'] . "/cgi-bin/webscr?cmd=_express-checkout&token=$token",
649 * @param array $params
650 * @param string $component
654 public function doTransferCheckout(&$params, $component = 'contribute') {
655 $config = CRM_Core_Config
::singleton();
657 if ($component != 'contribute' && $component != 'event') {
658 CRM_Core_Error
::fatal(ts('Component is invalid'));
661 $notifyURL = $config->userFrameworkResourceURL
. "extern/ipn.php?reset=1&contactID={$params['contactID']}" . "&contributionID={$params['contributionID']}" . "&module={$component}";
663 if ($component == 'event') {
664 $notifyURL .= "&eventID={$params['eventID']}&participantID={$params['participantID']}";
667 $membershipID = CRM_Utils_Array
::value('membershipID', $params);
669 $notifyURL .= "&membershipID=$membershipID";
671 $relatedContactID = CRM_Utils_Array
::value('related_contact', $params);
672 if ($relatedContactID) {
673 $notifyURL .= "&relatedContactID=$relatedContactID";
675 $onBehalfDupeAlert = CRM_Utils_Array
::value('onbehalf_dupe_alert', $params);
676 if ($onBehalfDupeAlert) {
677 $notifyURL .= "&onBehalfDupeAlert=$onBehalfDupeAlert";
682 $url = ($component == 'event') ?
'civicrm/event/register' : 'civicrm/contribute/transact';
683 $cancel = ($component == 'event') ?
'_qf_Register_display' : '_qf_Main_display';
684 $returnURL = CRM_Utils_System
::url($url,
685 "_qf_ThankYou_display=1&qfKey={$params['qfKey']}",
689 $cancelUrlString = "$cancel=1&cancel=1&qfKey={$params['qfKey']}";
690 if (!empty($params['is_recur'])) {
691 $cancelUrlString .= "&isRecur=1&recurId={$params['contributionRecurID']}&contribId={$params['contributionID']}";
694 $cancelURL = CRM_Utils_System
::url(
700 // ensure that the returnURL is absolute.
701 if (substr($returnURL, 0, 4) != 'http') {
702 $fixUrl = CRM_Utils_System
::url("civicrm/admin/setting/url", '&reset=1');
703 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)));
706 $paypalParams = array(
707 'business' => $this->_paymentProcessor
['user_name'],
708 'notify_url' => $notifyURL,
709 'item_name' => $params['item_name'],
711 'undefined_quantity' => 0,
712 'cancel_return' => $cancelURL,
715 'return' => $returnURL,
717 'currency_code' => $params['currencyID'],
718 'invoice' => $params['invoiceID'],
719 'lc' => substr($config->lcMessages
, -2),
720 'charset' => function_exists('mb_internal_encoding') ?
mb_internal_encoding() : 'UTF-8',
721 'custom' => CRM_Utils_Array
::value('accountingCode', $params),
722 'bn' => 'CiviCRM_SP',
725 // add name and address if available, CRM-3130
727 'first_name' => 'first_name',
728 'last_name' => 'last_name',
729 'street_address' => 'address1',
730 'country' => 'country',
731 'preferred_language' => 'lc',
733 'state_province' => 'state',
734 'postal_code' => 'zip',
738 foreach (array_keys($params) as $p) {
739 // get the base name without the location type suffixed to it
740 $parts = explode('-', $p);
741 $name = count($parts) > 1 ?
$parts[0] : $p;
742 if (isset($otherVars[$name])) {
743 $value = $params[$p];
745 if ($name == 'state_province') {
746 $stateName = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($value);
749 if ($name == 'country') {
750 $countryName = CRM_Core_PseudoConstant
::countryIsoCode($value);
751 $value = $countryName;
753 // ensure value is not an array
755 if (!is_array($value)) {
756 $paypalParams[$otherVars[$name]] = $value;
762 // if recurring donations, add a few more items
763 if (!empty($params['is_recur'])) {
764 if ($params['contributionRecurID']) {
765 $notifyURL .= "&contributionRecurID={$params['contributionRecurID']}&contributionPageID={$params['contributionPageID']}";
766 $paypalParams['notify_url'] = $notifyURL;
769 CRM_Core_Error
::fatal(ts('Recurring contribution, but no database id'));
772 $paypalParams +
= array(
773 'cmd' => '_xclick-subscriptions',
774 'a3' => $params['amount'],
775 'p3' => $params['frequency_interval'],
776 't3' => ucfirst(substr($params['frequency_unit'], 0, 1)),
779 'srt' => CRM_Utils_Array
::value('installments', $params),
785 $paypalParams +
= array(
787 'amount' => $params['amount'],
791 // Allow further manipulation of the arguments via custom hooks ..
792 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $paypalParams);
795 foreach ($paypalParams as $key => $value) {
796 if ($value === NULL) {
800 $value = urlencode($value);
801 if ($key == 'return' ||
802 $key == 'cancel_return' ||
805 $value = str_replace('%2F', '/', $value);
807 $uri .= "&{$key}={$value}";
810 $uri = substr($uri, 1);
811 $url = $this->_paymentProcessor
['url_site'];
812 $sub = empty($params['is_recur']) ?
'cgi-bin/webscr' : 'subscriptions';
813 $paypalURL = "{$url}{$sub}?$uri";
815 CRM_Utils_System
::redirect($paypalURL);
819 * Hash_call: Function to perform the API call to PayPal using API signature
820 * @methodName is name of API method.
821 * @nvpStr is nvp string.
822 * returns an associtive array containing the response from the server.
824 public function invokeAPI($args, $url = NULL) {
827 if (empty($this->_paymentProcessor
['url_api'])) {
828 CRM_Core_Error
::fatal(ts('Please set the API URL. Please refer to the documentation for more details'));
831 $url = $this->_paymentProcessor
['url_api'] . 'nvp';
834 if (!function_exists('curl_init')) {
835 CRM_Core_Error
::fatal("curl functions NOT available.");
838 //setting the curl parameters.
840 curl_setopt($ch, CURLOPT_URL
, $url);
841 curl_setopt($ch, CURLOPT_VERBOSE
, 1);
843 //turning off the server and peer verification(TrustManager Concept).
844 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'verifySSL'));
845 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST
, CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'verifySSL') ?
2 : 0);
847 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, 1);
848 curl_setopt($ch, CURLOPT_POST
, 1);
851 foreach ($args as $n => $v) {
852 $p[] = "$n=" . urlencode($v);
855 //NVPRequest for submitting to server
856 $nvpreq = implode('&', $p);
858 //setting the nvpreq as POST FIELD to curl
859 curl_setopt($ch, CURLOPT_POSTFIELDS
, $nvpreq);
861 //getting response from server
862 $response = curl_exec($ch);
864 //converting NVPResponse to an Associative Array
865 $result = self
::deformat($response);
867 if (curl_errno($ch)) {
868 $e = CRM_Core_Error
::singleton();
869 $e->push(curl_errno($ch),
879 if (strtolower($result['ack']) != 'success' &&
880 strtolower($result['ack']) != 'successwithwarning'
882 $e = CRM_Core_Error
::singleton();
883 $e->push($result['l_errorcode0'],
885 "{$result['l_shortmessage0']} {$result['l_longmessage0']}"
894 * This function will take NVPString and convert it to an Associative Array and it will decode the response.
895 * It is useful to search for a particular key and displaying arrays.
896 * @nvpstr is NVPString.
897 * @nvpArray is Associative Array.
899 public static function deformat($str) {
902 while (strlen($str)) {
904 $keyPos = strpos($str, '=');
907 $valPos = strpos($str, '&') ?
strpos($str, '&') : strlen($str);
909 /*getting the Key and Value values and storing in a Associative Array*/
911 $key = substr($str, 0, $keyPos);
912 $val = substr($str, $keyPos +
1, $valPos - $keyPos - 1);
914 //decoding the respose
915 $result[strtolower(urldecode($key))] = urldecode($val);
916 $str = substr($str, $valPos +
1, strlen($str));
923 * Map the paypal params to CiviCRM params using a field map.
925 * @param array $fieldMap
926 * @param array $paypalParams
930 protected function mapPaypalParamsToCivicrmParams($fieldMap, $paypalParams) {
932 foreach ($fieldMap as $civicrmField => $paypalField) {
933 $params[$civicrmField] = isset($paypalParams[$paypalField]) ?
$paypalParams[$paypalField] : NULL;