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');
72 if (!$this->_paymentProcessor
['user_name']) {
73 CRM_Core_Error
::fatal(ts('Could not find user name for payment processor'));
78 * Are back office payments supported - e.g paypal standard won't permit you to enter a credit card associated with someone else's login
81 protected function supportsBackOffice() {
82 if ($this->_processorName
== ts('PayPal Pro')) {
89 * Can recurring contributions be set against pledges.
91 * In practice all processors that use the baseIPN function to finish transactions or
92 * call the completetransaction api support this by looking up previous contributions in the
93 * series and, if there is a prior contribution against a pledge, and the pledge is not complete,
94 * adding the new payment to the pledge.
96 * However, only enabling for processors it has been tested against.
100 protected function supportsRecurContributionsForPledges() {
105 * Express checkout code. Check PayPal documentation for more information
107 * @param array $params
108 * Assoc array of input parameters for this transaction.
111 * the result in an nice formatted array (or an error object)
113 public function setExpressCheckOut(&$params) {
116 $this->initialize($args, 'SetExpressCheckout');
118 $args['paymentAction'] = $params['payment_action'];
119 $args['amt'] = $params['amount'];
120 $args['currencyCode'] = $params['currencyID'];
121 $args['desc'] = CRM_Utils_Array
::value('description', $params);
122 $args['invnum'] = $params['invoiceID'];
123 $args['returnURL'] = $params['returnURL'];
124 $args['cancelURL'] = $params['cancelURL'];
125 $args['version'] = '56.0';
127 //LCD if recurring, collect additional data and set some values
128 if (!empty($params['is_recur'])) {
129 $args['L_BILLINGTYPE0'] = 'RecurringPayments';
130 //$args['L_BILLINGAGREEMENTDESCRIPTION0'] = 'Recurring Contribution';
131 $args['L_BILLINGAGREEMENTDESCRIPTION0'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
132 $args['L_PAYMENTTYPE0'] = 'Any';
135 // Allow further manipulation of the arguments via custom hooks ..
136 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $args);
138 $result = $this->invokeAPI($args);
140 if (is_a($result, 'CRM_Core_Error')) {
146 return $result['token'];
150 * Get details from paypal. Check PayPal documentation for more information
152 * @param string $token
153 * The key associated with this transaction.
156 * the result in an nice formatted array (or an error object)
158 public function getExpressCheckoutDetails($token) {
161 $this->initialize($args, 'GetExpressCheckoutDetails');
162 $args['token'] = $token;
164 $args['method'] = 'GetExpressCheckoutDetails';
166 $result = $this->invokeAPI($args);
168 if (is_a($result, 'CRM_Core_Error')) {
175 $params['token'] = $result['token'];
176 $params['payer_id'] = $result['payerid'];
177 $params['payer_status'] = $result['payerstatus'];
178 $params['first_name'] = $result['firstname'];
179 $params['middle_name'] = CRM_Utils_Array
::value('middlename', $result);
180 $params['last_name'] = $result['lastname'];
181 $params['street_address'] = $result['shiptostreet'];
182 $params['supplemental_address_1'] = CRM_Utils_Array
::value('shiptostreet2', $result);
183 $params['city'] = $result['shiptocity'];
184 $params['state_province'] = $result['shiptostate'];
185 $params['postal_code'] = $result['shiptozip'];
186 $params['country'] = $result['shiptocountrycode'];
192 * Do the express checkout at paypal. Check PayPal documentation for more information
194 * @param array $params
196 * @internal param string $token the key associated with this transaction
199 * the result in an nice formatted array (or an error object)
201 public function doExpressCheckout(&$params) {
204 $this->initialize($args, 'DoExpressCheckoutPayment');
206 $args['token'] = $params['token'];
207 $args['paymentAction'] = $params['payment_action'];
208 $args['amt'] = $params['amount'];
209 $args['currencyCode'] = $params['currencyID'];
210 $args['payerID'] = $params['payer_id'];
211 $args['invnum'] = $params['invoiceID'];
212 $args['returnURL'] = CRM_Utils_Array
::value('returnURL', $params);
213 $args['cancelURL'] = CRM_Utils_Array
::value('cancelURL', $params);
214 $args['desc'] = $params['description'];
216 // add CiviCRM BN code
217 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
219 $result = $this->invokeAPI($args);
221 if (is_a($result, 'CRM_Core_Error')) {
227 $params['trxn_id'] = $result['transactionid'];
228 $params['gross_amount'] = $result['amt'];
229 $params['fee_amount'] = $result['feeamt'];
230 $params['net_amount'] = CRM_Utils_Array
::value('settleamt', $result);
231 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
232 $params['net_amount'] = $params['gross_amount'] - $params['fee_amount'];
234 $params['payment_status'] = $result['paymentstatus'];
235 $params['pending_reason'] = $result['pendingreason'];
240 //LCD add new function for handling recurring payments for PayPal Express
242 * @param array $params
246 public function createRecurringPayments(&$params) {
249 $this->initialize($args, 'CreateRecurringPaymentsProfile');
251 $start_time = strtotime(date('m/d/Y'));
252 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
254 $args['token'] = $params['token'];
255 $args['paymentAction'] = $params['payment_action'];
256 $args['amt'] = $params['amount'];
257 $args['currencyCode'] = $params['currencyID'];
258 $args['payerID'] = $params['payer_id'];
259 $args['invnum'] = $params['invoiceID'];
260 $args['returnURL'] = $params['returnURL'];
261 $args['cancelURL'] = $params['cancelURL'];
262 $args['profilestartdate'] = $start_date;
263 $args['method'] = 'CreateRecurringPaymentsProfile';
264 $args['billingfrequency'] = $params['frequency_interval'];
265 $args['billingperiod'] = ucwords($params['frequency_unit']);
266 $args['desc'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
267 //$args['desc'] = 'Recurring Contribution';
268 $args['totalbillingcycles'] = $params['installments'];
269 $args['version'] = '56.0';
270 $args['profilereference'] = "i={$params['invoiceID']}" .
272 "&c={$params['contactID']}" .
273 "&r={$params['contributionRecurID']}" .
274 "&b={$params['contributionID']}" .
275 "&p={$params['contributionPageID']}";
277 // add CiviCRM BN code
278 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
280 $result = $this->invokeAPI($args);
282 if (is_a($result, 'CRM_Core_Error')) {
287 $params['trxn_id'] = $result['transactionid'];
288 $params['gross_amount'] = $result['amt'];
289 $params['fee_amount'] = $result['feeamt'];
290 $params['net_amount'] = $result['settleamt'];
291 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
292 $params['net_amount'] = $params['gross_amount'] - $params['fee_amount'];
294 $params['payment_status'] = $result['paymentstatus'];
295 $params['pending_reason'] = $result['pendingreason'];
304 public function initialize(&$args, $method) {
305 $args['user'] = $this->_paymentProcessor
['user_name'];
306 $args['pwd'] = $this->_paymentProcessor
['password'];
307 $args['version'] = 3.0;
308 $args['signature'] = $this->_paymentProcessor
['signature'];
309 $args['subject'] = CRM_Utils_Array
::value('subject', $this->_paymentProcessor
);
310 $args['method'] = $method;
314 * This function collects all the information from a web/api form and invokes
315 * the relevant payment processor specific functions to perform the transaction
317 * @param array $params
318 * Assoc array of input parameters for this transaction.
320 * @param string $component
322 * the result in an nice formatted array (or an error object)
324 public function doDirectPayment(&$params, $component = 'contribute') {
327 $this->initialize($args, 'DoDirectPayment');
329 $args['paymentAction'] = $params['payment_action'];
330 $args['amt'] = $params['amount'];
331 $args['currencyCode'] = $params['currencyID'];
332 $args['invnum'] = $params['invoiceID'];
333 $args['ipaddress'] = $params['ip_address'];
334 $args['creditCardType'] = $params['credit_card_type'];
335 $args['acct'] = $params['credit_card_number'];
336 $args['expDate'] = sprintf('%02d', $params['month']) . $params['year'];
337 $args['cvv2'] = $params['cvv2'];
338 $args['firstName'] = $params['first_name'];
339 $args['lastName'] = $params['last_name'];
340 $args['email'] = CRM_Utils_Array
::value('email', $params);
341 $args['street'] = $params['street_address'];
342 $args['city'] = $params['city'];
343 $args['state'] = $params['state_province'];
344 $args['countryCode'] = $params['country'];
345 $args['zip'] = $params['postal_code'];
346 $args['desc'] = substr(CRM_Utils_Array
::value('description', $params), 0, 127);
347 $args['custom'] = CRM_Utils_Array
::value('accountingCode', $params);
349 // add CiviCRM BN code
350 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
352 if (CRM_Utils_Array
::value('is_recur', $params) == 1) {
353 $start_time = strtotime(date('m/d/Y'));
354 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
356 $args['PaymentAction'] = 'Sale';
357 $args['billingperiod'] = ucwords($params['frequency_unit']);
358 $args['billingfrequency'] = $params['frequency_interval'];
359 $args['method'] = "CreateRecurringPaymentsProfile";
360 $args['profilestartdate'] = $start_date;
362 $params['description'] . ": " .
363 $params['amount'] . " Per " .
364 $params['frequency_interval'] . " " .
365 $params['frequency_unit'];
366 $args['amt'] = $params['amount'];
367 $args['totalbillingcycles'] = $params['installments'];
368 $args['version'] = 56.0;
369 $args['PROFILEREFERENCE'] = "" .
370 "i=" . $params['invoiceID'] . "&m=" . $component .
371 "&c=" . $params['contactID'] . "&r=" . $params['contributionRecurID'] .
372 "&b=" . $params['contributionID'] . "&p=" . $params['contributionPageID'];
375 // Allow further manipulation of the arguments via custom hooks ..
376 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $args);
378 $result = $this->invokeAPI($args);
381 if (is_a($result, 'CRM_Core_Error')) {
385 $params['recurr_profile_id'] = NULL;
387 if (CRM_Utils_Array
::value('is_recur', $params) == 1) {
388 $params['recurr_profile_id'] = $result['profileid'];
393 $params['trxn_id'] = CRM_Utils_Array
::value('transactionid', $result);
394 $params['gross_amount'] = CRM_Utils_Array
::value('amt', $result);
395 $params = array_merge($params, $this->doQuery($params));
400 * Query payment processor for details about a transaction.
402 * For paypal see : https://developer.paypal.com/webapps/developer/docs/classic/api/merchant/GetTransactionDetails_API_Operation_NVP/
404 * @param array $params
405 * Array of parameters containing one of:
406 * - trxn_id Id of an individual transaction.
407 * - processor_id Id of a recurring contribution series as stored in the civicrm_contribution_recur table.
410 * Extra parameters retrieved.
411 * Any parameters retrievable through this should be documented in the function comments at
412 * CRM_Core_Payment::doQuery. Currently
413 * - fee_amount Amount of fee paid
415 * @throws \Civi\Payment\Exception\PaymentProcessorException
417 public function doQuery($params) {
418 if (empty($params['trxn_id'])) {
419 throw new \Civi\Payment\Exception\
PaymentProcessorException('transaction id not set');
422 'TRANSACTIONID' => $params['trxn_id'],
424 $this->initialize($args, 'GetTransactionDetails');
425 $result = $this->invokeAPI($args);
427 'fee_amount' => $result['feeamt'],
428 'net_amount' => $params['gross_amount'] - $result['feeamt'],
433 * This function checks to see if we have the right config values.
436 * the error message if any
438 public function checkConfig() {
440 $paymentProcessorType = CRM_Core_PseudoConstant
::paymentProcessorType(FALSE, NULL, 'name');
442 $this->_paymentProcessor
['payment_processor_type_id'] == CRM_Utils_Array
::key('PayPal_Standard', $paymentProcessorType) ||
443 $this->_paymentProcessor
['payment_processor_type_id'] == CRM_Utils_Array
::key('PayPal', $paymentProcessorType)
445 if (empty($this->_paymentProcessor
['user_name'])) {
446 $error[] = ts('User Name is not set in the Administer » System Settings » Payment Processors.');
450 if ($this->_paymentProcessor
['payment_processor_type_id'] != CRM_Utils_Array
::key('PayPal_Standard', $paymentProcessorType)) {
451 if (empty($this->_paymentProcessor
['signature'])) {
452 $error[] = ts('Signature is not set in the Administer » System Settings » Payment Processors.');
455 if (empty($this->_paymentProcessor
['password'])) {
456 $error[] = ts('Password is not set in the Administer » System Settings » Payment Processors.');
460 if (!empty($error)) {
461 return implode('<p>', $error);
469 * @return null|string
471 public function cancelSubscriptionURL() {
472 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal_Standard') {
473 return "{$this->_paymentProcessor['url_site']}cgi-bin/webscr?cmd=_subscr-find&alias=" . urlencode($this->_paymentProcessor
['user_name']);
481 * Check whether a method is present ( & supported ) by the payment processor object.
483 * @param string $method
484 * Method to check for.
488 public function isSupported($method = 'cancelSubscription') {
489 if ($this->_paymentProcessor
['payment_processor_type'] != 'PayPal') {
490 // since subscription methods like cancelSubscription or updateBilling is not yet implemented / supported
491 // by standard or express.
494 return parent
::isSupported($method);
498 * @param string $message
499 * @param array $params
501 * @return array|bool|object
503 public function cancelSubscription(&$message = '', $params = array()) {
504 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal') {
506 $this->initialize($args, 'ManageRecurringPaymentsProfileStatus');
508 $args['PROFILEID'] = CRM_Utils_Array
::value('subscriptionId', $params);
509 $args['ACTION'] = 'Cancel';
510 $args['NOTE'] = CRM_Utils_Array
::value('reason', $params);
512 $result = $this->invokeAPI($args);
513 if (is_a($result, 'CRM_Core_Error')) {
516 $message = "{$result['ack']}: profileid={$result['profileid']}";
523 * Process incoming notification.
525 * This is only supported for paypal pro at the moment & no specific plans to add this path to core
526 * for paypal standard as the goal must be to separate the 2.
528 * We don't need to handle paypal standard using this path as there has never been any historic support
529 * for paypal standard to call civicrm/payment/ipn as a path.
531 static public function handlePaymentNotification() {
532 $paypalIPN = new CRM_Core_Payment_PayPalProIPN($_REQUEST);
537 * @param string $message
538 * @param array $params
540 * @return array|bool|object
542 public function updateSubscriptionBillingInfo(&$message = '', $params = array()) {
543 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal') {
544 $config = CRM_Core_Config
::singleton();
546 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
548 $args['PROFILEID'] = $params['subscriptionId'];
549 $args['AMT'] = $params['amount'];
550 $args['CURRENCYCODE'] = $config->defaultCurrency
;
551 $args['CREDITCARDTYPE'] = $params['credit_card_type'];
552 $args['ACCT'] = $params['credit_card_number'];
553 $args['EXPDATE'] = sprintf('%02d', $params['month']) . $params['year'];
554 $args['CVV2'] = $params['cvv2'];
556 $args['FIRSTNAME'] = $params['first_name'];
557 $args['LASTNAME'] = $params['last_name'];
558 $args['STREET'] = $params['street_address'];
559 $args['CITY'] = $params['city'];
560 $args['STATE'] = $params['state_province'];
561 $args['COUNTRYCODE'] = $params['postal_code'];
562 $args['ZIP'] = $params['country'];
564 $result = $this->invokeAPI($args);
565 if (is_a($result, 'CRM_Core_Error')) {
568 $message = "{$result['ack']}: profileid={$result['profileid']}";
575 * @param string $message
576 * @param array $params
578 * @return array|bool|object
580 public function changeSubscriptionAmount(&$message = '', $params = array()) {
581 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal') {
582 $config = CRM_Core_Config
::singleton();
584 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
586 $args['PROFILEID'] = $params['subscriptionId'];
587 $args['AMT'] = $params['amount'];
588 $args['CURRENCYCODE'] = $config->defaultCurrency
;
589 $args['BILLINGFREQUENCY'] = $params['installments'];
591 $result = $this->invokeAPI($args);
592 CRM_Core_Error
::debug_var('$result', $result);
593 if (is_a($result, 'CRM_Core_Error')) {
596 $message = "{$result['ack']}: profileid={$result['profileid']}";
603 * @param array $params
604 * @param string $component
608 public function doTransferCheckout(&$params, $component = 'contribute') {
609 $config = CRM_Core_Config
::singleton();
611 if ($component != 'contribute' && $component != 'event') {
612 CRM_Core_Error
::fatal(ts('Component is invalid'));
615 $notifyURL = $config->userFrameworkResourceURL
. "extern/ipn.php?reset=1&contactID={$params['contactID']}" . "&contributionID={$params['contributionID']}" . "&module={$component}";
617 if ($component == 'event') {
618 $notifyURL .= "&eventID={$params['eventID']}&participantID={$params['participantID']}";
621 $membershipID = CRM_Utils_Array
::value('membershipID', $params);
623 $notifyURL .= "&membershipID=$membershipID";
625 $relatedContactID = CRM_Utils_Array
::value('related_contact', $params);
626 if ($relatedContactID) {
627 $notifyURL .= "&relatedContactID=$relatedContactID";
629 $onBehalfDupeAlert = CRM_Utils_Array
::value('onbehalf_dupe_alert', $params);
630 if ($onBehalfDupeAlert) {
631 $notifyURL .= "&onBehalfDupeAlert=$onBehalfDupeAlert";
636 $url = ($component == 'event') ?
'civicrm/event/register' : 'civicrm/contribute/transact';
637 $cancel = ($component == 'event') ?
'_qf_Register_display' : '_qf_Main_display';
638 $returnURL = CRM_Utils_System
::url($url,
639 "_qf_ThankYou_display=1&qfKey={$params['qfKey']}",
643 $cancelUrlString = "$cancel=1&cancel=1&qfKey={$params['qfKey']}";
644 if (!empty($params['is_recur'])) {
645 $cancelUrlString .= "&isRecur=1&recurId={$params['contributionRecurID']}&contribId={$params['contributionID']}";
648 $cancelURL = CRM_Utils_System
::url(
654 // ensure that the returnURL is absolute.
655 if (substr($returnURL, 0, 4) != 'http') {
656 $fixUrl = CRM_Utils_System
::url("civicrm/admin/setting/url", '&reset=1');
657 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)));
660 $paypalParams = array(
661 'business' => $this->_paymentProcessor
['user_name'],
662 'notify_url' => $notifyURL,
663 'item_name' => $params['item_name'],
665 'undefined_quantity' => 0,
666 'cancel_return' => $cancelURL,
669 'return' => $returnURL,
671 'currency_code' => $params['currencyID'],
672 'invoice' => $params['invoiceID'],
673 'lc' => substr($config->lcMessages
, -2),
674 'charset' => function_exists('mb_internal_encoding') ?
mb_internal_encoding() : 'UTF-8',
675 'custom' => CRM_Utils_Array
::value('accountingCode', $params),
676 'bn' => 'CiviCRM_SP',
679 // add name and address if available, CRM-3130
681 'first_name' => 'first_name',
682 'last_name' => 'last_name',
683 'street_address' => 'address1',
684 'country' => 'country',
685 'preferred_language' => 'lc',
687 'state_province' => 'state',
688 'postal_code' => 'zip',
692 foreach (array_keys($params) as $p) {
693 // get the base name without the location type suffixed to it
694 $parts = explode('-', $p);
695 $name = count($parts) > 1 ?
$parts[0] : $p;
696 if (isset($otherVars[$name])) {
697 $value = $params[$p];
699 if ($name == 'state_province') {
700 $stateName = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($value);
703 if ($name == 'country') {
704 $countryName = CRM_Core_PseudoConstant
::countryIsoCode($value);
705 $value = $countryName;
707 // ensure value is not an array
709 if (!is_array($value)) {
710 $paypalParams[$otherVars[$name]] = $value;
716 // if recurring donations, add a few more items
717 if (!empty($params['is_recur'])) {
718 if ($params['contributionRecurID']) {
719 $notifyURL .= "&contributionRecurID={$params['contributionRecurID']}&contributionPageID={$params['contributionPageID']}";
720 $paypalParams['notify_url'] = $notifyURL;
723 CRM_Core_Error
::fatal(ts('Recurring contribution, but no database id'));
726 $paypalParams +
= array(
727 'cmd' => '_xclick-subscriptions',
728 'a3' => $params['amount'],
729 'p3' => $params['frequency_interval'],
730 't3' => ucfirst(substr($params['frequency_unit'], 0, 1)),
733 'srt' => CRM_Utils_Array
::value('installments', $params),
739 $paypalParams +
= array(
741 'amount' => $params['amount'],
745 // Allow further manipulation of the arguments via custom hooks ..
746 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $paypalParams);
749 foreach ($paypalParams as $key => $value) {
750 if ($value === NULL) {
754 $value = urlencode($value);
755 if ($key == 'return' ||
756 $key == 'cancel_return' ||
759 $value = str_replace('%2F', '/', $value);
761 $uri .= "&{$key}={$value}";
764 $uri = substr($uri, 1);
765 $url = $this->_paymentProcessor
['url_site'];
766 $sub = empty($params['is_recur']) ?
'cgi-bin/webscr' : 'subscriptions';
767 $paypalURL = "{$url}{$sub}?$uri";
769 CRM_Utils_System
::redirect($paypalURL);
773 * Hash_call: Function to perform the API call to PayPal using API signature
774 * @methodName is name of API method.
775 * @nvpStr is nvp string.
776 * returns an associtive array containing the response from the server.
778 public function invokeAPI($args, $url = NULL) {
781 if (empty($this->_paymentProcessor
['url_api'])) {
782 CRM_Core_Error
::fatal(ts('Please set the API URL. Please refer to the documentation for more details'));
785 $url = $this->_paymentProcessor
['url_api'] . 'nvp';
788 if (!function_exists('curl_init')) {
789 CRM_Core_Error
::fatal("curl functions NOT available.");
792 //setting the curl parameters.
794 curl_setopt($ch, CURLOPT_URL
, $url);
795 curl_setopt($ch, CURLOPT_VERBOSE
, 1);
797 //turning off the server and peer verification(TrustManager Concept).
798 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'verifySSL'));
799 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST
, CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'verifySSL') ?
2 : 0);
801 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, 1);
802 curl_setopt($ch, CURLOPT_POST
, 1);
805 foreach ($args as $n => $v) {
806 $p[] = "$n=" . urlencode($v);
809 //NVPRequest for submitting to server
810 $nvpreq = implode('&', $p);
812 //setting the nvpreq as POST FIELD to curl
813 curl_setopt($ch, CURLOPT_POSTFIELDS
, $nvpreq);
815 //getting response from server
816 $response = curl_exec($ch);
818 //converting NVPResponse to an Associative Array
819 $result = self
::deformat($response);
821 if (curl_errno($ch)) {
822 $e = CRM_Core_Error
::singleton();
823 $e->push(curl_errno($ch),
833 if (strtolower($result['ack']) != 'success' &&
834 strtolower($result['ack']) != 'successwithwarning'
836 $e = CRM_Core_Error
::singleton();
837 $e->push($result['l_errorcode0'],
839 "{$result['l_shortmessage0']} {$result['l_longmessage0']}"
848 * This function will take NVPString and convert it to an Associative Array and it will decode the response.
849 * It is usefull to search for a particular key and displaying arrays.
850 * @nvpstr is NVPString.
851 * @nvpArray is Associative Array.
853 public static function deformat($str) {
856 while (strlen($str)) {
858 $keyPos = strpos($str, '=');
861 $valPos = strpos($str, '&') ?
strpos($str, '&') : strlen($str);
863 /*getting the Key and Value values and storing in a Associative Array*/
865 $key = substr($str, 0, $keyPos);
866 $val = substr($str, $keyPos +
1, $valPos - $keyPos - 1);
868 //decoding the respose
869 $result[strtolower(urldecode($key))] = urldecode($val);
870 $str = substr($str, $valPos +
1, strlen($str));