Commit | Line | Data |
---|---|---|
6a488035 TO |
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 | * @return void | |
84 | */ | |
85 | function __construct($mode, &$paymentProcessor) { | |
86 | parent::__construct(); | |
87 | ||
88 | $this->_mode = $mode; | |
89 | $this->_paymentProcessor = $paymentProcessor; | |
90 | } | |
91 | ||
92 | /** | |
93 | * The function gets called when a new order takes place. | |
94 | * | |
95 | * @param xml $dataRoot response send by google in xml format | |
96 | * @param array $privateData contains the name value pair of <merchant-private-data> | |
97 | * | |
98 | * @return void | |
99 | * | |
100 | */ | |
101 | function newOrderNotify($dataRoot, $privateData, $component) { | |
102 | $ids = $input = $params = array(); | |
103 | ||
104 | $input['component'] = strtolower($component); | |
105 | ||
106 | $ids['contact'] = self::retrieve('contactID', 'Integer', $privateData, TRUE); | |
107 | $ids['contribution'] = self::retrieve('contributionID', 'Integer', $privateData, TRUE); | |
108 | ||
109 | if ($input['component'] == "event") { | |
110 | $ids['event'] = self::retrieve('eventID', 'Integer', $privateData, TRUE); | |
111 | $ids['participant'] = self::retrieve('participantID', 'Integer', $privateData, TRUE); | |
112 | $ids['membership'] = NULL; | |
113 | } | |
114 | else { | |
115 | $ids['membership'] = self::retrieve('membershipID', 'Integer', $privateData, FALSE); | |
116 | $ids['related_contact'] = self::retrieve('relatedContactID', 'Integer', $privateData, FALSE); | |
117 | $ids['onbehalf_dupe_alert'] = self::retrieve('onBehalfDupeAlert', 'Integer', $privateData, FALSE); | |
118 | } | |
119 | $ids['contributionRecur'] = $ids['contributionPage'] = NULL; | |
120 | ||
121 | if (!$this->validateData($input, $ids, $objects)) { | |
122 | return FALSE; | |
123 | } | |
124 | ||
125 | // make sure the invoice is valid and matches what we have in the contribution record | |
126 | $input['invoice'] = $privateData['invoiceID']; | |
127 | $input['newInvoice'] = $dataRoot['google-order-number']['VALUE']; | |
128 | $contribution = &$objects['contribution']; | |
129 | if ($contribution->invoice_id != $input['invoice']) { | |
130 | CRM_Core_Error::debug_log_message("Invoice values dont match between database and IPN request"); | |
131 | echo "Failure: Invoice values dont match between database and IPN request<p>"; | |
132 | return; | |
133 | } | |
134 | ||
135 | // lets replace invoice-id with google-order-number because thats what is common and unique | |
136 | // in subsequent calls or notifications sent by google. | |
137 | $contribution->invoice_id = $input['newInvoice']; | |
138 | ||
139 | $input['amount'] = $dataRoot['order-total']['VALUE']; | |
140 | ||
141 | if ($contribution->total_amount != $input['amount']) { | |
142 | CRM_Core_Error::debug_log_message("Amount values dont match between database and IPN request"); | |
143 | echo "Failure: Amount values dont match between database and IPN request<p>"; | |
144 | return; | |
145 | } | |
146 | ||
147 | if (!$this->getInput($input, $ids)) { | |
148 | return FALSE; | |
149 | } | |
150 | ||
151 | require_once 'CRM/Core/Transaction.php'; | |
152 | $transaction = new CRM_Core_Transaction(); | |
153 | ||
154 | // fix for CRM-2842 | |
155 | // if ( ! $this->createContact( $input, $ids, $objects ) ) { | |
156 | // return false; | |
157 | // } | |
158 | ||
159 | // check if contribution is already completed, if so we ignore this ipn | |
160 | if ($contribution->contribution_status_id == 1) { | |
161 | CRM_Core_Error::debug_log_message("returning since contribution has already been handled"); | |
162 | echo "Success: Contribution has already been handled<p>"; | |
163 | } | |
164 | else { | |
165 | /* Since trxn_id hasn't got any use here, | |
166 | * lets make use of it by passing the eventID/membershipTypeID to next level. | |
167 | * And change trxn_id to google-order-number before finishing db update */ | |
168 | ||
169 | ||
170 | if ($ids['event']) { | |
171 | $contribution->trxn_id = $ids['event'] . CRM_Core_DAO::VALUE_SEPARATOR . $ids['participant']; | |
172 | } | |
173 | else { | |
174 | $contribution->trxn_id = $ids['membership'] . CRM_Core_DAO::VALUE_SEPARATOR . $ids['related_contact'] . CRM_Core_DAO::VALUE_SEPARATOR . $ids['onbehalf_dupe_alert']; | |
175 | } | |
176 | } | |
177 | ||
178 | // CRM_Core_Error::debug_var( 'c', $contribution ); | |
179 | $contribution->save(); | |
180 | $transaction->commit(); | |
181 | return TRUE; | |
182 | } | |
183 | ||
184 | /** | |
185 | * The function gets called when the state(CHARGED, CANCELLED..) changes for an order | |
186 | * | |
187 | * @param string $status status of the transaction send by google | |
188 | * @param array $privateData contains the name value pair of <merchant-private-data> | |
189 | * | |
190 | * @return void | |
191 | * | |
192 | */ | |
193 | function orderStateChange($status, $dataRoot, $component) { | |
194 | $input = $objects = $ids = array(); | |
195 | ||
196 | $input['component'] = strtolower($component); | |
197 | ||
198 | // CRM_Core_Error::debug_var( "$status, $component", $dataRoot ); | |
199 | $orderNo = $dataRoot['google-order-number']['VALUE']; | |
200 | ||
201 | require_once 'CRM/Contribute/DAO/Contribution.php'; | |
202 | $contribution = new CRM_Contribute_DAO_Contribution(); | |
203 | $contribution->invoice_id = $orderNo; | |
204 | if (!$contribution->find(TRUE)) { | |
205 | CRM_Core_Error::debug_log_message("Could not find contribution record with invoice id: $orderNo"); | |
206 | echo "Failure: Could not find contribution record with invoice id: $orderNo <p>"; | |
207 | exit(); | |
208 | } | |
209 | ||
210 | // Google sends the charged notification twice. | |
211 | // So to make sure, code is not executed again. | |
212 | if ($contribution->contribution_status_id == 1) { | |
213 | CRM_Core_Error::debug_log_message("Contribution already handled (ContributionID = $contribution)."); | |
214 | exit(); | |
215 | } | |
216 | ||
217 | $objects['contribution'] = &$contribution; | |
218 | $ids['contribution'] = $contribution->id; | |
219 | $ids['contact'] = $contribution->contact_id; | |
220 | ||
221 | $ids['event'] = $ids['participant'] = $ids['membership'] = NULL; | |
222 | $ids['contributionRecur'] = $ids['contributionPage'] = NULL; | |
223 | ||
224 | if ($input['component'] == "event") { | |
225 | list($ids['event'], $ids['participant']) = explode(CRM_Core_DAO::VALUE_SEPARATOR, | |
226 | $contribution->trxn_id | |
227 | ); | |
228 | } | |
229 | else { | |
230 | list($ids['membership'], $ids['related_contact'], $ids['onbehalf_dupe_alert']) = explode(CRM_Core_DAO::VALUE_SEPARATOR, | |
231 | $contribution->trxn_id | |
232 | ); | |
233 | ||
234 | foreach (array('membership', 'related_contact', 'onbehalf_dupe_alert') as $fld) { | |
235 | if (!is_numeric($ids[$fld])) { | |
236 | unset($ids[$fld]); | |
237 | } | |
238 | } | |
239 | } | |
240 | ||
241 | $this->loadObjects($input, $ids, $objects); | |
242 | ||
243 | require_once 'CRM/Core/Transaction.php'; | |
244 | $transaction = new CRM_Core_Transaction(); | |
245 | ||
246 | // CRM_Core_Error::debug_var( 'c', $contribution ); | |
247 | if ($status == 'PAYMENT_DECLINED' || | |
248 | $status == 'CANCELLED_BY_GOOGLE' || | |
249 | $status == 'CANCELLED' | |
250 | ) { | |
251 | return $this->failed($objects, $transaction); | |
252 | } | |
253 | ||
254 | $input['amount'] = $contribution->total_amount; | |
255 | $input['fee_amount'] = NULL; | |
256 | $input['net_amount'] = NULL; | |
257 | $input['trxn_id'] = $orderNo; | |
258 | $input['is_test'] = $contribution->is_test; | |
259 | ||
260 | $this->completeTransaction($input, $ids, $objects, $transaction); | |
261 | } | |
262 | ||
263 | /** | |
264 | * singleton function used to manage this object | |
265 | * | |
266 | * @param string $mode the mode of operation: live or test | |
267 | * | |
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 |