3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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 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 * 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 public 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 * Are back office payments supported - e.g paypal standard won't permit you to enter a credit card associated with someone else's login
101 protected function supportsBackOffice() {
102 if ($this->_processorName
== ts('PayPal Pro')) {
108 * Express checkout code. Check PayPal documentation for more information
110 * @param array $params assoc array of input parameters for this transaction
112 * @return array the result in an nice formatted array (or an error object)
114 public function setExpressCheckOut(&$params) {
117 $this->initialize($args, 'SetExpressCheckout');
119 $args['paymentAction'] = $params['payment_action'];
120 $args['amt'] = $params['amount'];
121 $args['currencyCode'] = $params['currencyID'];
122 $args['desc'] = CRM_Utils_Array
::value('description', $params);
123 $args['invnum'] = $params['invoiceID'];
124 $args['returnURL'] = $params['returnURL'];
125 $args['cancelURL'] = $params['cancelURL'];
126 $args['version'] = '56.0';
128 //LCD if recurring, collect additional data and set some values
129 if (!empty($params['is_recur'])) {
130 $args['L_BILLINGTYPE0'] = 'RecurringPayments';
131 //$args['L_BILLINGAGREEMENTDESCRIPTION0'] = 'Recurring Contribution';
132 $args['L_BILLINGAGREEMENTDESCRIPTION0'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
133 $args['L_PAYMENTTYPE0'] = 'Any';
136 // Allow further manipulation of the arguments via custom hooks ..
137 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $args);
139 $result = $this->invokeAPI($args);
141 if (is_a($result, 'CRM_Core_Error')) {
147 return $result['token'];
151 * Get details from paypal. Check PayPal documentation for more information
153 * @param string $token the key associated with this transaction
155 * @return array the result in an nice formatted array (or an error object)
157 public function getExpressCheckoutDetails($token) {
160 $this->initialize($args, 'GetExpressCheckoutDetails');
161 $args['token'] = $token;
163 $args['method'] = 'GetExpressCheckoutDetails';
165 $result = $this->invokeAPI($args);
167 if (is_a($result, 'CRM_Core_Error')) {
174 $params['token'] = $result['token'];
175 $params['payer_id'] = $result['payerid'];
176 $params['payer_status'] = $result['payerstatus'];
177 $params['first_name'] = $result['firstname'];
178 $params['middle_name'] = CRM_Utils_Array
::value('middlename', $result);
179 $params['last_name'] = $result['lastname'];
180 $params['street_address'] = $result['shiptostreet'];
181 $params['supplemental_address_1'] = CRM_Utils_Array
::value('shiptostreet2', $result);
182 $params['city'] = $result['shiptocity'];
183 $params['state_province'] = $result['shiptostate'];
184 $params['postal_code'] = $result['shiptozip'];
185 $params['country'] = $result['shiptocountrycode'];
191 * Do the express checkout at paypal. Check PayPal documentation for more information
193 * @param array $params
195 * @internal param string $token the key associated with this transaction
197 * @return array the result in an nice formatted array (or an error object)
199 public function doExpressCheckout(&$params) {
202 $this->initialize($args, 'DoExpressCheckoutPayment');
204 $args['token'] = $params['token'];
205 $args['paymentAction'] = $params['payment_action'];
206 $args['amt'] = $params['amount'];
207 $args['currencyCode'] = $params['currencyID'];
208 $args['payerID'] = $params['payer_id'];
209 $args['invnum'] = $params['invoiceID'];
210 $args['returnURL'] = CRM_Utils_Array
::value('returnURL', $params);
211 $args['cancelURL'] = CRM_Utils_Array
::value('cancelURL', $params);
212 $args['desc'] = $params['description'];
214 $result = $this->invokeAPI($args);
216 if (is_a($result, 'CRM_Core_Error')) {
222 $params['trxn_id'] = $result['transactionid'];
223 $params['gross_amount'] = $result['amt'];
224 $params['fee_amount'] = $result['feeamt'];
225 $params['net_amount'] = CRM_Utils_Array
::value('settleamt', $result);
226 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
227 $params['net_amount'] = $params['gross_amount'] - $params['fee_amount'];
229 $params['payment_status'] = $result['paymentstatus'];
230 $params['pending_reason'] = $result['pendingreason'];
235 //LCD add new function for handling recurring payments for PayPal Express
237 * @param array $params
241 public function createRecurringPayments(&$params) {
244 $this->initialize($args, 'CreateRecurringPaymentsProfile');
246 $start_time = strtotime(date('m/d/Y'));
247 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
249 $args['token'] = $params['token'];
250 $args['paymentAction'] = $params['payment_action'];
251 $args['amt'] = $params['amount'];
252 $args['currencyCode'] = $params['currencyID'];
253 $args['payerID'] = $params['payer_id'];
254 $args['invnum'] = $params['invoiceID'];
255 $args['returnURL'] = $params['returnURL'];
256 $args['cancelURL'] = $params['cancelURL'];
257 $args['profilestartdate'] = $start_date;
258 $args['method'] = 'CreateRecurringPaymentsProfile';
259 $args['billingfrequency'] = $params['frequency_interval'];
260 $args['billingperiod'] = ucwords($params['frequency_unit']);
261 $args['desc'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
262 //$args['desc'] = 'Recurring Contribution';
263 $args['totalbillingcycles'] = $params['installments'];
264 $args['version'] = '56.0';
265 $args['profilereference'] =
266 "i={$params['invoiceID']}" .
268 "&c={$params['contactID']}" .
269 "&r={$params['contributionRecurID']}" .
270 "&b={$params['contributionID']}" .
271 "&p={$params['contributionPageID']}";
273 $result = $this->invokeAPI($args);
275 if (is_a($result, 'CRM_Core_Error')) {
281 $params['trxn_id'] = $result['transactionid'];
282 $params['gross_amount'] = $result['amt'];
283 $params['fee_amount'] = $result['feeamt'];
284 $params['net_amount'] = $result['settleamt'];
285 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
286 $params['net_amount'] = $params['gross_amount'] - $params['fee_amount'];
288 $params['payment_status'] = $result['paymentstatus'];
289 $params['pending_reason'] = $result['pendingreason'];
298 public function initialize(&$args, $method) {
299 $args['user'] = $this->_paymentProcessor
['user_name'];
300 $args['pwd'] = $this->_paymentProcessor
['password'];
301 $args['version'] = 3.0;
302 $args['signature'] = $this->_paymentProcessor
['signature'];
303 $args['subject'] = CRM_Utils_Array
::value('subject', $this->_paymentProcessor
);
304 $args['method'] = $method;
308 * This function collects all the information from a web/api form and invokes
309 * the relevant payment processor specific functions to perform the transaction
311 * @param array $params assoc array of input parameters for this transaction
313 * @param string $component
314 * @return array the result in an nice formatted array (or an error object)
316 public function doDirectPayment(&$params, $component = 'contribute') {
319 $this->initialize($args, 'DoDirectPayment');
321 $args['paymentAction'] = $params['payment_action'];
322 $args['amt'] = $params['amount'];
323 $args['currencyCode'] = $params['currencyID'];
324 $args['invnum'] = $params['invoiceID'];
325 $args['ipaddress'] = $params['ip_address'];
326 $args['creditCardType'] = $params['credit_card_type'];
327 $args['acct'] = $params['credit_card_number'];
328 $args['expDate'] = sprintf('%02d', $params['month']) . $params['year'];
329 $args['cvv2'] = $params['cvv2'];
330 $args['firstName'] = $params['first_name'];
331 $args['lastName'] = $params['last_name'];
332 $args['email'] = CRM_Utils_Array
::value('email', $params);
333 $args['street'] = $params['street_address'];
334 $args['city'] = $params['city'];
335 $args['state'] = $params['state_province'];
336 $args['countryCode'] = $params['country'];
337 $args['zip'] = $params['postal_code'];
338 $args['desc'] = substr(CRM_Utils_Array
::value('description', $params), 0, 127);
339 $args['custom'] = CRM_Utils_Array
::value('accountingCode', $params);
341 if (CRM_Utils_Array
::value('is_recur', $params) == 1) {
342 $start_time = strtotime(date('m/d/Y'));
343 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
345 $args['PaymentAction'] = 'Sale';
346 $args['billingperiod'] = ucwords($params['frequency_unit']);
347 $args['billingfrequency'] = $params['frequency_interval'];
348 $args['method'] = "CreateRecurringPaymentsProfile";
349 $args['profilestartdate'] = $start_date;
351 $params['description'] . ": " .
352 $params['amount'] . " Per " .
353 $params['frequency_interval'] . " " .
354 $params['frequency_unit'];
355 $args['amt'] = $params['amount'];
356 $args['totalbillingcycles'] = $params['installments'];
357 $args['version'] = 56.0;
358 $args['PROFILEREFERENCE'] =
359 "i=" . $params['invoiceID'] . "&m=" . $component .
360 "&c=" . $params['contactID'] . "&r=" . $params['contributionRecurID'] .
361 "&b=" . $params['contributionID'] . "&p=" . $params['contributionPageID'];
364 // Allow further manipulation of the arguments via custom hooks ..
365 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $args);
367 $result = $this->invokeAPI($args);
370 if (is_a($result, 'CRM_Core_Error')) {
374 $params['recurr_profile_id'] = NULL;
376 if (CRM_Utils_Array
::value('is_recur', $params) == 1) {
377 $params['recurr_profile_id'] = $result['profileid'];
382 $params['trxn_id'] = CRM_Utils_Array
::value('transactionid', $result);
383 $params['gross_amount'] = CRM_Utils_Array
::value('amt', $result);
388 * This function checks to see if we have the right config values
390 * @return string the error message if any
392 public function checkConfig() {
394 $paymentProcessorType = CRM_Core_PseudoConstant
::paymentProcessorType(false, null, 'name');
396 $this->_paymentProcessor
['payment_processor_type_id'] == CRM_Utils_Array
::key('PayPal_Standard', $paymentProcessorType) ||
397 $this->_paymentProcessor
['payment_processor_type_id'] == CRM_Utils_Array
::key('PayPal', $paymentProcessorType)
399 if (empty($this->_paymentProcessor
['user_name'])) {
400 $error[] = ts('User Name is not set in the Administer » System Settings » Payment Processors.');
404 if ($this->_paymentProcessor
['payment_processor_type_id'] != CRM_Utils_Array
::key('PayPal_Standard', $paymentProcessorType)) {
405 if (empty($this->_paymentProcessor
['signature'])) {
406 $error[] = ts('Signature is not set in the Administer » System Settings » Payment Processors.');
409 if (empty($this->_paymentProcessor
['password'])) {
410 $error[] = ts('Password is not set in the Administer » System Settings » Payment Processors.');
414 if (!empty($error)) {
415 return implode('<p>', $error);
423 * @return null|string
425 public function cancelSubscriptionURL() {
426 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal_Standard') {
427 return "{$this->_paymentProcessor['url_site']}cgi-bin/webscr?cmd=_subscr-find&alias=" . urlencode($this->_paymentProcessor
['user_name']);
435 * Check whether a method is present ( & supported ) by the payment processor object.
437 * @param string $method method to check for.
441 public function isSupported($method = 'cancelSubscription') {
442 if ($this->_paymentProcessor
['payment_processor_type'] != 'PayPal') {
443 // since subscription methods like cancelSubscription or updateBilling is not yet implemented / supported
444 // by standard or express.
447 return parent
::isSupported($method);
451 * @param string $message
452 * @param array $params
454 * @return array|bool|object
456 public function cancelSubscription(&$message = '', $params = array()) {
457 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal') {
459 $this->initialize($args, 'ManageRecurringPaymentsProfileStatus');
461 $args['PROFILEID'] = CRM_Utils_Array
::value('subscriptionId', $params);
462 $args['ACTION'] = 'Cancel';
463 $args['NOTE'] = CRM_Utils_Array
::value('reason', $params);
465 $result = $this->invokeAPI($args);
466 if (is_a($result, 'CRM_Core_Error')) {
469 $message = "{$result['ack']}: profileid={$result['profileid']}";
476 * @param string $message
477 * @param array $params
479 * @return array|bool|object
481 public function updateSubscriptionBillingInfo(&$message = '', $params = array()) {
482 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal') {
483 $config = CRM_Core_Config
::singleton();
485 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
487 $args['PROFILEID'] = $params['subscriptionId'];
488 $args['AMT'] = $params['amount'];
489 $args['CURRENCYCODE'] = $config->defaultCurrency
;
490 $args['CREDITCARDTYPE'] = $params['credit_card_type'];
491 $args['ACCT'] = $params['credit_card_number'];
492 $args['EXPDATE'] = sprintf('%02d', $params['month']) . $params['year'];
493 $args['CVV2'] = $params['cvv2'];
495 $args['FIRSTNAME'] = $params['first_name'];
496 $args['LASTNAME'] = $params['last_name'];
497 $args['STREET'] = $params['street_address'];
498 $args['CITY'] = $params['city'];
499 $args['STATE'] = $params['state_province'];
500 $args['COUNTRYCODE'] = $params['postal_code'];
501 $args['ZIP'] = $params['country'];
503 $result = $this->invokeAPI($args);
504 if (is_a($result, 'CRM_Core_Error')) {
507 $message = "{$result['ack']}: profileid={$result['profileid']}";
514 * @param string $message
515 * @param array $params
517 * @return array|bool|object
519 public function changeSubscriptionAmount(&$message = '', $params = array()) {
520 if ($this->_paymentProcessor
['payment_processor_type'] == 'PayPal') {
521 $config = CRM_Core_Config
::singleton();
523 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
525 $args['PROFILEID'] = $params['subscriptionId'];
526 $args['AMT'] = $params['amount'];
527 $args['CURRENCYCODE'] = $config->defaultCurrency
;
528 $args['BILLINGFREQUENCY'] = $params['installments'];
530 $result = $this->invokeAPI($args);
531 CRM_Core_Error
::debug_var('$result', $result);
532 if (is_a($result, 'CRM_Core_Error')) {
535 $message = "{$result['ack']}: profileid={$result['profileid']}";
542 * @param array $params
543 * @param string $component
547 public function doTransferCheckout(&$params, $component = 'contribute') {
548 $config = CRM_Core_Config
::singleton();
550 if ($component != 'contribute' && $component != 'event') {
551 CRM_Core_Error
::fatal(ts('Component is invalid'));
554 $notifyURL = $config->userFrameworkResourceURL
. "extern/ipn.php?reset=1&contactID={$params['contactID']}" . "&contributionID={$params['contributionID']}" . "&module={$component}";
556 if ($component == 'event') {
557 $notifyURL .= "&eventID={$params['eventID']}&participantID={$params['participantID']}";
560 $membershipID = CRM_Utils_Array
::value('membershipID', $params);
562 $notifyURL .= "&membershipID=$membershipID";
564 $relatedContactID = CRM_Utils_Array
::value('related_contact', $params);
565 if ($relatedContactID) {
566 $notifyURL .= "&relatedContactID=$relatedContactID";
568 $onBehalfDupeAlert = CRM_Utils_Array
::value('onbehalf_dupe_alert', $params);
569 if ($onBehalfDupeAlert) {
570 $notifyURL .= "&onBehalfDupeAlert=$onBehalfDupeAlert";
575 $url = ($component == 'event') ?
'civicrm/event/register' : 'civicrm/contribute/transact';
576 $cancel = ($component == 'event') ?
'_qf_Register_display' : '_qf_Main_display';
577 $returnURL = CRM_Utils_System
::url($url,
578 "_qf_ThankYou_display=1&qfKey={$params['qfKey']}",
582 $cancelUrlString = "$cancel=1&cancel=1&qfKey={$params['qfKey']}";
583 if (!empty($params['is_recur'])) {
584 $cancelUrlString .= "&isRecur=1&recurId={$params['contributionRecurID']}&contribId={$params['contributionID']}";
587 $cancelURL = CRM_Utils_System
::url(
593 // ensure that the returnURL is absolute.
594 if (substr($returnURL, 0, 4) != 'http') {
595 $fixUrl = CRM_Utils_System
::url("civicrm/admin/setting/url", '&reset=1');
596 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)));
599 $paypalParams = array(
600 'business' => $this->_paymentProcessor
['user_name'],
601 'notify_url' => $notifyURL,
602 'item_name' => $params['item_name'],
604 'undefined_quantity' => 0,
605 'cancel_return' => $cancelURL,
608 'return' => $returnURL,
610 'currency_code' => $params['currencyID'],
611 'invoice' => $params['invoiceID'],
612 'lc' => substr($config->lcMessages
, -2),
613 'charset' => function_exists('mb_internal_encoding') ?
mb_internal_encoding() : 'UTF-8',
614 'custom' => CRM_Utils_Array
::value('accountingCode',
619 // add name and address if available, CRM-3130
621 'first_name' => 'first_name',
622 'last_name' => 'last_name',
623 'street_address' => 'address1',
624 'country' => 'country',
625 'preferred_language' => 'lc',
627 'state_province' => 'state',
628 'postal_code' => 'zip',
632 foreach (array_keys($params) as $p) {
633 // get the base name without the location type suffixed to it
634 $parts = explode('-', $p);
635 $name = count($parts) > 1 ?
$parts[0] : $p;
636 if (isset($otherVars[$name])) {
637 $value = $params[$p];
639 if ($name == 'state_province') {
640 $stateName = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($value);
643 if ($name == 'country') {
644 $countryName = CRM_Core_PseudoConstant
::countryIsoCode($value);
645 $value = $countryName;
647 // ensure value is not an array
649 if (!is_array($value)) {
650 $paypalParams[$otherVars[$name]] = $value;
656 // if recurring donations, add a few more items
657 if (!empty($params['is_recur'])) {
658 if ($params['contributionRecurID']) {
659 $notifyURL .= "&contributionRecurID={$params['contributionRecurID']}&contributionPageID={$params['contributionPageID']}";
660 $paypalParams['notify_url'] = $notifyURL;
663 CRM_Core_Error
::fatal(ts('Recurring contribution, but no database id'));
666 $paypalParams +
= array(
667 'cmd' => '_xclick-subscriptions',
668 'a3' => $params['amount'],
669 'p3' => $params['frequency_interval'],
670 't3' => ucfirst(substr($params['frequency_unit'], 0, 1)),
673 'srt' => CRM_Utils_Array
::value('installments', $params),
679 $paypalParams +
= array(
681 'amount' => $params['amount'],
685 // Allow further manipulation of the arguments via custom hooks ..
686 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $paypalParams);
689 foreach ($paypalParams as $key => $value) {
690 if ($value === NULL) {
694 $value = urlencode($value);
695 if ($key == 'return' ||
696 $key == 'cancel_return' ||
699 $value = str_replace('%2F', '/', $value);
701 $uri .= "&{$key}={$value}";
704 $uri = substr($uri, 1);
705 $url = $this->_paymentProcessor
['url_site'];
706 $sub = empty($params['is_recur']) ?
'cgi-bin/webscr' : 'subscriptions';
707 $paypalURL = "{$url}{$sub}?$uri";
709 CRM_Utils_System
::redirect($paypalURL);
713 * Hash_call: Function to perform the API call to PayPal using API signature
714 * @methodName is name of API method.
715 * @nvpStr is nvp string.
716 * returns an associtive array containing the response from the server.
718 public function invokeAPI($args, $url = NULL) {
721 if (empty($this->_paymentProcessor
['url_api'])) {
722 CRM_Core_Error
::fatal(ts('Please set the API URL. Please refer to the documentation for more details'));
725 $url = $this->_paymentProcessor
['url_api'] . 'nvp';
728 if (!function_exists('curl_init')) {
729 CRM_Core_Error
::fatal("curl functions NOT available.");
732 //setting the curl parameters.
734 curl_setopt($ch, CURLOPT_URL
, $url);
735 curl_setopt($ch, CURLOPT_VERBOSE
, 1);
737 //turning off the server and peer verification(TrustManager Concept).
738 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'verifySSL'));
739 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST
, CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'verifySSL') ?
2 : 0);
741 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, 1);
742 curl_setopt($ch, CURLOPT_POST
, 1);
745 foreach ($args as $n => $v) {
746 $p[] = "$n=" . urlencode($v);
749 //NVPRequest for submitting to server
750 $nvpreq = implode('&', $p);
752 //setting the nvpreq as POST FIELD to curl
753 curl_setopt($ch, CURLOPT_POSTFIELDS
, $nvpreq);
755 //getting response from server
756 $response = curl_exec($ch);
758 //converting NVPResponse to an Associative Array
759 $result = self
::deformat($response);
761 if (curl_errno($ch)) {
762 $e = CRM_Core_Error
::singleton();
763 $e->push(curl_errno($ch),
773 if (strtolower($result['ack']) != 'success' &&
774 strtolower($result['ack']) != 'successwithwarning'
776 $e = CRM_Core_Error
::singleton();
777 $e->push($result['l_errorcode0'],
779 "{$result['l_shortmessage0']} {$result['l_longmessage0']}"
787 /** This function will take NVPString and convert it to an Associative Array and it will decode the response.
788 * It is usefull to search for a particular key and displaying arrays.
789 * @nvpstr is NVPString.
790 * @nvpArray is Associative Array.
792 public static function deformat($str) {
795 while (strlen($str)) {
797 $keyPos = strpos($str, '=');
800 $valPos = strpos($str, '&') ?
strpos($str, '&') : strlen($str);
802 /*getting the Key and Value values and storing in a Associative Array*/
804 $key = substr($str, 0, $keyPos);
805 $val = substr($str, $keyPos +
1, $valPos - $keyPos - 1);
807 //decoding the respose
808 $result[strtolower(urldecode($key))] = urldecode($val);
809 $str = substr($str, $valPos +
1, strlen($str));