4 * Copyright (C) 2006 Google Inc.
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
10 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 /* This is the response handler code that will be invoked every time
20 * a notification or request is sent by the Google Server
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
25 * Order processing commands can be sent automatically by placing these
26 * commands appropriately
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
37 require_once 'CRM/Core/Payment/BaseIPN.php';
39 define('GOOGLE_DEBUG_PP', 1);
40 class org_civicrm_payment_googlecheckout_GoogleIPN
extends CRM_Core_Payment_BaseIPN
{
43 * We only need one instance of this object. So we use the singleton
44 * pattern and cache the instance in this variable
49 static private $_singleton = NULL;
52 * mode of operation: live or test
57 static protected $_mode = NULL;
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>";
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>";
81 * @param string $mode the mode of operation: live or test
83 * @param $paymentProcessor
85 * @return \org_civicrm_payment_googlecheckout_GoogleIPN
87 function __construct($mode, &$paymentProcessor) {
88 parent
::__construct();
91 $this->_paymentProcessor
= $paymentProcessor;
95 * The function gets called when a new order takes place.
97 * @param xml $dataRoot response send by google in xml format
98 * @param array $privateData contains the name value pair of <merchant-private-data>
103 function newOrderNotify($dataRoot, $privateData, $component) {
104 $ids = $input = $params = array();
106 $input['component'] = strtolower($component);
108 $ids['contact'] = self
::retrieve('contactID', 'Integer', $privateData, TRUE);
109 $ids['contribution'] = self
::retrieve('contributionID', 'Integer', $privateData, TRUE);
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;
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);
121 $ids['contributionRecur'] = $ids['contributionPage'] = NULL;
123 if (!$this->validateData($input, $ids, $objects)) {
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>";
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'];
141 $input['amount'] = $dataRoot['order-total']['VALUE'];
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>";
149 if (!$this->getInput($input, $ids)) {
153 require_once 'CRM/Core/Transaction.php';
154 $transaction = new CRM_Core_Transaction();
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>";
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 */
168 $contribution->trxn_id
= $ids['event'] . CRM_Core_DAO
::VALUE_SEPARATOR
. $ids['participant'];
171 $contribution->trxn_id
= $ids['membership'] . CRM_Core_DAO
::VALUE_SEPARATOR
. $ids['related_contact'] . CRM_Core_DAO
::VALUE_SEPARATOR
. $ids['onbehalf_dupe_alert'];
175 // CRM_Core_Error::debug_var( 'c', $contribution );
176 $contribution->save();
177 $transaction->commit();
182 * The function gets called when the state(CHARGED, CANCELLED..) changes for an order
184 * @param string $status status of the transaction send by google
187 * @internal param array $privateData contains the name value pair of <merchant-private-data>
191 function orderStateChange($status, $dataRoot, $component) {
192 $input = $objects = $ids = array();
194 $input['component'] = strtolower($component);
196 // CRM_Core_Error::debug_var( "$status, $component", $dataRoot );
197 $orderNo = $dataRoot['google-order-number']['VALUE'];
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>";
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).");
215 $objects['contribution'] = &$contribution;
216 $ids['contribution'] = $contribution->id
;
217 $ids['contact'] = $contribution->contact_id
;
219 $ids['event'] = $ids['participant'] = $ids['membership'] = NULL;
220 $ids['contributionRecur'] = $ids['contributionPage'] = NULL;
222 if ($input['component'] == "event") {
223 list($ids['event'], $ids['participant']) = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
224 $contribution->trxn_id
228 list($ids['membership'], $ids['related_contact'], $ids['onbehalf_dupe_alert']) = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
229 $contribution->trxn_id
232 foreach (array('membership', 'related_contact', 'onbehalf_dupe_alert') as $fld) {
233 if (!is_numeric($ids[$fld])) {
239 $this->loadObjects($input, $ids, $objects);
241 require_once 'CRM/Core/Transaction.php';
242 $transaction = new CRM_Core_Transaction();
244 // CRM_Core_Error::debug_var( 'c', $contribution );
245 if ($status == 'PAYMENT_DECLINED' ||
246 $status == 'CANCELLED_BY_GOOGLE' ||
247 $status == 'CANCELLED'
249 return $this->failed($objects, $transaction);
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
;
258 $this->completeTransaction($input, $ids, $objects, $transaction);
262 * singleton function used to manage this object
264 * @param string $mode the mode of operation: live or test
267 * @param $paymentProcessor
272 function &singleton($mode, $component, &$paymentProcessor) {
273 if (self
::$_singleton === NULL) {
274 self
::$_singleton = new org_civicrm_payment_googlecheckout_GoogleIPN($mode, $paymentProcessor);
276 return self
::$_singleton;
280 * The function retrieves the amount the contribution is for, based on the order-no google sends
282 * @param int $orderNo <order-total> send by google
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>";
296 return $contribution->total_amount
;
300 * The function returns the component(Event/Contribute..), given the google-order-no and merchant-private-data
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
307 * @return array context of this call (test, module, payment processor id)
311 function getContext($xml_response, $privateData, $orderNo, $root) {
312 require_once 'CRM/Contribute/DAO/Contribution.php';
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>";
325 if (stristr($contribution->source
, ts('Online Contribution'))) {
326 $module = 'Contribute';
328 elseif (stristr($contribution->source
, ts('Online Event Registration'))) {
331 $isTest = $contribution->is_test
;
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>";
341 if (stristr($contribution->source
, ts('Online Contribution'))) {
342 $module = 'Contribute';
344 elseif (stristr($contribution->source
, ts('Online Event Registration'))) {
347 $isTest = $contribution->is_test
;
350 if ($contribution->contribution_status_id
== 1) {
351 //contribution already handled.
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>";
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'
369 if ($root == 'new-order-notification') {
370 $eventID = $privateData['eventID'];
373 list($eventID, $participantID) = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
374 $contribution->trxn_id
378 CRM_Core_Error
::debug_log_message("Could not find event ID");
379 echo "Failure: Could not find eventID<p>";
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>";
394 // get the payment processor id from contribution page
395 $paymentProcessorID = $event->payment_processor_id
;
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>";
404 return array($isTest, $module, $paymentProcessorID);
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.
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');
419 $config = CRM_Core_Config
::singleton();
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);
426 require_once 'CRM/Utils/System.php';
427 $headers = CRM_Utils_System
::getAllHeaders();
429 if (GOOGLE_DEBUG_PP
) {
430 CRM_Core_Error
::debug_var('RESPONSE', $xml_response, TRUE, TRUE, 'Google');
433 // Retrieve the root and data from the xml response
434 $xmlParser = new XmlParser($xml_response);
435 $root = $xmlParser->GetRoot();
436 $data = $xmlParser->GetData();
438 $orderNo = $data[$root]['google-order-number']['VALUE'];
440 // lets retrieve the private-data
441 $privateData = $data[$root]['shopping-cart']['merchant-private-data']['VALUE'];
442 $privateData = $privateData ? self
::stringToArray($privateData) : '';
444 list($mode, $module, $paymentProcessorID) = self
::getContext($xml_response, $privateData, $orderNo, $root);
445 $mode = $mode ?
'test' : 'live';
447 require_once 'CRM/Financial/BAO/PaymentProcessor.php';
448 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
452 $ipn = &self
::singleton($mode, $module, $paymentProcessor);
454 // Create new response object
455 $merchant_id = $paymentProcessor['user_name'];
456 $merchant_key = $paymentProcessor['password'];
457 $server_type = ($mode == 'test') ?
"sandbox" : '';
459 $response = new GoogleResponse($merchant_id, $merchant_key,
460 $xml_response, $server_type
462 if (GOOGLE_DEBUG_PP
) {
463 CRM_Core_Error
::debug_var('RESPONSE-ROOT', $response->root
, TRUE, TRUE, 'Google');
466 //Check status and take appropriate action
467 $status = $response->HttpAuthentication($headers);
470 case "request-received":
473 case "checkout-redirect":
474 case "merchant-calculation-callback":
477 case "new-order-notification": {
478 $response->SendAck();
479 $ipn->newOrderNotify($data[$root], $privateData, $module);
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'];
487 switch ($new_financial_state) {
489 $amount = $ipn->getAmount($orderNo);
491 $response->SendChargeOrder($data[$root]['google-order-number']['VALUE'],
492 $amount, $message_log
494 $response->SendProcessOrder($data[$root]['google-order-number']['VALUE'],
501 case 'PAYMENT_DECLINED':
503 $ipn->orderStateChange($new_financial_state, $data[$root], $module);
508 case 'CANCELLED_BY_GOOGLE':
515 case "charge-amount-notification":
516 case "chargeback-amount-notification":
517 case "refund-amount-notification":
518 case "risk-information-notification":
519 $response->SendAck();
527 function getInput(&$input, &$ids) {
528 if (!$this->getBillingID($ids)) {
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',
543 foreach ($lookup as $name => $googleName) {
544 $value = $dataRoot['buyer-billing-address'][$googleName]['VALUE'];
545 $input[$name] = $value ?
$value : NULL;
551 * Converts the comma separated name-value pairs in <merchant-private-data>
552 * to an array of name-value pairs.
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];