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 $params['token'] = $result['token'];
228 $params['payer_id'] = $result['payerid'];
229 $params['payer_status'] = $result['payerstatus'];
230 $params['first_name'] = $result['firstname'];
231 $params['middle_name'] = CRM_Utils_Array
::value('middlename', $result);
232 $params['last_name'] = $result['lastname'];
233 $params['street_address'] = $result['shiptostreet'];
234 $params['supplemental_address_1'] = CRM_Utils_Array
::value('shiptostreet2', $result);
235 $params['city'] = $result['shiptocity'];
236 $params['state_province'] = $result['shiptostate'];
237 $params['postal_code'] = $result['shiptozip'];
238 $params['country'] = $result['shiptocountrycode'];
244 * Do the express checkout at paypal. Check PayPal documentation for more information
246 * @param array $params
248 * @internal param string $token the key associated with this transaction
251 * the result in an nice formatted array (or an error object)
253 public function doExpressCheckout(&$params) {
255 if (!empty($params['is_recur'])) {
256 return $this->createRecurringPayments($params);
260 $this->initialize($args, 'DoExpressCheckoutPayment');
261 $args['token'] = $params['token'];
262 $args['paymentAction'] = 'Sale';
263 $args['amt'] = $params['amount'];
264 $args['currencyCode'] = $params['currencyID'];
265 $args['payerID'] = $params['payer_id'];
266 $args['invnum'] = $params['invoiceID'];
267 $args['returnURL'] = $this->getReturnSuccessUrl($params['qfKey']);
268 $args['cancelURL'] = $this->getCancelUrl($params['qfKey'], NULL);
269 $args['desc'] = $params['description'];
271 // add CiviCRM BN code
272 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
274 $result = $this->invokeAPI($args);
276 if (is_a($result, 'CRM_Core_Error')) {
282 $params['trxn_id'] = $result['transactionid'];
283 $params['gross_amount'] = $result['amt'];
284 $params['fee_amount'] = $result['feeamt'];
285 $params['net_amount'] = CRM_Utils_Array
::value('settleamt', $result);
286 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
287 $params['net_amount'] = $params['gross_amount'] - $params['fee_amount'];
289 $params['payment_status'] = $result['paymentstatus'];
290 $params['pending_reason'] = $result['pendingreason'];
295 //LCD add new function for handling recurring payments for PayPal Express
297 * @param array $params
301 public function createRecurringPayments(&$params) {
304 $this->initialize($args, 'CreateRecurringPaymentsProfile');
306 $start_time = strtotime(date('m/d/Y'));
307 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
309 $args['token'] = $params['token'];
310 $args['paymentAction'] = 'Sale';
311 $args['amt'] = $params['amount'];
312 $args['currencyCode'] = $params['currencyID'];
313 $args['payerID'] = $params['payer_id'];
314 $args['invnum'] = $params['invoiceID'];
315 $args['returnURL'] = $params['returnURL'];
316 $args['cancelURL'] = $params['cancelURL'];
317 $args['profilestartdate'] = $start_date;
318 $args['method'] = 'CreateRecurringPaymentsProfile';
319 $args['billingfrequency'] = $params['frequency_interval'];
320 $args['billingperiod'] = ucwords($params['frequency_unit']);
321 $args['desc'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
322 //$args['desc'] = 'Recurring Contribution';
323 $args['totalbillingcycles'] = $params['installments'];
324 $args['version'] = '56.0';
325 $args['profilereference'] = "i={$params['invoiceID']}" .
327 "&c={$params['contactID']}" .
328 "&r={$params['contributionRecurID']}" .
329 "&b={$params['contributionID']}" .
330 "&p={$params['contributionPageID']}";
332 // add CiviCRM BN code
333 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
335 $result = $this->invokeAPI($args);
337 if (is_a($result, 'CRM_Core_Error')) {
342 $params['trxn_id'] = $result['transactionid'];
343 $params['gross_amount'] = $result['amt'];
344 $params['fee_amount'] = $result['feeamt'];
345 $params['net_amount'] = $result['settleamt'];
346 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
347 $params['net_amount'] = $params['gross_amount'] - $params['fee_amount'];
349 $params['payment_status'] = $result['paymentstatus'];
350 $params['pending_reason'] = $result['pendingreason'];
359 public function initialize(&$args, $method) {
360 $args['user'] = $this->_paymentProcessor
['user_name'];
361 $args['pwd'] = $this->_paymentProcessor
['password'];
362 $args['version'] = 3.0;
363 $args['signature'] = $this->_paymentProcessor
['signature'];
364 $args['subject'] = CRM_Utils_Array
::value('subject', $this->_paymentProcessor
);
365 $args['method'] = $method;
369 * This function collects all the information from a web/api form and invokes
370 * the relevant payment processor specific functions to perform the transaction
372 * @param array $params
373 * Assoc array of input parameters for this transaction.
375 * @param string $component
377 * the result in an nice formatted array (or an error object)
379 public function doDirectPayment(&$params, $component = 'contribute') {
382 $this->initialize($args, 'DoDirectPayment');
384 $args['paymentAction'] = 'Sale';
385 $args['amt'] = $params['amount'];
386 $args['currencyCode'] = $params['currencyID'];
387 $args['invnum'] = $params['invoiceID'];
388 $args['ipaddress'] = $params['ip_address'];
389 $args['creditCardType'] = $params['credit_card_type'];
390 $args['acct'] = $params['credit_card_number'];
391 $args['expDate'] = sprintf('%02d', $params['month']) . $params['year'];
392 $args['cvv2'] = $params['cvv2'];
393 $args['firstName'] = $params['first_name'];
394 $args['lastName'] = $params['last_name'];
395 $args['email'] = CRM_Utils_Array
::value('email', $params);
396 $args['street'] = $params['street_address'];
397 $args['city'] = $params['city'];
398 $args['state'] = $params['state_province'];
399 $args['countryCode'] = $params['country'];
400 $args['zip'] = $params['postal_code'];
401 $args['desc'] = substr(CRM_Utils_Array
::value('description', $params), 0, 127);
402 $args['custom'] = CRM_Utils_Array
::value('accountingCode', $params);
404 // add CiviCRM BN code
405 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
407 if (CRM_Utils_Array
::value('is_recur', $params) == 1) {
408 $start_time = strtotime(date('m/d/Y'));
409 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
411 $args['PaymentAction'] = 'Sale';
412 $args['billingperiod'] = ucwords($params['frequency_unit']);
413 $args['billingfrequency'] = $params['frequency_interval'];
414 $args['method'] = "CreateRecurringPaymentsProfile";
415 $args['profilestartdate'] = $start_date;
417 $params['description'] . ": " .
418 $params['amount'] . " Per " .
419 $params['frequency_interval'] . " " .
420 $params['frequency_unit'];
421 $args['amt'] = $params['amount'];
422 $args['totalbillingcycles'] = $params['installments'];
423 $args['version'] = 56.0;
424 $args['PROFILEREFERENCE'] = "" .
425 "i=" . $params['invoiceID'] . "&m=" . $component .
426 "&c=" . $params['contactID'] . "&r=" . $params['contributionRecurID'] .
427 "&b=" . $params['contributionID'] . "&p=" . $params['contributionPageID'];
430 // Allow further manipulation of the arguments via custom hooks ..
431 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $args);
433 $result = $this->invokeAPI($args);
436 if (is_a($result, 'CRM_Core_Error')) {
440 $params['recurr_profile_id'] = NULL;
442 if (CRM_Utils_Array
::value('is_recur', $params) == 1) {
443 $params['recurr_profile_id'] = $result['profileid'];
448 $params['trxn_id'] = CRM_Utils_Array
::value('transactionid', $result);
449 $params['gross_amount'] = CRM_Utils_Array
::value('amt', $result);
454 * This function checks to see if we have the right config values.
457 * the error message if any
459 public function checkConfig() {
461 $paymentProcessorType = CRM_Core_PseudoConstant
::paymentProcessorType(FALSE, NULL, 'name');
463 if ($this->_paymentProcessor
['payment_processor_type_id'] != CRM_Utils_Array
::key('PayPal_Standard', $paymentProcessorType)) {
464 if (empty($this->_paymentProcessor
['signature'])) {
465 $error[] = ts('Signature is not set in the Administer » System Settings » Payment Processors.');
468 if (empty($this->_paymentProcessor
['password'])) {
469 $error[] = ts('Password is not set in the Administer » System Settings » Payment Processors.');
472 if (!$this->_paymentProcessor
['user_name']) {
473 $error[] = ts('User Name is not set in the Administer » System Settings » Payment Processors.');
476 if (!empty($error)) {
477 return implode('<p>', $error);
485 * @return null|string
487 public function cancelSubscriptionURL() {
488 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal_Standard') {
489 return "{$this->_paymentProcessor['url_site']}cgi-bin/webscr?cmd=_subscr-find&alias=" . urlencode($this->_paymentProcessor
['user_name']);
497 * Check whether a method is present ( & supported ) by the payment processor object.
499 * @param string $method
500 * Method to check for.
504 public function isSupported($method = 'cancelSubscription') {
505 if ($this->_paymentProcessor
['payment_processor_type'] != 'PayPal') {
506 // since subscription methods like cancelSubscription or updateBilling is not yet implemented / supported
507 // by standard or express.
510 return parent
::isSupported($method);
514 * Paypal express replaces the submit button with it's own.
517 * Should the form button by suppressed?
519 public function isSuppressSubmitButtons() {
520 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal_Express') {
527 * @param string $message
528 * @param array $params
530 * @return array|bool|object
532 public function cancelSubscription(&$message = '', $params = array()) {
533 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal') {
535 $this->initialize($args, 'ManageRecurringPaymentsProfileStatus');
537 $args['PROFILEID'] = CRM_Utils_Array
::value('subscriptionId', $params);
538 $args['ACTION'] = 'Cancel';
539 $args['NOTE'] = CRM_Utils_Array
::value('reason', $params);
541 $result = $this->invokeAPI($args);
542 if (is_a($result, 'CRM_Core_Error')) {
545 $message = "{$result['ack']}: profileid={$result['profileid']}";
552 * Process incoming notification.
554 * This is only supported for paypal pro at the moment & no specific plans to add this path to core
555 * for paypal standard as the goal must be to separate the 2.
557 * We don't need to handle paypal standard using this path as there has never been any historic support
558 * for paypal standard to call civicrm/payment/ipn as a path.
560 static public function handlePaymentNotification() {
561 $paypalIPN = new CRM_Core_Payment_PayPalProIPN($_REQUEST);
566 * @param string $message
567 * @param array $params
569 * @return array|bool|object
571 public function updateSubscriptionBillingInfo(&$message = '', $params = array()) {
572 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal') {
573 $config = CRM_Core_Config
::singleton();
575 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
577 $args['PROFILEID'] = $params['subscriptionId'];
578 $args['AMT'] = $params['amount'];
579 $args['CURRENCYCODE'] = $config->defaultCurrency
;
580 $args['CREDITCARDTYPE'] = $params['credit_card_type'];
581 $args['ACCT'] = $params['credit_card_number'];
582 $args['EXPDATE'] = sprintf('%02d', $params['month']) . $params['year'];
583 $args['CVV2'] = $params['cvv2'];
585 $args['FIRSTNAME'] = $params['first_name'];
586 $args['LASTNAME'] = $params['last_name'];
587 $args['STREET'] = $params['street_address'];
588 $args['CITY'] = $params['city'];
589 $args['STATE'] = $params['state_province'];
590 $args['COUNTRYCODE'] = $params['postal_code'];
591 $args['ZIP'] = $params['country'];
593 $result = $this->invokeAPI($args);
594 if (is_a($result, 'CRM_Core_Error')) {
597 $message = "{$result['ack']}: profileid={$result['profileid']}";
604 * @param string $message
605 * @param array $params
607 * @return array|bool|object
609 public function changeSubscriptionAmount(&$message = '', $params = array()) {
610 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal') {
611 $config = CRM_Core_Config
::singleton();
613 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
615 $args['PROFILEID'] = $params['subscriptionId'];
616 $args['AMT'] = $params['amount'];
617 $args['CURRENCYCODE'] = $config->defaultCurrency
;
618 $args['BILLINGFREQUENCY'] = $params['installments'];
620 $result = $this->invokeAPI($args);
621 CRM_Core_Error
::debug_var('$result', $result);
622 if (is_a($result, 'CRM_Core_Error')) {
625 $message = "{$result['ack']}: profileid={$result['profileid']}";
632 * Function to action pre-approval if supported
634 * @param array $params
635 * Parameters from the form
638 * - pre_approval_parameters (this will be stored on the calling form & available later)
639 * - redirect_url (if set the browser will be redirected to this.
641 public function doPreApproval(&$params) {
642 $token = $this->setExpressCheckOut($params);
644 'pre_approval_parameters' => array('token' => $token),
645 'redirect_url' => $this->_paymentProcessor
['url_site'] . "/cgi-bin/webscr?cmd=_express-checkout&token=$token",
650 * @param array $params
651 * @param string $component
655 public function doTransferCheckout(&$params, $component = 'contribute') {
656 $config = CRM_Core_Config
::singleton();
658 if ($component != 'contribute' && $component != 'event') {
659 CRM_Core_Error
::fatal(ts('Component is invalid'));
662 $notifyURL = $config->userFrameworkResourceURL
. "extern/ipn.php?reset=1&contactID={$params['contactID']}" . "&contributionID={$params['contributionID']}" . "&module={$component}";
664 if ($component == 'event') {
665 $notifyURL .= "&eventID={$params['eventID']}&participantID={$params['participantID']}";
668 $membershipID = CRM_Utils_Array
::value('membershipID', $params);
670 $notifyURL .= "&membershipID=$membershipID";
672 $relatedContactID = CRM_Utils_Array
::value('related_contact', $params);
673 if ($relatedContactID) {
674 $notifyURL .= "&relatedContactID=$relatedContactID";
676 $onBehalfDupeAlert = CRM_Utils_Array
::value('onbehalf_dupe_alert', $params);
677 if ($onBehalfDupeAlert) {
678 $notifyURL .= "&onBehalfDupeAlert=$onBehalfDupeAlert";
683 $url = ($component == 'event') ?
'civicrm/event/register' : 'civicrm/contribute/transact';
684 $cancel = ($component == 'event') ?
'_qf_Register_display' : '_qf_Main_display';
685 $returnURL = CRM_Utils_System
::url($url,
686 "_qf_ThankYou_display=1&qfKey={$params['qfKey']}",
690 $cancelUrlString = "$cancel=1&cancel=1&qfKey={$params['qfKey']}";
691 if (!empty($params['is_recur'])) {
692 $cancelUrlString .= "&isRecur=1&recurId={$params['contributionRecurID']}&contribId={$params['contributionID']}";
695 $cancelURL = CRM_Utils_System
::url(
701 // ensure that the returnURL is absolute.
702 if (substr($returnURL, 0, 4) != 'http') {
703 $fixUrl = CRM_Utils_System
::url("civicrm/admin/setting/url", '&reset=1');
704 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)));
707 $paypalParams = array(
708 'business' => $this->_paymentProcessor
['user_name'],
709 'notify_url' => $notifyURL,
710 'item_name' => $params['item_name'],
712 'undefined_quantity' => 0,
713 'cancel_return' => $cancelURL,
716 'return' => $returnURL,
718 'currency_code' => $params['currencyID'],
719 'invoice' => $params['invoiceID'],
720 'lc' => substr($config->lcMessages
, -2),
721 'charset' => function_exists('mb_internal_encoding') ?
mb_internal_encoding() : 'UTF-8',
722 'custom' => CRM_Utils_Array
::value('accountingCode', $params),
723 'bn' => 'CiviCRM_SP',
726 // add name and address if available, CRM-3130
728 'first_name' => 'first_name',
729 'last_name' => 'last_name',
730 'street_address' => 'address1',
731 'country' => 'country',
732 'preferred_language' => 'lc',
734 'state_province' => 'state',
735 'postal_code' => 'zip',
739 foreach (array_keys($params) as $p) {
740 // get the base name without the location type suffixed to it
741 $parts = explode('-', $p);
742 $name = count($parts) > 1 ?
$parts[0] : $p;
743 if (isset($otherVars[$name])) {
744 $value = $params[$p];
746 if ($name == 'state_province') {
747 $stateName = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($value);
750 if ($name == 'country') {
751 $countryName = CRM_Core_PseudoConstant
::countryIsoCode($value);
752 $value = $countryName;
754 // ensure value is not an array
756 if (!is_array($value)) {
757 $paypalParams[$otherVars[$name]] = $value;
763 // if recurring donations, add a few more items
764 if (!empty($params['is_recur'])) {
765 if ($params['contributionRecurID']) {
766 $notifyURL .= "&contributionRecurID={$params['contributionRecurID']}&contributionPageID={$params['contributionPageID']}";
767 $paypalParams['notify_url'] = $notifyURL;
770 CRM_Core_Error
::fatal(ts('Recurring contribution, but no database id'));
773 $paypalParams +
= array(
774 'cmd' => '_xclick-subscriptions',
775 'a3' => $params['amount'],
776 'p3' => $params['frequency_interval'],
777 't3' => ucfirst(substr($params['frequency_unit'], 0, 1)),
780 'srt' => CRM_Utils_Array
::value('installments', $params),
786 $paypalParams +
= array(
788 'amount' => $params['amount'],
792 // Allow further manipulation of the arguments via custom hooks ..
793 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $paypalParams);
796 foreach ($paypalParams as $key => $value) {
797 if ($value === NULL) {
801 $value = urlencode($value);
802 if ($key == 'return' ||
803 $key == 'cancel_return' ||
806 $value = str_replace('%2F', '/', $value);
808 $uri .= "&{$key}={$value}";
811 $uri = substr($uri, 1);
812 $url = $this->_paymentProcessor
['url_site'];
813 $sub = empty($params['is_recur']) ?
'cgi-bin/webscr' : 'subscriptions';
814 $paypalURL = "{$url}{$sub}?$uri";
816 CRM_Utils_System
::redirect($paypalURL);
820 * Hash_call: Function to perform the API call to PayPal using API signature
821 * @methodName is name of API method.
822 * @nvpStr is nvp string.
823 * returns an associtive array containing the response from the server.
825 public function invokeAPI($args, $url = NULL) {
828 if (empty($this->_paymentProcessor
['url_api'])) {
829 CRM_Core_Error
::fatal(ts('Please set the API URL. Please refer to the documentation for more details'));
832 $url = $this->_paymentProcessor
['url_api'] . 'nvp';
835 if (!function_exists('curl_init')) {
836 CRM_Core_Error
::fatal("curl functions NOT available.");
839 //setting the curl parameters.
841 curl_setopt($ch, CURLOPT_URL
, $url);
842 curl_setopt($ch, CURLOPT_VERBOSE
, 1);
844 //turning off the server and peer verification(TrustManager Concept).
845 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'verifySSL'));
846 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST
, CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'verifySSL') ?
2 : 0);
848 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, 1);
849 curl_setopt($ch, CURLOPT_POST
, 1);
852 foreach ($args as $n => $v) {
853 $p[] = "$n=" . urlencode($v);
856 //NVPRequest for submitting to server
857 $nvpreq = implode('&', $p);
859 //setting the nvpreq as POST FIELD to curl
860 curl_setopt($ch, CURLOPT_POSTFIELDS
, $nvpreq);
862 //getting response from server
863 $response = curl_exec($ch);
865 //converting NVPResponse to an Associative Array
866 $result = self
::deformat($response);
868 if (curl_errno($ch)) {
869 $e = CRM_Core_Error
::singleton();
870 $e->push(curl_errno($ch),
880 if (strtolower($result['ack']) != 'success' &&
881 strtolower($result['ack']) != 'successwithwarning'
883 $e = CRM_Core_Error
::singleton();
884 $e->push($result['l_errorcode0'],
886 "{$result['l_shortmessage0']} {$result['l_longmessage0']}"
895 * This function will take NVPString and convert it to an Associative Array and it will decode the response.
896 * It is useful to search for a particular key and displaying arrays.
897 * @nvpstr is NVPString.
898 * @nvpArray is Associative Array.
900 public static function deformat($str) {
903 while (strlen($str)) {
905 $keyPos = strpos($str, '=');
908 $valPos = strpos($str, '&') ?
strpos($str, '&') : strlen($str);
910 /*getting the Key and Value values and storing in a Associative Array*/
912 $key = substr($str, 0, $keyPos);
913 $val = substr($str, $keyPos +
1, $valPos - $keyPos - 1);
915 //decoding the respose
916 $result[strtolower(urldecode($key))] = urldecode($val);
917 $str = substr($str, $valPos +
1, strlen($str));