3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
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
47 static private $_singleton = NULL;
52 * @param string $mode the mode of operation: live or test
54 * @param $paymentProcessor
56 * @return \CRM_Core_Payment_PayPalImpl
58 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 * singleton function used to manage this object
80 * @param string $mode the mode of operation: live or test
82 * @param object $paymentProcessor
83 * @param null $paymentForm
89 static function &singleton($mode, &$paymentProcessor, &$paymentForm = NULL, $force = FALSE) {
90 $processorName = $paymentProcessor['name'];
91 if (!isset(self
::$_singleton[$processorName]) || self
::$_singleton[$processorName] === NULL) {
92 self
::$_singleton[$processorName] = new CRM_Core_Payment_PaypalImpl($mode, $paymentProcessor);
94 return self
::$_singleton[$processorName];
98 * express checkout code. Check PayPal documentation for more information
100 * @param array $params assoc array of input parameters for this transaction
102 * @return array the result in an nice formatted array (or an error object)
105 function setExpressCheckOut(&$params) {
108 $this->initialize($args, 'SetExpressCheckout');
110 $args['paymentAction'] = $params['payment_action'];
111 $args['amt'] = $params['amount'];
112 $args['currencyCode'] = $params['currencyID'];
113 $args['desc'] = CRM_Utils_Array
::value('description', $params);
114 $args['invnum'] = $params['invoiceID'];
115 $args['returnURL'] = $params['returnURL'];
116 $args['cancelURL'] = $params['cancelURL'];
117 $args['version'] = '56.0';
119 //LCD if recurring, collect additional data and set some values
120 if (!empty($params['is_recur'])) {
121 $args['L_BILLINGTYPE0'] = 'RecurringPayments';
122 //$args['L_BILLINGAGREEMENTDESCRIPTION0'] = 'Recurring Contribution';
123 $args['L_BILLINGAGREEMENTDESCRIPTION0'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
124 $args['L_PAYMENTTYPE0'] = 'Any';
127 // Allow further manipulation of the arguments via custom hooks ..
128 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $args);
130 $result = $this->invokeAPI($args);
132 if (is_a($result, 'CRM_Core_Error')) {
138 return $result['token'];
142 * get details from paypal. Check PayPal documentation for more information
144 * @param string $token the key associated with this transaction
146 * @return array the result in an nice formatted array (or an error object)
149 function getExpressCheckoutDetails($token) {
152 $this->initialize($args, 'GetExpressCheckoutDetails');
153 $args['token'] = $token;
155 $args['method'] = 'GetExpressCheckoutDetails';
157 $result = $this->invokeAPI($args);
159 if (is_a($result, 'CRM_Core_Error')) {
166 $params['token'] = $result['token'];
167 $params['payer_id'] = $result['payerid'];
168 $params['payer_status'] = $result['payerstatus'];
169 $params['first_name'] = $result['firstname'];
170 $params['middle_name'] = CRM_Utils_Array
::value('middlename', $result);
171 $params['last_name'] = $result['lastname'];
172 $params['street_address'] = $result['shiptostreet'];
173 $params['supplemental_address_1'] = CRM_Utils_Array
::value('shiptostreet2', $result);
174 $params['city'] = $result['shiptocity'];
175 $params['state_province'] = $result['shiptostate'];
176 $params['postal_code'] = $result['shiptozip'];
177 $params['country'] = $result['shiptocountrycode'];
183 * do the express checkout at paypal. Check PayPal documentation for more information
187 * @internal param string $token the key associated with this transaction
189 * @return array the result in an nice formatted array (or an error object)
192 function doExpressCheckout(&$params) {
195 $this->initialize($args, 'DoExpressCheckoutPayment');
197 $args['token'] = $params['token'];
198 $args['paymentAction'] = $params['payment_action'];
199 $args['amt'] = $params['amount'];
200 $args['currencyCode'] = $params['currencyID'];
201 $args['payerID'] = $params['payer_id'];
202 $args['invnum'] = $params['invoiceID'];
203 $args['returnURL'] = CRM_Utils_Array
::value('returnURL', $params);
204 $args['cancelURL'] = CRM_Utils_Array
::value('cancelURL', $params);
205 $args['desc'] = $params['description'];
207 // add CiviCRM BN code
208 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
210 $result = $this->invokeAPI($args);
212 if (is_a($result, 'CRM_Core_Error')) {
218 $params['trxn_id'] = $result['transactionid'];
219 $params['gross_amount'] = $result['amt'];
220 $params['fee_amount'] = $result['feeamt'];
221 $params['net_amount'] = CRM_Utils_Array
::value('settleamt', $result);
222 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
223 $params['net_amount'] = $params['gross_amount'] - $params['fee_amount'];
225 $params['payment_status'] = $result['paymentstatus'];
226 $params['pending_reason'] = $result['pendingreason'];
231 //LCD add new function for handling recurring payments for PayPal Express
237 function createRecurringPayments(&$params) {
240 $this->initialize($args, 'CreateRecurringPaymentsProfile');
242 $start_time = strtotime(date('m/d/Y'));
243 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
245 $args['token'] = $params['token'];
246 $args['paymentAction'] = $params['payment_action'];
247 $args['amt'] = $params['amount'];
248 $args['currencyCode'] = $params['currencyID'];
249 $args['payerID'] = $params['payer_id'];
250 $args['invnum'] = $params['invoiceID'];
251 $args['returnURL'] = $params['returnURL'];
252 $args['cancelURL'] = $params['cancelURL'];
253 $args['profilestartdate'] = $start_date;
254 $args['method'] = 'CreateRecurringPaymentsProfile';
255 $args['billingfrequency'] = $params['frequency_interval'];
256 $args['billingperiod'] = ucwords($params['frequency_unit']);
257 $args['desc'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
258 //$args['desc'] = 'Recurring Contribution';
259 $args['totalbillingcycles'] = $params['installments'];
260 $args['version'] = '56.0';
261 $args['profilereference'] =
262 "i={$params['invoiceID']}" .
264 "&c={$params['contactID']}" .
265 "&r={$params['contributionRecurID']}" .
266 "&b={$params['contributionID']}" .
267 "&p={$params['contributionPageID']}";
269 // add CiviCRM BN code
270 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
272 $result = $this->invokeAPI($args);
274 if (is_a($result, 'CRM_Core_Error')) {
279 $params['trxn_id'] = $result['transactionid'];
280 $params['gross_amount'] = $result['amt'];
281 $params['fee_amount'] = $result['feeamt'];
282 $params['net_amount'] = $result['settleamt'];
283 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
284 $params['net_amount'] = $params['gross_amount'] - $params['fee_amount'];
286 $params['payment_status'] = $result['paymentstatus'];
287 $params['pending_reason'] = $result['pendingreason'];
296 function initialize(&$args, $method) {
297 $args['user'] = $this->_paymentProcessor
['user_name'];
298 $args['pwd'] = $this->_paymentProcessor
['password'];
299 $args['version'] = 3.0;
300 $args['signature'] = $this->_paymentProcessor
['signature'];
301 $args['subject'] = $this->_paymentProcessor
['subject'];
302 $args['method'] = $method;
306 * This function collects all the information from a web/api form and invokes
307 * the relevant payment processor specific functions to perform the transaction
309 * @param array $params assoc array of input parameters for this transaction
311 * @param string $component
312 * @return array the result in an nice formatted array (or an error object)
315 function doDirectPayment(&$params, $component = 'contribute') {
318 $this->initialize($args, 'DoDirectPayment');
320 $args['paymentAction'] = $params['payment_action'];
321 $args['amt'] = $params['amount'];
322 $args['currencyCode'] = $params['currencyID'];
323 $args['invnum'] = $params['invoiceID'];
324 $args['ipaddress'] = $params['ip_address'];
325 $args['creditCardType'] = $params['credit_card_type'];
326 $args['acct'] = $params['credit_card_number'];
327 $args['expDate'] = sprintf('%02d', $params['month']) . $params['year'];
328 $args['cvv2'] = $params['cvv2'];
329 $args['firstName'] = $params['first_name'];
330 $args['lastName'] = $params['last_name'];
331 $args['email'] = CRM_Utils_Array
::value('email', $params);
332 $args['street'] = $params['street_address'];
333 $args['city'] = $params['city'];
334 $args['state'] = $params['state_province'];
335 $args['countryCode'] = $params['country'];
336 $args['zip'] = $params['postal_code'];
337 $args['desc'] = substr(CRM_Utils_Array
::value('description', $params), 0, 127);
338 $args['custom'] = CRM_Utils_Array
::value('accountingCode', $params);
340 // add CiviCRM BN code
341 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
343 if (CRM_Utils_Array
::value('is_recur', $params) == 1) {
344 $start_time = strtotime(date('m/d/Y'));
345 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
347 $args['PaymentAction'] = 'Sale';
348 $args['billingperiod'] = ucwords($params['frequency_unit']);
349 $args['billingfrequency'] = $params['frequency_interval'];
350 $args['method'] = "CreateRecurringPaymentsProfile";
351 $args['profilestartdate'] = $start_date;
353 $params['description'] . ": " .
354 $params['amount'] . " Per " .
355 $params['frequency_interval'] . " " .
356 $params['frequency_unit'];
357 $args['amt'] = $params['amount'];
358 $args['totalbillingcycles'] = $params['installments'];
359 $args['version'] = 56.0;
360 $args['PROFILEREFERENCE'] =
361 "i=" . $params['invoiceID'] . "&m=" . $component .
362 "&c=" . $params['contactID'] . "&r=" . $params['contributionRecurID'] .
363 "&b=" . $params['contributionID'] . "&p=" . $params['contributionPageID'];
366 // Allow further manipulation of the arguments via custom hooks ..
367 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $args);
369 $result = $this->invokeAPI($args);
372 if (is_a($result, 'CRM_Core_Error')) {
376 $params['recurr_profile_id'] = NULL;
378 if (CRM_Utils_Array
::value('is_recur', $params) == 1) {
379 $params['recurr_profile_id'] = $result['profileid'];
384 $params['trxn_id'] = CRM_Utils_Array
::value('transactionid', $result);
385 $params['gross_amount'] = CRM_Utils_Array
::value('amt', $result);
390 * This function checks to see if we have the right config values
392 * @return string the error message if any
395 function checkConfig() {
397 $paymentProcessorType = CRM_Core_PseudoConstant
::paymentProcessorType(false, null, 'name');
399 $this->_paymentProcessor
['payment_processor_type_id'] == CRM_Utils_Array
::key('PayPal_Standard', $paymentProcessorType) ||
400 $this->_paymentProcessor
['payment_processor_type_id'] == CRM_Utils_Array
::key('PayPal', $paymentProcessorType)
402 if (empty($this->_paymentProcessor
['user_name'])) {
403 $error[] = ts('User Name is not set in the Administer » System Settings » Payment Processors.');
407 if ($this->_paymentProcessor
['payment_processor_type_id'] != CRM_Utils_Array
::key('PayPal_Standard', $paymentProcessorType)) {
408 if (empty($this->_paymentProcessor
['signature'])) {
409 $error[] = ts('Signature is not set in the Administer » System Settings » Payment Processors.');
412 if (empty($this->_paymentProcessor
['password'])) {
413 $error[] = ts('Password is not set in the Administer » System Settings » Payment Processors.');
417 if (!empty($error)) {
418 return implode('<p>', $error);
426 * @return null|string
428 function cancelSubscriptionURL() {
429 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal_Standard') {
430 return "{$this->_paymentProcessor['url_site']}cgi-bin/webscr?cmd=_subscr-find&alias=" . urlencode($this->_paymentProcessor
['user_name']);
438 * Function to check whether a method is present ( & supported ) by the payment processor object.
440 * @param string $method method to check for.
445 function isSupported($method = 'cancelSubscription') {
446 if ($this->_paymentProcessor
['payment_processor_type'] != 'PayPal') {
447 // since subscription methods like cancelSubscription or updateBilling is not yet implemented / supported
448 // by standard or express.
451 return parent
::isSupported($method);
455 * @param string $message
456 * @param array $params
458 * @return array|bool|object
460 function cancelSubscription(&$message = '', $params = array(
462 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal') {
464 $this->initialize($args, 'ManageRecurringPaymentsProfileStatus');
466 $args['PROFILEID'] = CRM_Utils_Array
::value('subscriptionId', $params);
467 $args['ACTION'] = 'Cancel';
468 $args['NOTE'] = CRM_Utils_Array
::value('reason', $params);
470 $result = $this->invokeAPI($args);
471 if (is_a($result, 'CRM_Core_Error')) {
474 $message = "{$result['ack']}: profileid={$result['profileid']}";
481 * @param string $message
482 * @param array $params
484 * @return array|bool|object
486 function updateSubscriptionBillingInfo(&$message = '', $params = array(
488 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal') {
489 $config = CRM_Core_Config
::singleton();
491 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
493 $args['PROFILEID'] = $params['subscriptionId'];
494 $args['AMT'] = $params['amount'];
495 $args['CURRENCYCODE'] = $config->defaultCurrency
;
496 $args['CREDITCARDTYPE'] = $params['credit_card_type'];
497 $args['ACCT'] = $params['credit_card_number'];
498 $args['EXPDATE'] = sprintf('%02d', $params['month']) . $params['year'];
499 $args['CVV2'] = $params['cvv2'];
501 $args['FIRSTNAME'] = $params['first_name'];
502 $args['LASTNAME'] = $params['last_name'];
503 $args['STREET'] = $params['street_address'];
504 $args['CITY'] = $params['city'];
505 $args['STATE'] = $params['state_province'];
506 $args['COUNTRYCODE'] = $params['postal_code'];
507 $args['ZIP'] = $params['country'];
509 $result = $this->invokeAPI($args);
510 if (is_a($result, 'CRM_Core_Error')) {
513 $message = "{$result['ack']}: profileid={$result['profileid']}";
520 * @param string $message
521 * @param array $params
523 * @return array|bool|object
525 function changeSubscriptionAmount(&$message = '', $params = array()) {
526 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal') {
527 $config = CRM_Core_Config
::singleton();
529 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
531 $args['PROFILEID'] = $params['subscriptionId'];
532 $args['AMT'] = $params['amount'];
533 $args['CURRENCYCODE'] = $config->defaultCurrency
;
534 $args['BILLINGFREQUENCY'] = $params['installments'];
536 $result = $this->invokeAPI($args);
537 CRM_Core_Error
::debug_var('$result', $result);
538 if (is_a($result, 'CRM_Core_Error')) {
541 $message = "{$result['ack']}: profileid={$result['profileid']}";
549 * @param string $component
553 function doTransferCheckout(&$params, $component = 'contribute') {
554 $config = CRM_Core_Config
::singleton();
556 if ($component != 'contribute' && $component != 'event') {
557 CRM_Core_Error
::fatal(ts('Component is invalid'));
560 $notifyURL = $config->userFrameworkResourceURL
. "extern/ipn.php?reset=1&contactID={$params['contactID']}" . "&contributionID={$params['contributionID']}" . "&module={$component}";
562 if ($component == 'event') {
563 $notifyURL .= "&eventID={$params['eventID']}&participantID={$params['participantID']}";
566 $membershipID = CRM_Utils_Array
::value('membershipID', $params);
568 $notifyURL .= "&membershipID=$membershipID";
570 $relatedContactID = CRM_Utils_Array
::value('related_contact', $params);
571 if ($relatedContactID) {
572 $notifyURL .= "&relatedContactID=$relatedContactID";
574 $onBehalfDupeAlert = CRM_Utils_Array
::value('onbehalf_dupe_alert', $params);
575 if ($onBehalfDupeAlert) {
576 $notifyURL .= "&onBehalfDupeAlert=$onBehalfDupeAlert";
581 $url = ($component == 'event') ?
'civicrm/event/register' : 'civicrm/contribute/transact';
582 $cancel = ($component == 'event') ?
'_qf_Register_display' : '_qf_Main_display';
583 $returnURL = CRM_Utils_System
::url($url,
584 "_qf_ThankYou_display=1&qfKey={$params['qfKey']}",
588 $cancelUrlString = "$cancel=1&cancel=1&qfKey={$params['qfKey']}";
589 if (!empty($params['is_recur'])) {
590 $cancelUrlString .= "&isRecur=1&recurId={$params['contributionRecurID']}&contribId={$params['contributionID']}";
593 $cancelURL = CRM_Utils_System
::url(
599 // ensure that the returnURL is absolute.
600 if (substr($returnURL, 0, 4) != 'http') {
601 $fixUrl = CRM_Utils_System
::url("civicrm/admin/setting/url", '&reset=1');
602 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)));
605 $paypalParams = array(
606 'business' => $this->_paymentProcessor
['user_name'],
607 'notify_url' => $notifyURL,
608 'item_name' => $params['item_name'],
610 'undefined_quantity' => 0,
611 'cancel_return' => $cancelURL,
614 'return' => $returnURL,
616 'currency_code' => $params['currencyID'],
617 'invoice' => $params['invoiceID'],
618 'lc' => substr($config->lcMessages
, -2),
619 'charset' => function_exists('mb_internal_encoding') ?
mb_internal_encoding() : 'UTF-8',
620 'custom' => CRM_Utils_Array
::value('accountingCode', $params),
621 'bn' => 'CiviCRM_SP',
624 // add name and address if available, CRM-3130
626 'first_name' => 'first_name',
627 'last_name' => 'last_name',
628 'street_address' => 'address1',
629 'country' => 'country',
630 'preferred_language' => 'lc',
632 'state_province' => 'state',
633 'postal_code' => 'zip',
637 foreach (array_keys($params) as $p) {
638 // get the base name without the location type suffixed to it
639 $parts = explode('-', $p);
640 $name = count($parts) > 1 ?
$parts[0] : $p;
641 if (isset($otherVars[$name])) {
642 $value = $params[$p];
644 if ($name == 'state_province') {
645 $stateName = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($value);
648 if ($name == 'country') {
649 $countryName = CRM_Core_PseudoConstant
::countryIsoCode($value);
650 $value = $countryName;
652 // ensure value is not an array
654 if (!is_array($value)) {
655 $paypalParams[$otherVars[$name]] = $value;
661 // if recurring donations, add a few more items
662 if (!empty($params['is_recur'])) {
663 if ($params['contributionRecurID']) {
664 $notifyURL .= "&contributionRecurID={$params['contributionRecurID']}&contributionPageID={$params['contributionPageID']}";
665 $paypalParams['notify_url'] = $notifyURL;
668 CRM_Core_Error
::fatal(ts('Recurring contribution, but no database id'));
671 $paypalParams +
= array(
672 'cmd' => '_xclick-subscriptions',
673 'a3' => $params['amount'],
674 'p3' => $params['frequency_interval'],
675 't3' => ucfirst(substr($params['frequency_unit'], 0, 1)),
678 'srt' => CRM_Utils_Array
::value('installments', $params),
684 $paypalParams +
= array(
686 'amount' => $params['amount'],
690 // Allow further manipulation of the arguments via custom hooks ..
691 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $paypalParams);
694 foreach ($paypalParams as $key => $value) {
695 if ($value === NULL) {
699 $value = urlencode($value);
700 if ($key == 'return' ||
701 $key == 'cancel_return' ||
704 $value = str_replace('%2F', '/', $value);
706 $uri .= "&{$key}={$value}";
709 $uri = substr($uri, 1);
710 $url = $this->_paymentProcessor
['url_site'];
711 $sub = empty($params['is_recur']) ?
'cgi-bin/webscr' : 'subscriptions';
712 $paypalURL = "{$url}{$sub}?$uri";
714 CRM_Utils_System
::redirect($paypalURL);
718 * hash_call: Function to perform the API call to PayPal using API signature
719 * @methodName is name of API method.
720 * @nvpStr is nvp string.
721 * returns an associtive array containing the response from the server.
723 function invokeAPI($args, $url = NULL) {
726 if (empty($this->_paymentProcessor
['url_api'])) {
727 CRM_Core_Error
::fatal(ts('Please set the API URL. Please refer to the documentation for more details'));
730 $url = $this->_paymentProcessor
['url_api'] . 'nvp';
733 if (!function_exists('curl_init')) {
734 CRM_Core_Error
::fatal("curl functions NOT available.");
737 //setting the curl parameters.
739 curl_setopt($ch, CURLOPT_URL
, $url);
740 curl_setopt($ch, CURLOPT_VERBOSE
, 1);
742 //turning off the server and peer verification(TrustManager Concept).
743 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'verifySSL'));
744 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST
, CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'verifySSL') ?
2 : 0);
746 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, 1);
747 curl_setopt($ch, CURLOPT_POST
, 1);
750 foreach ($args as $n => $v) {
751 $p[] = "$n=" . urlencode($v);
754 //NVPRequest for submitting to server
755 $nvpreq = implode('&', $p);
757 //setting the nvpreq as POST FIELD to curl
758 curl_setopt($ch, CURLOPT_POSTFIELDS
, $nvpreq);
760 //getting response from server
761 $response = curl_exec($ch);
763 //converting NVPResponse to an Associative Array
764 $result = self
::deformat($response);
766 if (curl_errno($ch)) {
767 $e = CRM_Core_Error
::singleton();
768 $e->push(curl_errno($ch),
778 if (strtolower($result['ack']) != 'success' &&
779 strtolower($result['ack']) != 'successwithwarning'
781 $e = CRM_Core_Error
::singleton();
782 $e->push($result['l_errorcode0'],
784 "{$result['l_shortmessage0']} {$result['l_longmessage0']}"
792 /** This function will take NVPString and convert it to an Associative Array and it will decode the response.
793 * It is usefull to search for a particular key and displaying arrays.
794 * @nvpstr is NVPString.
795 * @nvpArray is Associative Array.
797 static function deformat($str) {
800 while (strlen($str)) {
802 $keyPos = strpos($str, '=');
805 $valPos = strpos($str, '&') ?
strpos($str, '&') : strlen($str);
807 /*getting the Key and Value values and storing in a Associative Array*/
809 $key = substr($str, 0, $keyPos);
810 $val = substr($str, $keyPos +
1, $valPos - $keyPos - 1);
812 //decoding the respose
813 $result[strtolower(urldecode($key))] = urldecode($val);
814 $str = substr($str, $valPos +
1, strlen($str));