Merge pull request #4981 from totten/master-cbf2
[civicrm-core.git] / CRM / Core / Payment / PayPalImpl.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2014
32 * $Id$
33 *
34 */
35 class CRM_Core_Payment_PayPalImpl extends CRM_Core_Payment {
36 const CHARSET = 'iso-8859-1';
37
38 protected $_mode = NULL;
39
40 /**
41 * We only need one instance of this object. So we use the singleton
42 * pattern and cache the instance in this variable
43 *
44 * @var object
45 */
46 static private $_singleton = NULL;
47
48 /**
49 * Constructor
50 *
51 * @param string $mode
52 * The mode of operation: live or test.
53 *
54 * @param $paymentProcessor
55 *
56 * @return \CRM_Core_Payment_PayPalImpl
57 */
58 public function __construct($mode, &$paymentProcessor) {
59 $this->_mode = $mode;
60 $this->_paymentProcessor = $paymentProcessor;
61 $this->_processorName = ts('PayPal Pro');
62 $paymentProcessorType = CRM_Core_PseudoConstant::paymentProcessorType(FALSE, NULL, 'name');
63
64 if ($this->_paymentProcessor['payment_processor_type_id'] == CRM_Utils_Array::key('PayPal_Standard', $paymentProcessorType)) {
65 $this->_processorName = ts('PayPal Standard');
66 return;
67 }
68 elseif ($this->_paymentProcessor['payment_processor_type_id'] == CRM_Utils_Array::key('PayPal_Express', $paymentProcessorType)) {
69 $this->_processorName = ts('PayPal Express');
70 }
71
72 if (!$this->_paymentProcessor['user_name']) {
73 CRM_Core_Error::fatal(ts('Could not find user name for payment processor'));
74 }
75 }
76
77 /**
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
79 * @return bool
80 */
81 protected function supportsBackOffice() {
82 if ($this->_processorName == ts('PayPal Pro')) {
83 return TRUE;
84 }
85 return FALSE;
86 }
87
88 /**
89 * Express checkout code. Check PayPal documentation for more information
90 *
91 * @param array $params
92 * Assoc array of input parameters for this transaction.
93 *
94 * @return array
95 * the result in an nice formatted array (or an error object)
96 */
97 public function setExpressCheckOut(&$params) {
98 $args = array();
99
100 $this->initialize($args, 'SetExpressCheckout');
101
102 $args['paymentAction'] = $params['payment_action'];
103 $args['amt'] = $params['amount'];
104 $args['currencyCode'] = $params['currencyID'];
105 $args['desc'] = CRM_Utils_Array::value('description', $params);
106 $args['invnum'] = $params['invoiceID'];
107 $args['returnURL'] = $params['returnURL'];
108 $args['cancelURL'] = $params['cancelURL'];
109 $args['version'] = '56.0';
110
111 //LCD if recurring, collect additional data and set some values
112 if (!empty($params['is_recur'])) {
113 $args['L_BILLINGTYPE0'] = 'RecurringPayments';
114 //$args['L_BILLINGAGREEMENTDESCRIPTION0'] = 'Recurring Contribution';
115 $args['L_BILLINGAGREEMENTDESCRIPTION0'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
116 $args['L_PAYMENTTYPE0'] = 'Any';
117 }
118
119 // Allow further manipulation of the arguments via custom hooks ..
120 CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $args);
121
122 $result = $this->invokeAPI($args);
123
124 if (is_a($result, 'CRM_Core_Error')) {
125 return $result;
126 }
127
128 /* Success */
129
130 return $result['token'];
131 }
132
133 /**
134 * Get details from paypal. Check PayPal documentation for more information
135 *
136 * @param string $token
137 * The key associated with this transaction.
138 *
139 * @return array
140 * the result in an nice formatted array (or an error object)
141 */
142 public function getExpressCheckoutDetails($token) {
143 $args = array();
144
145 $this->initialize($args, 'GetExpressCheckoutDetails');
146 $args['token'] = $token;
147 // LCD
148 $args['method'] = 'GetExpressCheckoutDetails';
149
150 $result = $this->invokeAPI($args);
151
152 if (is_a($result, 'CRM_Core_Error')) {
153 return $result;
154 }
155
156 /* Success */
157
158 $params = array();
159 $params['token'] = $result['token'];
160 $params['payer_id'] = $result['payerid'];
161 $params['payer_status'] = $result['payerstatus'];
162 $params['first_name'] = $result['firstname'];
163 $params['middle_name'] = CRM_Utils_Array::value('middlename', $result);
164 $params['last_name'] = $result['lastname'];
165 $params['street_address'] = $result['shiptostreet'];
166 $params['supplemental_address_1'] = CRM_Utils_Array::value('shiptostreet2', $result);
167 $params['city'] = $result['shiptocity'];
168 $params['state_province'] = $result['shiptostate'];
169 $params['postal_code'] = $result['shiptozip'];
170 $params['country'] = $result['shiptocountrycode'];
171
172 return $params;
173 }
174
175 /**
176 * Do the express checkout at paypal. Check PayPal documentation for more information
177 *
178 * @param array $params
179 *
180 * @internal param string $token the key associated with this transaction
181 *
182 * @return array
183 * the result in an nice formatted array (or an error object)
184 */
185 public function doExpressCheckout(&$params) {
186 $args = array();
187
188 $this->initialize($args, 'DoExpressCheckoutPayment');
189
190 $args['token'] = $params['token'];
191 $args['paymentAction'] = $params['payment_action'];
192 $args['amt'] = $params['amount'];
193 $args['currencyCode'] = $params['currencyID'];
194 $args['payerID'] = $params['payer_id'];
195 $args['invnum'] = $params['invoiceID'];
196 $args['returnURL'] = CRM_Utils_Array::value('returnURL', $params);
197 $args['cancelURL'] = CRM_Utils_Array::value('cancelURL', $params);
198 $args['desc'] = $params['description'];
199
200 $result = $this->invokeAPI($args);
201
202 if (is_a($result, 'CRM_Core_Error')) {
203 return $result;
204 }
205
206 /* Success */
207
208 $params['trxn_id'] = $result['transactionid'];
209 $params['gross_amount'] = $result['amt'];
210 $params['fee_amount'] = $result['feeamt'];
211 $params['net_amount'] = CRM_Utils_Array::value('settleamt', $result);
212 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
213 $params['net_amount'] = $params['gross_amount'] - $params['fee_amount'];
214 }
215 $params['payment_status'] = $result['paymentstatus'];
216 $params['pending_reason'] = $result['pendingreason'];
217
218 return $params;
219 }
220
221 //LCD add new function for handling recurring payments for PayPal Express
222 /**
223 * @param array $params
224 *
225 * @return mixed
226 */
227 public function createRecurringPayments(&$params) {
228 $args = array();
229
230 $this->initialize($args, 'CreateRecurringPaymentsProfile');
231
232 $start_time = strtotime(date('m/d/Y'));
233 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
234
235 $args['token'] = $params['token'];
236 $args['paymentAction'] = $params['payment_action'];
237 $args['amt'] = $params['amount'];
238 $args['currencyCode'] = $params['currencyID'];
239 $args['payerID'] = $params['payer_id'];
240 $args['invnum'] = $params['invoiceID'];
241 $args['returnURL'] = $params['returnURL'];
242 $args['cancelURL'] = $params['cancelURL'];
243 $args['profilestartdate'] = $start_date;
244 $args['method'] = 'CreateRecurringPaymentsProfile';
245 $args['billingfrequency'] = $params['frequency_interval'];
246 $args['billingperiod'] = ucwords($params['frequency_unit']);
247 $args['desc'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
248 //$args['desc'] = 'Recurring Contribution';
249 $args['totalbillingcycles'] = $params['installments'];
250 $args['version'] = '56.0';
251 $args['profilereference'] = "i={$params['invoiceID']}" .
252 "&m=$component" .
253 "&c={$params['contactID']}" .
254 "&r={$params['contributionRecurID']}" .
255 "&b={$params['contributionID']}" .
256 "&p={$params['contributionPageID']}";
257
258 $result = $this->invokeAPI($args);
259
260 if (is_a($result, 'CRM_Core_Error')) {
261 return $result;
262 }
263
264 /* Success */
265
266 $params['trxn_id'] = $result['transactionid'];
267 $params['gross_amount'] = $result['amt'];
268 $params['fee_amount'] = $result['feeamt'];
269 $params['net_amount'] = $result['settleamt'];
270 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
271 $params['net_amount'] = $params['gross_amount'] - $params['fee_amount'];
272 }
273 $params['payment_status'] = $result['paymentstatus'];
274 $params['pending_reason'] = $result['pendingreason'];
275
276 return $params;
277 }
278 //LCD end
279 /**
280 * @param $args
281 * @param $method
282 */
283 public function initialize(&$args, $method) {
284 $args['user'] = $this->_paymentProcessor['user_name'];
285 $args['pwd'] = $this->_paymentProcessor['password'];
286 $args['version'] = 3.0;
287 $args['signature'] = $this->_paymentProcessor['signature'];
288 $args['subject'] = CRM_Utils_Array::value('subject', $this->_paymentProcessor);
289 $args['method'] = $method;
290 }
291
292 /**
293 * This function collects all the information from a web/api form and invokes
294 * the relevant payment processor specific functions to perform the transaction
295 *
296 * @param array $params
297 * Assoc array of input parameters for this transaction.
298 *
299 * @param string $component
300 * @return array
301 * the result in an nice formatted array (or an error object)
302 */
303 public function doDirectPayment(&$params, $component = 'contribute') {
304 $args = array();
305
306 $this->initialize($args, 'DoDirectPayment');
307
308 $args['paymentAction'] = $params['payment_action'];
309 $args['amt'] = $params['amount'];
310 $args['currencyCode'] = $params['currencyID'];
311 $args['invnum'] = $params['invoiceID'];
312 $args['ipaddress'] = $params['ip_address'];
313 $args['creditCardType'] = $params['credit_card_type'];
314 $args['acct'] = $params['credit_card_number'];
315 $args['expDate'] = sprintf('%02d', $params['month']) . $params['year'];
316 $args['cvv2'] = $params['cvv2'];
317 $args['firstName'] = $params['first_name'];
318 $args['lastName'] = $params['last_name'];
319 $args['email'] = CRM_Utils_Array::value('email', $params);
320 $args['street'] = $params['street_address'];
321 $args['city'] = $params['city'];
322 $args['state'] = $params['state_province'];
323 $args['countryCode'] = $params['country'];
324 $args['zip'] = $params['postal_code'];
325 $args['desc'] = substr(CRM_Utils_Array::value('description', $params), 0, 127);
326 $args['custom'] = CRM_Utils_Array::value('accountingCode', $params);
327
328 if (CRM_Utils_Array::value('is_recur', $params) == 1) {
329 $start_time = strtotime(date('m/d/Y'));
330 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
331
332 $args['PaymentAction'] = 'Sale';
333 $args['billingperiod'] = ucwords($params['frequency_unit']);
334 $args['billingfrequency'] = $params['frequency_interval'];
335 $args['method'] = "CreateRecurringPaymentsProfile";
336 $args['profilestartdate'] = $start_date;
337 $args['desc'] = "" .
338 $params['description'] . ": " .
339 $params['amount'] . " Per " .
340 $params['frequency_interval'] . " " .
341 $params['frequency_unit'];
342 $args['amt'] = $params['amount'];
343 $args['totalbillingcycles'] = $params['installments'];
344 $args['version'] = 56.0;
345 $args['PROFILEREFERENCE'] = "" .
346 "i=" . $params['invoiceID'] . "&m=" . $component .
347 "&c=" . $params['contactID'] . "&r=" . $params['contributionRecurID'] .
348 "&b=" . $params['contributionID'] . "&p=" . $params['contributionPageID'];
349 }
350
351 // Allow further manipulation of the arguments via custom hooks ..
352 CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $args);
353
354 $result = $this->invokeAPI($args);
355
356 //WAG
357 if (is_a($result, 'CRM_Core_Error')) {
358 return $result;
359 }
360
361 $params['recurr_profile_id'] = NULL;
362
363 if (CRM_Utils_Array::value('is_recur', $params) == 1) {
364 $params['recurr_profile_id'] = $result['profileid'];
365 }
366
367 /* Success */
368
369 $params['trxn_id'] = CRM_Utils_Array::value('transactionid', $result);
370 $params['gross_amount'] = CRM_Utils_Array::value('amt', $result);
371 return $params;
372 }
373
374 /**
375 * This function checks to see if we have the right config values
376 *
377 * @return string
378 * the error message if any
379 */
380 public function checkConfig() {
381 $error = array();
382 $paymentProcessorType = CRM_Core_PseudoConstant::paymentProcessorType(FALSE, NULL, 'name');
383 if (
384 $this->_paymentProcessor['payment_processor_type_id'] == CRM_Utils_Array::key('PayPal_Standard', $paymentProcessorType) ||
385 $this->_paymentProcessor['payment_processor_type_id'] == CRM_Utils_Array::key('PayPal', $paymentProcessorType)
386 ) {
387 if (empty($this->_paymentProcessor['user_name'])) {
388 $error[] = ts('User Name is not set in the Administer &raquo; System Settings &raquo; Payment Processors.');
389 }
390 }
391
392 if ($this->_paymentProcessor['payment_processor_type_id'] != CRM_Utils_Array::key('PayPal_Standard', $paymentProcessorType)) {
393 if (empty($this->_paymentProcessor['signature'])) {
394 $error[] = ts('Signature is not set in the Administer &raquo; System Settings &raquo; Payment Processors.');
395 }
396
397 if (empty($this->_paymentProcessor['password'])) {
398 $error[] = ts('Password is not set in the Administer &raquo; System Settings &raquo; Payment Processors.');
399 }
400 }
401
402 if (!empty($error)) {
403 return implode('<p>', $error);
404 }
405 else {
406 return NULL;
407 }
408 }
409
410 /**
411 * @return null|string
412 */
413 public function cancelSubscriptionURL() {
414 if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal_Standard') {
415 return "{$this->_paymentProcessor['url_site']}cgi-bin/webscr?cmd=_subscr-find&alias=" . urlencode($this->_paymentProcessor['user_name']);
416 }
417 else {
418 return NULL;
419 }
420 }
421
422 /**
423 * Check whether a method is present ( & supported ) by the payment processor object.
424 *
425 * @param string $method
426 * Method to check for.
427 *
428 * @return bool
429 */
430 public function isSupported($method = 'cancelSubscription') {
431 if ($this->_paymentProcessor['payment_processor_type'] != 'PayPal') {
432 // since subscription methods like cancelSubscription or updateBilling is not yet implemented / supported
433 // by standard or express.
434 return FALSE;
435 }
436 return parent::isSupported($method);
437 }
438
439 /**
440 * @param string $message
441 * @param array $params
442 *
443 * @return array|bool|object
444 */
445 public function cancelSubscription(&$message = '', $params = array()) {
446 if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal') {
447 $args = array();
448 $this->initialize($args, 'ManageRecurringPaymentsProfileStatus');
449
450 $args['PROFILEID'] = CRM_Utils_Array::value('subscriptionId', $params);
451 $args['ACTION'] = 'Cancel';
452 $args['NOTE'] = CRM_Utils_Array::value('reason', $params);
453
454 $result = $this->invokeAPI($args);
455 if (is_a($result, 'CRM_Core_Error')) {
456 return $result;
457 }
458 $message = "{$result['ack']}: profileid={$result['profileid']}";
459 return TRUE;
460 }
461 return FALSE;
462 }
463
464 /**
465 * @param string $message
466 * @param array $params
467 *
468 * @return array|bool|object
469 */
470 public function updateSubscriptionBillingInfo(&$message = '', $params = array()) {
471 if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal') {
472 $config = CRM_Core_Config::singleton();
473 $args = array();
474 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
475
476 $args['PROFILEID'] = $params['subscriptionId'];
477 $args['AMT'] = $params['amount'];
478 $args['CURRENCYCODE'] = $config->defaultCurrency;
479 $args['CREDITCARDTYPE'] = $params['credit_card_type'];
480 $args['ACCT'] = $params['credit_card_number'];
481 $args['EXPDATE'] = sprintf('%02d', $params['month']) . $params['year'];
482 $args['CVV2'] = $params['cvv2'];
483
484 $args['FIRSTNAME'] = $params['first_name'];
485 $args['LASTNAME'] = $params['last_name'];
486 $args['STREET'] = $params['street_address'];
487 $args['CITY'] = $params['city'];
488 $args['STATE'] = $params['state_province'];
489 $args['COUNTRYCODE'] = $params['postal_code'];
490 $args['ZIP'] = $params['country'];
491
492 $result = $this->invokeAPI($args);
493 if (is_a($result, 'CRM_Core_Error')) {
494 return $result;
495 }
496 $message = "{$result['ack']}: profileid={$result['profileid']}";
497 return TRUE;
498 }
499 return FALSE;
500 }
501
502 /**
503 * @param string $message
504 * @param array $params
505 *
506 * @return array|bool|object
507 */
508 public function changeSubscriptionAmount(&$message = '', $params = array()) {
509 if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal') {
510 $config = CRM_Core_Config::singleton();
511 $args = array();
512 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
513
514 $args['PROFILEID'] = $params['subscriptionId'];
515 $args['AMT'] = $params['amount'];
516 $args['CURRENCYCODE'] = $config->defaultCurrency;
517 $args['BILLINGFREQUENCY'] = $params['installments'];
518
519 $result = $this->invokeAPI($args);
520 CRM_Core_Error::debug_var('$result', $result);
521 if (is_a($result, 'CRM_Core_Error')) {
522 return $result;
523 }
524 $message = "{$result['ack']}: profileid={$result['profileid']}";
525 return TRUE;
526 }
527 return FALSE;
528 }
529
530 /**
531 * @param array $params
532 * @param string $component
533 *
534 * @throws Exception
535 */
536 public function doTransferCheckout(&$params, $component = 'contribute') {
537 $config = CRM_Core_Config::singleton();
538
539 if ($component != 'contribute' && $component != 'event') {
540 CRM_Core_Error::fatal(ts('Component is invalid'));
541 }
542
543 $notifyURL = $config->userFrameworkResourceURL . "extern/ipn.php?reset=1&contactID={$params['contactID']}" . "&contributionID={$params['contributionID']}" . "&module={$component}";
544
545 if ($component == 'event') {
546 $notifyURL .= "&eventID={$params['eventID']}&participantID={$params['participantID']}";
547 }
548 else {
549 $membershipID = CRM_Utils_Array::value('membershipID', $params);
550 if ($membershipID) {
551 $notifyURL .= "&membershipID=$membershipID";
552 }
553 $relatedContactID = CRM_Utils_Array::value('related_contact', $params);
554 if ($relatedContactID) {
555 $notifyURL .= "&relatedContactID=$relatedContactID";
556
557 $onBehalfDupeAlert = CRM_Utils_Array::value('onbehalf_dupe_alert', $params);
558 if ($onBehalfDupeAlert) {
559 $notifyURL .= "&onBehalfDupeAlert=$onBehalfDupeAlert";
560 }
561 }
562 }
563
564 $url = ($component == 'event') ? 'civicrm/event/register' : 'civicrm/contribute/transact';
565 $cancel = ($component == 'event') ? '_qf_Register_display' : '_qf_Main_display';
566 $returnURL = CRM_Utils_System::url($url,
567 "_qf_ThankYou_display=1&qfKey={$params['qfKey']}",
568 TRUE, NULL, FALSE
569 );
570
571 $cancelUrlString = "$cancel=1&cancel=1&qfKey={$params['qfKey']}";
572 if (!empty($params['is_recur'])) {
573 $cancelUrlString .= "&isRecur=1&recurId={$params['contributionRecurID']}&contribId={$params['contributionID']}";
574 }
575
576 $cancelURL = CRM_Utils_System::url(
577 $url,
578 $cancelUrlString,
579 TRUE, NULL, FALSE
580 );
581
582 // ensure that the returnURL is absolute.
583 if (substr($returnURL, 0, 4) != 'http') {
584 $fixUrl = CRM_Utils_System::url("civicrm/admin/setting/url", '&reset=1');
585 CRM_Core_Error::fatal(ts('Sending a relative URL to PayPalIPN is erroneous. Please make your resource URL (in <a href="%1">Administer &raquo; System Settings &raquo; Resource URLs</a> ) complete.', array(1 => $fixUrl)));
586 }
587
588 $paypalParams = array(
589 'business' => $this->_paymentProcessor['user_name'],
590 'notify_url' => $notifyURL,
591 'item_name' => $params['item_name'],
592 'quantity' => 1,
593 'undefined_quantity' => 0,
594 'cancel_return' => $cancelURL,
595 'no_note' => 1,
596 'no_shipping' => 1,
597 'return' => $returnURL,
598 'rm' => 2,
599 'currency_code' => $params['currencyID'],
600 'invoice' => $params['invoiceID'],
601 'lc' => substr($config->lcMessages, -2),
602 'charset' => function_exists('mb_internal_encoding') ? mb_internal_encoding() : 'UTF-8',
603 'custom' => CRM_Utils_Array::value('accountingCode',
604 $params
605 ),
606 );
607
608 // add name and address if available, CRM-3130
609 $otherVars = array(
610 'first_name' => 'first_name',
611 'last_name' => 'last_name',
612 'street_address' => 'address1',
613 'country' => 'country',
614 'preferred_language' => 'lc',
615 'city' => 'city',
616 'state_province' => 'state',
617 'postal_code' => 'zip',
618 'email' => 'email',
619 );
620
621 foreach (array_keys($params) as $p) {
622 // get the base name without the location type suffixed to it
623 $parts = explode('-', $p);
624 $name = count($parts) > 1 ? $parts[0] : $p;
625 if (isset($otherVars[$name])) {
626 $value = $params[$p];
627 if ($value) {
628 if ($name == 'state_province') {
629 $stateName = CRM_Core_PseudoConstant::stateProvinceAbbreviation($value);
630 $value = $stateName;
631 }
632 if ($name == 'country') {
633 $countryName = CRM_Core_PseudoConstant::countryIsoCode($value);
634 $value = $countryName;
635 }
636 // ensure value is not an array
637 // CRM-4174
638 if (!is_array($value)) {
639 $paypalParams[$otherVars[$name]] = $value;
640 }
641 }
642 }
643 }
644
645 // if recurring donations, add a few more items
646 if (!empty($params['is_recur'])) {
647 if ($params['contributionRecurID']) {
648 $notifyURL .= "&contributionRecurID={$params['contributionRecurID']}&contributionPageID={$params['contributionPageID']}";
649 $paypalParams['notify_url'] = $notifyURL;
650 }
651 else {
652 CRM_Core_Error::fatal(ts('Recurring contribution, but no database id'));
653 }
654
655 $paypalParams += array(
656 'cmd' => '_xclick-subscriptions',
657 'a3' => $params['amount'],
658 'p3' => $params['frequency_interval'],
659 't3' => ucfirst(substr($params['frequency_unit'], 0, 1)),
660 'src' => 1,
661 'sra' => 1,
662 'srt' => CRM_Utils_Array::value('installments', $params),
663 'no_note' => 1,
664 'modify' => 0,
665 );
666 }
667 else {
668 $paypalParams += array(
669 'cmd' => '_xclick',
670 'amount' => $params['amount'],
671 );
672 }
673
674 // Allow further manipulation of the arguments via custom hooks ..
675 CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $paypalParams);
676
677 $uri = '';
678 foreach ($paypalParams as $key => $value) {
679 if ($value === NULL) {
680 continue;
681 }
682
683 $value = urlencode($value);
684 if ($key == 'return' ||
685 $key == 'cancel_return' ||
686 $key == 'notify_url'
687 ) {
688 $value = str_replace('%2F', '/', $value);
689 }
690 $uri .= "&{$key}={$value}";
691 }
692
693 $uri = substr($uri, 1);
694 $url = $this->_paymentProcessor['url_site'];
695 $sub = empty($params['is_recur']) ? 'cgi-bin/webscr' : 'subscriptions';
696 $paypalURL = "{$url}{$sub}?$uri";
697
698 CRM_Utils_System::redirect($paypalURL);
699 }
700
701 /**
702 * Hash_call: Function to perform the API call to PayPal using API signature
703 * @methodName is name of API method.
704 * @nvpStr is nvp string.
705 * returns an associtive array containing the response from the server.
706 */
707 public function invokeAPI($args, $url = NULL) {
708
709 if ($url === NULL) {
710 if (empty($this->_paymentProcessor['url_api'])) {
711 CRM_Core_Error::fatal(ts('Please set the API URL. Please refer to the documentation for more details'));
712 }
713
714 $url = $this->_paymentProcessor['url_api'] . 'nvp';
715 }
716
717 if (!function_exists('curl_init')) {
718 CRM_Core_Error::fatal("curl functions NOT available.");
719 }
720
721 //setting the curl parameters.
722 $ch = curl_init();
723 curl_setopt($ch, CURLOPT_URL, $url);
724 curl_setopt($ch, CURLOPT_VERBOSE, 1);
725
726 //turning off the server and peer verification(TrustManager Concept).
727 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'verifySSL'));
728 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'verifySSL') ? 2 : 0);
729
730 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
731 curl_setopt($ch, CURLOPT_POST, 1);
732
733 $p = array();
734 foreach ($args as $n => $v) {
735 $p[] = "$n=" . urlencode($v);
736 }
737
738 //NVPRequest for submitting to server
739 $nvpreq = implode('&', $p);
740
741 //setting the nvpreq as POST FIELD to curl
742 curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
743
744 //getting response from server
745 $response = curl_exec($ch);
746
747 //converting NVPResponse to an Associative Array
748 $result = self::deformat($response);
749
750 if (curl_errno($ch)) {
751 $e = CRM_Core_Error::singleton();
752 $e->push(curl_errno($ch),
753 0, NULL,
754 curl_error($ch)
755 );
756 return $e;
757 }
758 else {
759 curl_close($ch);
760 }
761
762 if (strtolower($result['ack']) != 'success' &&
763 strtolower($result['ack']) != 'successwithwarning'
764 ) {
765 $e = CRM_Core_Error::singleton();
766 $e->push($result['l_errorcode0'],
767 0, NULL,
768 "{$result['l_shortmessage0']} {$result['l_longmessage0']}"
769 );
770 return $e;
771 }
772
773 return $result;
774 }
775
776 /**
777 * This function will take NVPString and convert it to an Associative Array and it will decode the response.
778 * It is usefull to search for a particular key and displaying arrays.
779 * @nvpstr is NVPString.
780 * @nvpArray is Associative Array.
781 */
782 public static function deformat($str) {
783 $result = array();
784
785 while (strlen($str)) {
786 // postion of key
787 $keyPos = strpos($str, '=');
788
789 // position of value
790 $valPos = strpos($str, '&') ? strpos($str, '&') : strlen($str);
791
792 /*getting the Key and Value values and storing in a Associative Array*/
793
794 $key = substr($str, 0, $keyPos);
795 $val = substr($str, $keyPos + 1, $valPos - $keyPos - 1);
796
797 //decoding the respose
798 $result[strtolower(urldecode($key))] = urldecode($val);
799 $str = substr($str, $valPos + 1, strlen($str));
800 }
801
802 return $result;
803 }
804
805 }