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