Merge pull request #3152 from pradpnayak/CRM-14112
[civicrm-core.git] / tools / extensions / org.civicrm.payment.googlecheckout / GoogleIPN.php
1 <?php
2
3 /**
4 * Copyright (C) 2006 Google Inc.
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19 /* This is the response handler code that will be invoked every time
20 * a notification or request is sent by the Google Server
21 *
22 * To allow this code to receive responses, the url for this file
23 * must be set on the seller page under Settings->Integration as the
24 * "API Callback URL'
25 * Order processing commands can be sent automatically by placing these
26 * commands appropriately
27 *
28 * To use this code for merchant-calculated feedback, this url must be
29 * set also as the merchant-calculations-url when the cart is posted
30 * Depending on your calculations for shipping, taxes, coupons and gift
31 * certificates update parts of the code as required
32 *
33 */
34
35
36
37 require_once 'CRM/Core/Payment/BaseIPN.php';
38
39 define('GOOGLE_DEBUG_PP', 1);
40 class org_civicrm_payment_googlecheckout_GoogleIPN extends CRM_Core_Payment_BaseIPN {
41
42 /**
43 * We only need one instance of this object. So we use the singleton
44 * pattern and cache the instance in this variable
45 *
46 * @var object
47 * @static
48 */
49 static private $_singleton = NULL;
50
51 /**
52 * mode of operation: live or test
53 *
54 * @var object
55 * @static
56 */
57 static protected $_mode = NULL;
58
59 static function retrieve($name, $type, $object, $abort = TRUE) {
60 $value = CRM_Utils_Array::value($name, $object);
61 if ($abort && $value === NULL) {
62 CRM_Core_Error::debug_log_message("Could not find an entry for $name");
63 echo "Failure: Missing Parameter<p>";
64 exit();
65 }
66
67 if ($value) {
68 if (!CRM_Utils_Type::validate($value, $type)) {
69 CRM_Core_Error::debug_log_message("Could not find a valid entry for $name");
70 echo "Failure: Invalid Parameter<p>";
71 exit();
72 }
73 }
74
75 return $value;
76 }
77
78 /**
79 * Constructor
80 *
81 * @param string $mode the mode of operation: live or test
82 *
83 * @param $paymentProcessor
84 *
85 * @return \org_civicrm_payment_googlecheckout_GoogleIPN
86 */
87 function __construct($mode, &$paymentProcessor) {
88 parent::__construct();
89
90 $this->_mode = $mode;
91 $this->_paymentProcessor = $paymentProcessor;
92 }
93
94 /**
95 * The function gets called when a new order takes place.
96 *
97 * @param xml $dataRoot response send by google in xml format
98 * @param array $privateData contains the name value pair of <merchant-private-data>
99 *
100 * @param $component
101 * @return void
102 */
103 function newOrderNotify($dataRoot, $privateData, $component) {
104 $ids = $input = $params = array();
105
106 $input['component'] = strtolower($component);
107
108 $ids['contact'] = self::retrieve('contactID', 'Integer', $privateData, TRUE);
109 $ids['contribution'] = self::retrieve('contributionID', 'Integer', $privateData, TRUE);
110
111 if ($input['component'] == "event") {
112 $ids['event'] = self::retrieve('eventID', 'Integer', $privateData, TRUE);
113 $ids['participant'] = self::retrieve('participantID', 'Integer', $privateData, TRUE);
114 $ids['membership'] = NULL;
115 }
116 else {
117 $ids['membership'] = self::retrieve('membershipID', 'Integer', $privateData, FALSE);
118 $ids['related_contact'] = self::retrieve('relatedContactID', 'Integer', $privateData, FALSE);
119 $ids['onbehalf_dupe_alert'] = self::retrieve('onBehalfDupeAlert', 'Integer', $privateData, FALSE);
120 }
121 $ids['contributionRecur'] = $ids['contributionPage'] = NULL;
122
123 if (!$this->validateData($input, $ids, $objects)) {
124 return FALSE;
125 }
126
127 // make sure the invoice is valid and matches what we have in the contribution record
128 $input['invoice'] = $privateData['invoiceID'];
129 $input['newInvoice'] = $dataRoot['google-order-number']['VALUE'];
130 $contribution = &$objects['contribution'];
131 if ($contribution->invoice_id != $input['invoice']) {
132 CRM_Core_Error::debug_log_message("Invoice values dont match between database and IPN request");
133 echo "Failure: Invoice values dont match between database and IPN request<p>";
134 return;
135 }
136
137 // lets replace invoice-id with google-order-number because thats what is common and unique
138 // in subsequent calls or notifications sent by google.
139 $contribution->invoice_id = $input['newInvoice'];
140
141 $input['amount'] = $dataRoot['order-total']['VALUE'];
142
143 if ($contribution->total_amount != $input['amount']) {
144 CRM_Core_Error::debug_log_message("Amount values dont match between database and IPN request");
145 echo "Failure: Amount values dont match between database and IPN request<p>";
146 return;
147 }
148
149 if (!$this->getInput($input, $ids)) {
150 return FALSE;
151 }
152
153 require_once 'CRM/Core/Transaction.php';
154 $transaction = new CRM_Core_Transaction();
155
156 // check if contribution is already completed, if so we ignore this ipn
157 if ($contribution->contribution_status_id == 1) {
158 CRM_Core_Error::debug_log_message("returning since contribution has already been handled");
159 echo "Success: Contribution has already been handled<p>";
160 }
161 else {
162 /* Since trxn_id hasn't got any use here,
163 * lets make use of it by passing the eventID/membershipTypeID to next level.
164 * And change trxn_id to google-order-number before finishing db update */
165
166
167 if ($ids['event']) {
168 $contribution->trxn_id = $ids['event'] . CRM_Core_DAO::VALUE_SEPARATOR . $ids['participant'];
169 }
170 else {
171 $contribution->trxn_id = $ids['membership'] . CRM_Core_DAO::VALUE_SEPARATOR . $ids['related_contact'] . CRM_Core_DAO::VALUE_SEPARATOR . $ids['onbehalf_dupe_alert'];
172 }
173 }
174
175 // CRM_Core_Error::debug_var( 'c', $contribution );
176 $contribution->save();
177 $transaction->commit();
178 return TRUE;
179 }
180
181 /**
182 * The function gets called when the state(CHARGED, CANCELLED..) changes for an order
183 *
184 * @param string $status status of the transaction send by google
185 * @param $dataRoot
186 * @param $component
187 * @internal param array $privateData contains the name value pair of <merchant-private-data>
188 *
189 * @return void
190 */
191 function orderStateChange($status, $dataRoot, $component) {
192 $input = $objects = $ids = array();
193
194 $input['component'] = strtolower($component);
195
196 // CRM_Core_Error::debug_var( "$status, $component", $dataRoot );
197 $orderNo = $dataRoot['google-order-number']['VALUE'];
198
199 require_once 'CRM/Contribute/DAO/Contribution.php';
200 $contribution = new CRM_Contribute_DAO_Contribution();
201 $contribution->invoice_id = $orderNo;
202 if (!$contribution->find(TRUE)) {
203 CRM_Core_Error::debug_log_message("Could not find contribution record with invoice id: $orderNo");
204 echo "Failure: Could not find contribution record with invoice id: $orderNo <p>";
205 exit();
206 }
207
208 // Google sends the charged notification twice.
209 // So to make sure, code is not executed again.
210 if ($contribution->contribution_status_id == 1) {
211 CRM_Core_Error::debug_log_message("Contribution already handled (ContributionID = $contribution).");
212 exit();
213 }
214
215 $objects['contribution'] = &$contribution;
216 $ids['contribution'] = $contribution->id;
217 $ids['contact'] = $contribution->contact_id;
218
219 $ids['event'] = $ids['participant'] = $ids['membership'] = NULL;
220 $ids['contributionRecur'] = $ids['contributionPage'] = NULL;
221
222 if ($input['component'] == "event") {
223 list($ids['event'], $ids['participant']) = explode(CRM_Core_DAO::VALUE_SEPARATOR,
224 $contribution->trxn_id
225 );
226 }
227 else {
228 list($ids['membership'], $ids['related_contact'], $ids['onbehalf_dupe_alert']) = explode(CRM_Core_DAO::VALUE_SEPARATOR,
229 $contribution->trxn_id
230 );
231
232 foreach (array('membership', 'related_contact', 'onbehalf_dupe_alert') as $fld) {
233 if (!is_numeric($ids[$fld])) {
234 unset($ids[$fld]);
235 }
236 }
237 }
238
239 $this->loadObjects($input, $ids, $objects);
240
241 require_once 'CRM/Core/Transaction.php';
242 $transaction = new CRM_Core_Transaction();
243
244 // CRM_Core_Error::debug_var( 'c', $contribution );
245 if ($status == 'PAYMENT_DECLINED' ||
246 $status == 'CANCELLED_BY_GOOGLE' ||
247 $status == 'CANCELLED'
248 ) {
249 return $this->failed($objects, $transaction);
250 }
251
252 $input['amount'] = $contribution->total_amount;
253 $input['fee_amount'] = NULL;
254 $input['net_amount'] = NULL;
255 $input['trxn_id'] = $orderNo;
256 $input['is_test'] = $contribution->is_test;
257
258 $this->completeTransaction($input, $ids, $objects, $transaction);
259 }
260
261 /**
262 * singleton function used to manage this object
263 *
264 * @param string $mode the mode of operation: live or test
265 *
266 * @param $component
267 * @param $paymentProcessor
268 * @return object
269 * @static
270 */
271 static
272 function &singleton($mode, $component, &$paymentProcessor) {
273 if (self::$_singleton === NULL) {
274 self::$_singleton = new org_civicrm_payment_googlecheckout_GoogleIPN($mode, $paymentProcessor);
275 }
276 return self::$_singleton;
277 }
278
279 /**
280 * The function retrieves the amount the contribution is for, based on the order-no google sends
281 *
282 * @param int $orderNo <order-total> send by google
283 *
284 * @return amount
285 * @access public
286 */
287 function getAmount($orderNo) {
288 require_once 'CRM/Contribute/DAO/Contribution.php';
289 $contribution = new CRM_Contribute_DAO_Contribution();
290 $contribution->invoice_id = $orderNo;
291 if (!$contribution->find(TRUE)) {
292 CRM_Core_Error::debug_log_message("Could not find contribution record with invoice id: $orderNo");
293 echo "Failure: Could not find contribution record with invoice id: $orderNo <p>";
294 exit();
295 }
296 return $contribution->total_amount;
297 }
298
299 /**
300 * The function returns the component(Event/Contribute..), given the google-order-no and merchant-private-data
301 *
302 * @param xml $xml_response response send by google in xml format
303 * @param array $privateData contains the name value pair of <merchant-private-data>
304 * @param int $orderNo <order-total> send by google
305 * @param string $root root of xml-response
306 *
307 * @return array context of this call (test, module, payment processor id)
308 * @static
309 */
310 static
311 function getContext($xml_response, $privateData, $orderNo, $root) {
312 require_once 'CRM/Contribute/DAO/Contribution.php';
313
314 $isTest = NULL;
315 $module = NULL;
316 if ($root == 'new-order-notification') {
317 $contributionID = $privateData['contributionID'];
318 $contribution = new CRM_Contribute_DAO_Contribution();
319 $contribution->id = $contributionID;
320 if (!$contribution->find(TRUE)) {
321 CRM_Core_Error::debug_log_message("Could not find contribution record: $contributionID");
322 echo "Failure: Could not find contribution record for $contributionID<p>";
323 exit();
324 }
325 if (stristr($contribution->source, ts('Online Contribution'))) {
326 $module = 'Contribute';
327 }
328 elseif (stristr($contribution->source, ts('Online Event Registration'))) {
329 $module = 'Event';
330 }
331 $isTest = $contribution->is_test;
332 }
333 else {
334 $contribution = new CRM_Contribute_DAO_Contribution();
335 $contribution->invoice_id = $orderNo;
336 if (!$contribution->find(TRUE)) {
337 CRM_Core_Error::debug_log_message("Could not find contribution record with invoice id: $orderNo");
338 echo "Failure: Could not find contribution record with invoice id: $orderNo <p>";
339 exit();
340 }
341 if (stristr($contribution->source, ts('Online Contribution'))) {
342 $module = 'Contribute';
343 }
344 elseif (stristr($contribution->source, ts('Online Event Registration'))) {
345 $module = 'Event';
346 }
347 $isTest = $contribution->is_test;
348 }
349
350 if ($contribution->contribution_status_id == 1) {
351 //contribution already handled.
352 exit();
353 }
354
355 if ($module == 'Contribute') {
356 if (!$contribution->contribution_page_id) {
357 CRM_Core_Error::debug_log_message("Could not find contribution page for contribution record: $contributionID");
358 echo "Failure: Could not find contribution page for contribution record: $contributionID<p>";
359 exit();
360 }
361
362 // get the payment processor id from contribution page
363 $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage',
364 $contribution->contribution_page_id,
365 'payment_processor_id'
366 );
367 }
368 else {
369 if ($root == 'new-order-notification') {
370 $eventID = $privateData['eventID'];
371 }
372 else {
373 list($eventID, $participantID) = explode(CRM_Core_DAO::VALUE_SEPARATOR,
374 $contribution->trxn_id
375 );
376 }
377 if (!$eventID) {
378 CRM_Core_Error::debug_log_message("Could not find event ID");
379 echo "Failure: Could not find eventID<p>";
380 exit();
381 }
382
383 // we are in event mode
384 // make sure event exists and is valid
385 require_once 'CRM/Event/DAO/Event.php';
386 $event = new CRM_Event_DAO_Event();
387 $event->id = $eventID;
388 if (!$event->find(TRUE)) {
389 CRM_Core_Error::debug_log_message("Could not find event: $eventID");
390 echo "Failure: Could not find event: $eventID<p>";
391 exit();
392 }
393
394 // get the payment processor id from contribution page
395 $paymentProcessorID = $event->payment_processor_id;
396 }
397
398 if (!$paymentProcessorID) {
399 CRM_Core_Error::debug_log_message("Could not find payment processor for contribution record: $contributionID");
400 echo "Failure: Could not find payment processor for contribution record: $contributionID<p>";
401 exit();
402 }
403
404 return array($isTest, $module, $paymentProcessorID);
405 }
406
407 /**
408 * This method is handles the response that will be invoked (from extern/googleNotify) every time
409 * a notification or request is sent by the Google Server.
410 *
411 */
412 static
413 function main($xml_response) {
414 require_once ('Google/library/googleresponse.php');
415 require_once ('Google/library/googlemerchantcalculations.php');
416 require_once ('Google/library/googleresult.php');
417 require_once ('Google/library/xml-processing/xmlparser.php');
418
419 $config = CRM_Core_Config::singleton();
420
421 // Retrieve the XML sent in the HTTP POST request to the ResponseHandler
422 if (get_magic_quotes_gpc()) {
423 $xml_response = stripslashes($xml_response);
424 }
425
426 require_once 'CRM/Utils/System.php';
427 $headers = CRM_Utils_System::getAllHeaders();
428
429 if (GOOGLE_DEBUG_PP) {
430 CRM_Core_Error::debug_var('RESPONSE', $xml_response, TRUE, TRUE, 'Google');
431 }
432
433 // Retrieve the root and data from the xml response
434 $xmlParser = new XmlParser($xml_response);
435 $root = $xmlParser->GetRoot();
436 $data = $xmlParser->GetData();
437
438 $orderNo = $data[$root]['google-order-number']['VALUE'];
439
440 // lets retrieve the private-data
441 $privateData = $data[$root]['shopping-cart']['merchant-private-data']['VALUE'];
442 $privateData = $privateData ? self::stringToArray($privateData) : '';
443
444 list($mode, $module, $paymentProcessorID) = self::getContext($xml_response, $privateData, $orderNo, $root);
445 $mode = $mode ? 'test' : 'live';
446
447 require_once 'CRM/Financial/BAO/PaymentProcessor.php';
448 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($paymentProcessorID,
449 $mode
450 );
451
452 $ipn = &self::singleton($mode, $module, $paymentProcessor);
453
454 // Create new response object
455 $merchant_id = $paymentProcessor['user_name'];
456 $merchant_key = $paymentProcessor['password'];
457 $server_type = ($mode == 'test') ? "sandbox" : '';
458
459 $response = new GoogleResponse($merchant_id, $merchant_key,
460 $xml_response, $server_type
461 );
462 if (GOOGLE_DEBUG_PP) {
463 CRM_Core_Error::debug_var('RESPONSE-ROOT', $response->root, TRUE, TRUE, 'Google');
464 }
465
466 //Check status and take appropriate action
467 $status = $response->HttpAuthentication($headers);
468
469 switch ($root) {
470 case "request-received":
471 case "error":
472 case "diagnosis":
473 case "checkout-redirect":
474 case "merchant-calculation-callback":
475 break;
476
477 case "new-order-notification": {
478 $response->SendAck();
479 $ipn->newOrderNotify($data[$root], $privateData, $module);
480 break;
481 }
482 case "order-state-change-notification": {
483 $response->SendAck();
484 $new_financial_state = $data[$root]['new-financial-order-state']['VALUE'];
485 $new_fulfillment_order = $data[$root]['new-fulfillment-order-state']['VALUE'];
486
487 switch ($new_financial_state) {
488 case 'CHARGEABLE':
489 $amount = $ipn->getAmount($orderNo);
490 if ($amount) {
491 $response->SendChargeOrder($data[$root]['google-order-number']['VALUE'],
492 $amount, $message_log
493 );
494 $response->SendProcessOrder($data[$root]['google-order-number']['VALUE'],
495 $message_log
496 );
497 }
498 break;
499
500 case 'CHARGED':
501 case 'PAYMENT_DECLINED':
502 case 'CANCELLED':
503 $ipn->orderStateChange($new_financial_state, $data[$root], $module);
504 break;
505
506 case 'REVIEWING':
507 case 'CHARGING':
508 case 'CANCELLED_BY_GOOGLE':
509 break;
510
511 default:
512 break;
513 }
514 }
515 case "charge-amount-notification":
516 case "chargeback-amount-notification":
517 case "refund-amount-notification":
518 case "risk-information-notification":
519 $response->SendAck();
520 break;
521
522 default:
523 break;
524 }
525 }
526
527 function getInput(&$input, &$ids) {
528 if (!$this->getBillingID($ids)) {
529 return FALSE;
530 }
531
532 $billingID = $ids['billing'];
533 $lookup = array("first_name" => 'contact-name',
534 // "last-name" not available with google (every thing in contact-name)
535 "last_name" => 'last_name',
536 "street_address-{$billingID}" => 'address1',
537 "city-{$billingID}" => 'city',
538 "state-{$billingID}" => 'region',
539 "postal_code-{$billingID}" => 'postal-code',
540 "country-{$billingID}" => 'country-code',
541 );
542
543 foreach ($lookup as $name => $googleName) {
544 $value = $dataRoot['buyer-billing-address'][$googleName]['VALUE'];
545 $input[$name] = $value ? $value : NULL;
546 }
547 return TRUE;
548 }
549
550 /**
551 * Converts the comma separated name-value pairs in <merchant-private-data>
552 * to an array of name-value pairs.
553 */
554 static
555 function stringToArray($str) {
556 $vars = $labels = array();
557 $labels = explode(',', $str);
558 foreach ($labels as $label) {
559 $terms = explode('=', $label);
560 $vars[$terms[0]] = $terms[1];
561 }
562 return $vars;
563 }
564 }
565