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