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
extends CRM_Core_Payment
{
36 const CHARSET
= 'iso-8859-1';
38 protected $_mode = NULL;
41 * We only need one instance of this object. So we use the singleton
42 * pattern and cache the instance in this variable
46 static private $_singleton = NULL;
52 * The mode of operation: live or test.
54 * @param $paymentProcessor
56 * @return \CRM_Core_Payment_PayPalImpl
58 public function __construct($mode, &$paymentProcessor) {
60 $this->_paymentProcessor
= $paymentProcessor;
61 $this->_processorName
= ts('PayPal Pro');
62 $paymentProcessorType = CRM_Core_PseudoConstant
::paymentProcessorType(FALSE, NULL, 'name');
64 if ($this->_paymentProcessor
['payment_processor_type_id'] == CRM_Utils_Array
::key('PayPal_Standard', $paymentProcessorType)) {
65 $this->_processorName
= ts('PayPal Standard');
68 elseif ($this->_paymentProcessor
['payment_processor_type_id'] == CRM_Utils_Array
::key('PayPal_Express', $paymentProcessorType)) {
69 $this->_processorName
= ts('PayPal Express');
75 * Are back office payments supported - e.g paypal standard won't permit you to enter a credit card associated with someone else's login
78 protected function supportsBackOffice() {
79 if ($this->_processorName
== ts('PayPal Pro')) {
86 * Does this processor support pre-approval.
88 * This would generally look like a redirect to enter credentials which can then be used in a later payment call.
90 * Currently Paypal express supports this, with a redirect to paypal after the 'Main' form is submitted in the
91 * contribution page. This token can then be processed at the confirm phase. Although this flow 'looks' like the
92 * 'notify' flow a key difference is that in the notify flow they don't have to return but in this flow they do.
96 protected function supportsPreApproval() {
97 if ($this->_processorName
== ts('PayPal_Express')) {
104 * Opportunity for the payment processor to override the entire form build.
106 * @param CRM_Core_Form $form
109 * Should form building stop at this point?
111 public function buildForm(&$form) {
112 if ($this->_processorName
== 'PayPal Express' ||
$this->_processorName
== 'PayPal Pro') {
113 $this->addPaypalExpressCode($form);
114 if ($this->_processorName
== 'PayPal Express') {
115 CRM_Core_Region
::instance('billing-block-post')->add(array(
116 'template' => 'CRM/Financial/Form/PaypalExpress.tpl',
117 'name' => 'paypal_express',
120 if ($this->_processorName
== 'PayPal Pro') {
121 CRM_Core_Region
::instance('billing-block-pre')->add(array(
122 'template' => 'CRM/Financial/Form/PaypalPro.tpl',
130 * Billing mode button is basically synonymous with paypal express - this is probably a good example of 'odds & sods' code we
131 * 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
135 protected function addPaypalExpressCode(&$form) {
136 if (empty($form->isBackOffice
)) {
137 $form->_expressButtonName
= $form->getButtonName('upload', 'express');
138 $form->assign('expressButtonName', $form->_expressButtonName
);
141 $form->_expressButtonName
,
142 $this->_paymentProcessor
['url_button'],
143 array('class' => 'crm-form-submit')
149 * Express checkout code. Check PayPal documentation for more information
151 * @param array $params
152 * Assoc array of input parameters for this transaction.
155 * the result in an nice formatted array (or an error object)
157 protected function setExpressCheckOut(&$params) {
160 $this->initialize($args, 'SetExpressCheckout');
162 $args['paymentAction'] = 'Sale';
163 $args['amt'] = $params['amount'];
164 $args['currencyCode'] = $params['currencyID'];
165 $args['desc'] = CRM_Utils_Array
::value('description', $params);
166 $args['invnum'] = $params['invoiceID'];
167 $args['returnURL'] = $this->getReturnSuccessUrl($params['qfKey']);
168 $args['cancelURL'] = $this->getCancelUrl($params['qfKey'], NULL);
169 $args['version'] = '56.0';
171 //LCD if recurring, collect additional data and set some values
172 if (!empty($params['is_recur'])) {
173 $args['L_BILLINGTYPE0'] = 'RecurringPayments';
174 //$args['L_BILLINGAGREEMENTDESCRIPTION0'] = 'Recurring Contribution';
175 $args['L_BILLINGAGREEMENTDESCRIPTION0'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
176 $args['L_PAYMENTTYPE0'] = 'Any';
179 // Allow further manipulation of the arguments via custom hooks ..
180 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $args);
182 $result = $this->invokeAPI($args);
184 if (is_a($result, 'CRM_Core_Error')) {
190 return $result['token'];
194 * Get any details that may be available to the payment processor due to an approval process having happened.
196 * In some cases the browser is redirected to enter details on a processor site. Some details may be available as a
199 * @param array $storedDetails
203 public function getPreApprovalDetails($storedDetails) {
204 return $this->getExpressCheckoutDetails($storedDetails['token']);
208 * Get details from paypal. Check PayPal documentation for more information
210 * @param string $token
211 * The key associated with this transaction.
214 * the result in an nice formatted array (or an error object)
216 public function getExpressCheckoutDetails($token) {
219 $this->initialize($args, 'GetExpressCheckoutDetails');
220 $args['token'] = $token;
222 $args['method'] = 'GetExpressCheckoutDetails';
224 $result = $this->invokeAPI($args);
226 if (is_a($result, 'CRM_Core_Error')) {
233 $params['token'] = $result['token'];
234 $params['payer_id'] = $result['payerid'];
235 $params['payer_status'] = $result['payerstatus'];
236 $params['first_name'] = $result['firstname'];
237 $params['middle_name'] = CRM_Utils_Array
::value('middlename', $result);
238 $params['last_name'] = $result['lastname'];
239 $params['street_address'] = $result['shiptostreet'];
240 $params['supplemental_address_1'] = CRM_Utils_Array
::value('shiptostreet2', $result);
241 $params['city'] = $result['shiptocity'];
242 $params['state_province'] = $result['shiptostate'];
243 $params['postal_code'] = $result['shiptozip'];
244 $params['country'] = $result['shiptocountrycode'];
250 * Do the express checkout at paypal. Check PayPal documentation for more information
252 * @param array $params
254 * @internal param string $token the key associated with this transaction
257 * the result in an nice formatted array (or an error object)
259 public function doExpressCheckout(&$params) {
262 $this->initialize($args, 'DoExpressCheckoutPayment');
263 $args['token'] = $params['token'];
264 $args['paymentAction'] = 'Sale';
265 $args['amt'] = $params['amount'];
266 $args['currencyCode'] = $params['currencyID'];
267 $args['payerID'] = $params['payer_id'];
268 $args['invnum'] = $params['invoiceID'];
269 $args['returnURL'] = $this->getReturnSuccessUrl($params['qfKey']);
270 $args['cancelURL'] = $this->getCancelUrl($params['qfKey'], NULL);
271 $args['desc'] = $params['description'];
273 // add CiviCRM BN code
274 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
276 $result = $this->invokeAPI($args);
278 if (is_a($result, 'CRM_Core_Error')) {
284 $params['trxn_id'] = $result['transactionid'];
285 $params['gross_amount'] = $result['amt'];
286 $params['fee_amount'] = $result['feeamt'];
287 $params['net_amount'] = CRM_Utils_Array
::value('settleamt', $result);
288 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
289 $params['net_amount'] = $params['gross_amount'] - $params['fee_amount'];
291 $params['payment_status'] = $result['paymentstatus'];
292 $params['pending_reason'] = $result['pendingreason'];
297 //LCD add new function for handling recurring payments for PayPal Express
299 * @param array $params
303 public function createRecurringPayments(&$params) {
306 $this->initialize($args, 'CreateRecurringPaymentsProfile');
308 $start_time = strtotime(date('m/d/Y'));
309 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
311 $args['token'] = $params['token'];
312 $args['paymentAction'] = 'Sale';
313 $args['amt'] = $params['amount'];
314 $args['currencyCode'] = $params['currencyID'];
315 $args['payerID'] = $params['payer_id'];
316 $args['invnum'] = $params['invoiceID'];
317 $args['returnURL'] = $params['returnURL'];
318 $args['cancelURL'] = $params['cancelURL'];
319 $args['profilestartdate'] = $start_date;
320 $args['method'] = 'CreateRecurringPaymentsProfile';
321 $args['billingfrequency'] = $params['frequency_interval'];
322 $args['billingperiod'] = ucwords($params['frequency_unit']);
323 $args['desc'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
324 //$args['desc'] = 'Recurring Contribution';
325 $args['totalbillingcycles'] = $params['installments'];
326 $args['version'] = '56.0';
327 $args['profilereference'] = "i={$params['invoiceID']}" .
329 "&c={$params['contactID']}" .
330 "&r={$params['contributionRecurID']}" .
331 "&b={$params['contributionID']}" .
332 "&p={$params['contributionPageID']}";
334 // add CiviCRM BN code
335 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
337 $result = $this->invokeAPI($args);
339 if (is_a($result, 'CRM_Core_Error')) {
344 $params['trxn_id'] = $result['transactionid'];
345 $params['gross_amount'] = $result['amt'];
346 $params['fee_amount'] = $result['feeamt'];
347 $params['net_amount'] = $result['settleamt'];
348 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
349 $params['net_amount'] = $params['gross_amount'] - $params['fee_amount'];
351 $params['payment_status'] = $result['paymentstatus'];
352 $params['pending_reason'] = $result['pendingreason'];
361 public function initialize(&$args, $method) {
362 $args['user'] = $this->_paymentProcessor
['user_name'];
363 $args['pwd'] = $this->_paymentProcessor
['password'];
364 $args['version'] = 3.0;
365 $args['signature'] = $this->_paymentProcessor
['signature'];
366 $args['subject'] = CRM_Utils_Array
::value('subject', $this->_paymentProcessor
);
367 $args['method'] = $method;
371 * This function collects all the information from a web/api form and invokes
372 * the relevant payment processor specific functions to perform the transaction
374 * @param array $params
375 * Assoc array of input parameters for this transaction.
377 * @param string $component
379 * the result in an nice formatted array (or an error object)
381 public function doDirectPayment(&$params, $component = 'contribute') {
384 $this->initialize($args, 'DoDirectPayment');
386 $args['paymentAction'] = 'Sale';
387 $args['amt'] = $params['amount'];
388 $args['currencyCode'] = $params['currencyID'];
389 $args['invnum'] = $params['invoiceID'];
390 $args['ipaddress'] = $params['ip_address'];
391 $args['creditCardType'] = $params['credit_card_type'];
392 $args['acct'] = $params['credit_card_number'];
393 $args['expDate'] = sprintf('%02d', $params['month']) . $params['year'];
394 $args['cvv2'] = $params['cvv2'];
395 $args['firstName'] = $params['first_name'];
396 $args['lastName'] = $params['last_name'];
397 $args['email'] = CRM_Utils_Array
::value('email', $params);
398 $args['street'] = $params['street_address'];
399 $args['city'] = $params['city'];
400 $args['state'] = $params['state_province'];
401 $args['countryCode'] = $params['country'];
402 $args['zip'] = $params['postal_code'];
403 $args['desc'] = substr(CRM_Utils_Array
::value('description', $params), 0, 127);
404 $args['custom'] = CRM_Utils_Array
::value('accountingCode', $params);
406 // add CiviCRM BN code
407 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
409 if (CRM_Utils_Array
::value('is_recur', $params) == 1) {
410 $start_time = strtotime(date('m/d/Y'));
411 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
413 $args['PaymentAction'] = 'Sale';
414 $args['billingperiod'] = ucwords($params['frequency_unit']);
415 $args['billingfrequency'] = $params['frequency_interval'];
416 $args['method'] = "CreateRecurringPaymentsProfile";
417 $args['profilestartdate'] = $start_date;
419 $params['description'] . ": " .
420 $params['amount'] . " Per " .
421 $params['frequency_interval'] . " " .
422 $params['frequency_unit'];
423 $args['amt'] = $params['amount'];
424 $args['totalbillingcycles'] = $params['installments'];
425 $args['version'] = 56.0;
426 $args['PROFILEREFERENCE'] = "" .
427 "i=" . $params['invoiceID'] . "&m=" . $component .
428 "&c=" . $params['contactID'] . "&r=" . $params['contributionRecurID'] .
429 "&b=" . $params['contributionID'] . "&p=" . $params['contributionPageID'];
432 // Allow further manipulation of the arguments via custom hooks ..
433 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $args);
435 $result = $this->invokeAPI($args);
438 if (is_a($result, 'CRM_Core_Error')) {
442 $params['recurr_profile_id'] = NULL;
444 if (CRM_Utils_Array
::value('is_recur', $params) == 1) {
445 $params['recurr_profile_id'] = $result['profileid'];
450 $params['trxn_id'] = CRM_Utils_Array
::value('transactionid', $result);
451 $params['gross_amount'] = CRM_Utils_Array
::value('amt', $result);
456 * This function checks to see if we have the right config values.
459 * the error message if any
461 public function checkConfig() {
463 $paymentProcessorType = CRM_Core_PseudoConstant
::paymentProcessorType(FALSE, NULL, 'name');
465 if ($this->_paymentProcessor
['payment_processor_type_id'] != CRM_Utils_Array
::key('PayPal_Standard', $paymentProcessorType)) {
466 if (empty($this->_paymentProcessor
['signature'])) {
467 $error[] = ts('Signature is not set in the Administer » System Settings » Payment Processors.');
470 if (empty($this->_paymentProcessor
['password'])) {
471 $error[] = ts('Password is not set in the Administer » System Settings » Payment Processors.');
474 if (!$this->_paymentProcessor
['user_name']) {
475 $error[] = ts('User Name is not set in the Administer » System Settings » Payment Processors.');
478 if (!empty($error)) {
479 return implode('<p>', $error);
487 * @return null|string
489 public function cancelSubscriptionURL() {
490 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal_Standard') {
491 return "{$this->_paymentProcessor['url_site']}cgi-bin/webscr?cmd=_subscr-find&alias=" . urlencode($this->_paymentProcessor
['user_name']);
499 * Check whether a method is present ( & supported ) by the payment processor object.
501 * @param string $method
502 * Method to check for.
506 public function isSupported($method = 'cancelSubscription') {
507 if ($this->_paymentProcessor
['payment_processor_type'] != 'PayPal') {
508 // since subscription methods like cancelSubscription or updateBilling is not yet implemented / supported
509 // by standard or express.
512 return parent
::isSupported($method);
516 * Paypal express replaces the submit button with it's own.
519 * Should the form button by suppressed?
521 public function isSuppressSubmitButtons() {
522 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal_Express') {
529 * @param string $message
530 * @param array $params
532 * @return array|bool|object
534 public function cancelSubscription(&$message = '', $params = array()) {
535 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal') {
537 $this->initialize($args, 'ManageRecurringPaymentsProfileStatus');
539 $args['PROFILEID'] = CRM_Utils_Array
::value('subscriptionId', $params);
540 $args['ACTION'] = 'Cancel';
541 $args['NOTE'] = CRM_Utils_Array
::value('reason', $params);
543 $result = $this->invokeAPI($args);
544 if (is_a($result, 'CRM_Core_Error')) {
547 $message = "{$result['ack']}: profileid={$result['profileid']}";
554 * Process incoming notification.
556 * This is only supported for paypal pro at the moment & no specific plans to add this path to core
557 * for paypal standard as the goal must be to separate the 2.
559 * We don't need to handle paypal standard using this path as there has never been any historic support
560 * for paypal standard to call civicrm/payment/ipn as a path.
562 static public function handlePaymentNotification() {
563 $paypalIPN = new CRM_Core_Payment_PayPalProIPN($_REQUEST);
568 * @param string $message
569 * @param array $params
571 * @return array|bool|object
573 public function updateSubscriptionBillingInfo(&$message = '', $params = array()) {
574 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal') {
575 $config = CRM_Core_Config
::singleton();
577 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
579 $args['PROFILEID'] = $params['subscriptionId'];
580 $args['AMT'] = $params['amount'];
581 $args['CURRENCYCODE'] = $config->defaultCurrency
;
582 $args['CREDITCARDTYPE'] = $params['credit_card_type'];
583 $args['ACCT'] = $params['credit_card_number'];
584 $args['EXPDATE'] = sprintf('%02d', $params['month']) . $params['year'];
585 $args['CVV2'] = $params['cvv2'];
587 $args['FIRSTNAME'] = $params['first_name'];
588 $args['LASTNAME'] = $params['last_name'];
589 $args['STREET'] = $params['street_address'];
590 $args['CITY'] = $params['city'];
591 $args['STATE'] = $params['state_province'];
592 $args['COUNTRYCODE'] = $params['postal_code'];
593 $args['ZIP'] = $params['country'];
595 $result = $this->invokeAPI($args);
596 if (is_a($result, 'CRM_Core_Error')) {
599 $message = "{$result['ack']}: profileid={$result['profileid']}";
606 * @param string $message
607 * @param array $params
609 * @return array|bool|object
611 public function changeSubscriptionAmount(&$message = '', $params = array()) {
612 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal') {
613 $config = CRM_Core_Config
::singleton();
615 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
617 $args['PROFILEID'] = $params['subscriptionId'];
618 $args['AMT'] = $params['amount'];
619 $args['CURRENCYCODE'] = $config->defaultCurrency
;
620 $args['BILLINGFREQUENCY'] = $params['installments'];
622 $result = $this->invokeAPI($args);
623 CRM_Core_Error
::debug_var('$result', $result);
624 if (is_a($result, 'CRM_Core_Error')) {
627 $message = "{$result['ack']}: profileid={$result['profileid']}";
634 * Function to action pre-approval if supported
636 * @param array $params
637 * Parameters from the form
640 * - pre_approval_parameters (this will be stored on the calling form & available later)
641 * - redirect_url (if set the browser will be redirected to this.
643 public function doPreApproval(&$params) {
644 $token = $this->setExpressCheckOut($params);
646 'pre_approval_parameters' => array('token' => $token),
647 'redirect_url' => $this->_paymentProcessor
['url_site'] . "/cgi-bin/webscr?cmd=_express-checkout&token=$token",
652 * @param array $params
653 * @param string $component
657 public function doTransferCheckout(&$params, $component = 'contribute') {
658 $config = CRM_Core_Config
::singleton();
660 if ($component != 'contribute' && $component != 'event') {
661 CRM_Core_Error
::fatal(ts('Component is invalid'));
664 $notifyURL = $config->userFrameworkResourceURL
. "extern/ipn.php?reset=1&contactID={$params['contactID']}" . "&contributionID={$params['contributionID']}" . "&module={$component}";
666 if ($component == 'event') {
667 $notifyURL .= "&eventID={$params['eventID']}&participantID={$params['participantID']}";
670 $membershipID = CRM_Utils_Array
::value('membershipID', $params);
672 $notifyURL .= "&membershipID=$membershipID";
674 $relatedContactID = CRM_Utils_Array
::value('related_contact', $params);
675 if ($relatedContactID) {
676 $notifyURL .= "&relatedContactID=$relatedContactID";
678 $onBehalfDupeAlert = CRM_Utils_Array
::value('onbehalf_dupe_alert', $params);
679 if ($onBehalfDupeAlert) {
680 $notifyURL .= "&onBehalfDupeAlert=$onBehalfDupeAlert";
685 $url = ($component == 'event') ?
'civicrm/event/register' : 'civicrm/contribute/transact';
686 $cancel = ($component == 'event') ?
'_qf_Register_display' : '_qf_Main_display';
687 $returnURL = CRM_Utils_System
::url($url,
688 "_qf_ThankYou_display=1&qfKey={$params['qfKey']}",
692 $cancelUrlString = "$cancel=1&cancel=1&qfKey={$params['qfKey']}";
693 if (!empty($params['is_recur'])) {
694 $cancelUrlString .= "&isRecur=1&recurId={$params['contributionRecurID']}&contribId={$params['contributionID']}";
697 $cancelURL = CRM_Utils_System
::url(
703 // ensure that the returnURL is absolute.
704 if (substr($returnURL, 0, 4) != 'http') {
705 $fixUrl = CRM_Utils_System
::url("civicrm/admin/setting/url", '&reset=1');
706 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)));
709 $paypalParams = array(
710 'business' => $this->_paymentProcessor
['user_name'],
711 'notify_url' => $notifyURL,
712 'item_name' => $params['item_name'],
714 'undefined_quantity' => 0,
715 'cancel_return' => $cancelURL,
718 'return' => $returnURL,
720 'currency_code' => $params['currencyID'],
721 'invoice' => $params['invoiceID'],
722 'lc' => substr($config->lcMessages
, -2),
723 'charset' => function_exists('mb_internal_encoding') ?
mb_internal_encoding() : 'UTF-8',
724 'custom' => CRM_Utils_Array
::value('accountingCode', $params),
725 'bn' => 'CiviCRM_SP',
728 // add name and address if available, CRM-3130
730 'first_name' => 'first_name',
731 'last_name' => 'last_name',
732 'street_address' => 'address1',
733 'country' => 'country',
734 'preferred_language' => 'lc',
736 'state_province' => 'state',
737 'postal_code' => 'zip',
741 foreach (array_keys($params) as $p) {
742 // get the base name without the location type suffixed to it
743 $parts = explode('-', $p);
744 $name = count($parts) > 1 ?
$parts[0] : $p;
745 if (isset($otherVars[$name])) {
746 $value = $params[$p];
748 if ($name == 'state_province') {
749 $stateName = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($value);
752 if ($name == 'country') {
753 $countryName = CRM_Core_PseudoConstant
::countryIsoCode($value);
754 $value = $countryName;
756 // ensure value is not an array
758 if (!is_array($value)) {
759 $paypalParams[$otherVars[$name]] = $value;
765 // if recurring donations, add a few more items
766 if (!empty($params['is_recur'])) {
767 if ($params['contributionRecurID']) {
768 $notifyURL .= "&contributionRecurID={$params['contributionRecurID']}&contributionPageID={$params['contributionPageID']}";
769 $paypalParams['notify_url'] = $notifyURL;
772 CRM_Core_Error
::fatal(ts('Recurring contribution, but no database id'));
775 $paypalParams +
= array(
776 'cmd' => '_xclick-subscriptions',
777 'a3' => $params['amount'],
778 'p3' => $params['frequency_interval'],
779 't3' => ucfirst(substr($params['frequency_unit'], 0, 1)),
782 'srt' => CRM_Utils_Array
::value('installments', $params),
788 $paypalParams +
= array(
790 'amount' => $params['amount'],
794 // Allow further manipulation of the arguments via custom hooks ..
795 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $paypalParams);
798 foreach ($paypalParams as $key => $value) {
799 if ($value === NULL) {
803 $value = urlencode($value);
804 if ($key == 'return' ||
805 $key == 'cancel_return' ||
808 $value = str_replace('%2F', '/', $value);
810 $uri .= "&{$key}={$value}";
813 $uri = substr($uri, 1);
814 $url = $this->_paymentProcessor
['url_site'];
815 $sub = empty($params['is_recur']) ?
'cgi-bin/webscr' : 'subscriptions';
816 $paypalURL = "{$url}{$sub}?$uri";
818 CRM_Utils_System
::redirect($paypalURL);
822 * Hash_call: Function to perform the API call to PayPal using API signature
823 * @methodName is name of API method.
824 * @nvpStr is nvp string.
825 * returns an associtive array containing the response from the server.
827 public function invokeAPI($args, $url = NULL) {
830 if (empty($this->_paymentProcessor
['url_api'])) {
831 CRM_Core_Error
::fatal(ts('Please set the API URL. Please refer to the documentation for more details'));
834 $url = $this->_paymentProcessor
['url_api'] . 'nvp';
837 if (!function_exists('curl_init')) {
838 CRM_Core_Error
::fatal("curl functions NOT available.");
841 //setting the curl parameters.
843 curl_setopt($ch, CURLOPT_URL
, $url);
844 curl_setopt($ch, CURLOPT_VERBOSE
, 1);
846 //turning off the server and peer verification(TrustManager Concept).
847 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'verifySSL'));
848 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST
, CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'verifySSL') ?
2 : 0);
850 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, 1);
851 curl_setopt($ch, CURLOPT_POST
, 1);
854 foreach ($args as $n => $v) {
855 $p[] = "$n=" . urlencode($v);
858 //NVPRequest for submitting to server
859 $nvpreq = implode('&', $p);
861 //setting the nvpreq as POST FIELD to curl
862 curl_setopt($ch, CURLOPT_POSTFIELDS
, $nvpreq);
864 //getting response from server
865 $response = curl_exec($ch);
867 //converting NVPResponse to an Associative Array
868 $result = self
::deformat($response);
870 if (curl_errno($ch)) {
871 $e = CRM_Core_Error
::singleton();
872 $e->push(curl_errno($ch),
882 if (strtolower($result['ack']) != 'success' &&
883 strtolower($result['ack']) != 'successwithwarning'
885 $e = CRM_Core_Error
::singleton();
886 $e->push($result['l_errorcode0'],
888 "{$result['l_shortmessage0']} {$result['l_longmessage0']}"
897 * This function will take NVPString and convert it to an Associative Array and it will decode the response.
898 * It is useful to search for a particular key and displaying arrays.
899 * @nvpstr is NVPString.
900 * @nvpArray is Associative Array.
902 public static function deformat($str) {
905 while (strlen($str)) {
907 $keyPos = strpos($str, '=');
910 $valPos = strpos($str, '&') ?
strpos($str, '&') : strlen($str);
912 /*getting the Key and Value values and storing in a Associative Array*/
914 $key = substr($str, 0, $keyPos);
915 $val = substr($str, $keyPos +
1, $valPos - $keyPos - 1);
917 //decoding the respose
918 $result[strtolower(urldecode($key))] = urldecode($val);
919 $str = substr($str, $valPos +
1, strlen($str));