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);
42 * Class org_civicrm_payment_googlecheckout_GoogleIPN
44 class org_civicrm_payment_googlecheckout_GoogleIPN
extends CRM_Core_Payment_BaseIPN
{
47 * We only need one instance of this object. So we use the singleton
48 * pattern and cache the instance in this variable
53 static private $_singleton = NULL;
56 * mode of operation: live or test
61 static protected $_mode = NULL;
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>";
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>";
93 * @param string $mode the mode of operation: live or test
95 * @param $paymentProcessor
97 * @return \org_civicrm_payment_googlecheckout_GoogleIPN
99 function __construct($mode, &$paymentProcessor) {
100 parent
::__construct();
102 $this->_mode
= $mode;
103 $this->_paymentProcessor
= $paymentProcessor;
107 * The function gets called when a new order takes place.
109 * @param xml $dataRoot response send by google in xml format
110 * @param array $privateData contains the name value pair of <merchant-private-data>
115 function newOrderNotify($dataRoot, $privateData, $component) {
116 $ids = $input = $params = array();
118 $input['component'] = strtolower($component);
120 $ids['contact'] = self
::retrieve('contactID', 'Integer', $privateData, TRUE);
121 $ids['contribution'] = self
::retrieve('contributionID', 'Integer', $privateData, TRUE);
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;
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);
133 $ids['contributionRecur'] = $ids['contributionPage'] = NULL;
135 if (!$this->validateData($input, $ids, $objects)) {
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>";
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'];
153 $input['amount'] = $dataRoot['order-total']['VALUE'];
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>";
161 if (!$this->getInput($input, $ids)) {
165 require_once 'CRM/Core/Transaction.php';
166 $transaction = new CRM_Core_Transaction();
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>";
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 */
180 $contribution->trxn_id
= $ids['event'] . CRM_Core_DAO
::VALUE_SEPARATOR
. $ids['participant'];
183 $contribution->trxn_id
= $ids['membership'] . CRM_Core_DAO
::VALUE_SEPARATOR
. $ids['related_contact'] . CRM_Core_DAO
::VALUE_SEPARATOR
. $ids['onbehalf_dupe_alert'];
187 $contribution->save();
188 $transaction->commit();
193 * The function gets called when the state(CHARGED, CANCELLED..) changes for an order
195 * @param string $status status of the transaction send by google
198 * @internal param array $privateData contains the name value pair of <merchant-private-data>
202 function orderStateChange($status, $dataRoot, $component) {
203 $input = $objects = $ids = array();
205 $input['component'] = strtolower($component);
207 $orderNo = $dataRoot['google-order-number']['VALUE'];
209 require_once 'CRM/Contribute/DAO/Contribution.php';
210 $contribution = new CRM_Contribute_DAO_Contribution();
211 $contribution->invoice_id
= $orderNo;
212 if (!$contribution->find(TRUE)) {
213 CRM_Core_Error
::debug_log_message("Could not find contribution record with invoice id: $orderNo");
214 echo "Failure: Could not find contribution record with invoice id: $orderNo <p>";
218 // Google sends the charged notification twice.
219 // So to make sure, code is not executed again.
220 if ($contribution->contribution_status_id
== 1) {
221 CRM_Core_Error
::debug_log_message("Contribution already handled (ContributionID = $contribution).");
225 $objects['contribution'] = &$contribution;
226 $ids['contribution'] = $contribution->id
;
227 $ids['contact'] = $contribution->contact_id
;
229 $ids['event'] = $ids['participant'] = $ids['membership'] = NULL;
230 $ids['contributionRecur'] = $ids['contributionPage'] = NULL;
232 if ($input['component'] == "event") {
233 list($ids['event'], $ids['participant']) = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
234 $contribution->trxn_id
238 list($ids['membership'], $ids['related_contact'], $ids['onbehalf_dupe_alert']) = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
239 $contribution->trxn_id
242 foreach (array('membership', 'related_contact', 'onbehalf_dupe_alert') as $fld) {
243 if (!is_numeric($ids[$fld])) {
249 $this->loadObjects($input, $ids, $objects);
251 require_once 'CRM/Core/Transaction.php';
252 $transaction = new CRM_Core_Transaction();
254 if ($status == 'PAYMENT_DECLINED' ||
255 $status == 'CANCELLED_BY_GOOGLE' ||
256 $status == 'CANCELLED'
258 return $this->failed($objects, $transaction);
261 $input['amount'] = $contribution->total_amount
;
262 $input['fee_amount'] = NULL;
263 $input['net_amount'] = NULL;
264 $input['trxn_id'] = $orderNo;
265 $input['is_test'] = $contribution->is_test
;
267 $this->completeTransaction($input, $ids, $objects, $transaction);
271 * singleton function used to manage this object
273 * @param string $mode the mode of operation: live or test
276 * @param $paymentProcessor
281 function &singleton($mode, $component, &$paymentProcessor) {
282 if (self
::$_singleton === NULL) {
283 self
::$_singleton = new org_civicrm_payment_googlecheckout_GoogleIPN($mode, $paymentProcessor);
285 return self
::$_singleton;
289 * The function retrieves the amount the contribution is for, based on the order-no google sends
291 * @param int $orderNo <order-total> send by google
296 function getAmount($orderNo) {
297 require_once 'CRM/Contribute/DAO/Contribution.php';
298 $contribution = new CRM_Contribute_DAO_Contribution();
299 $contribution->invoice_id
= $orderNo;
300 if (!$contribution->find(TRUE)) {
301 CRM_Core_Error
::debug_log_message("Could not find contribution record with invoice id: $orderNo");
302 echo "Failure: Could not find contribution record with invoice id: $orderNo <p>";
305 return $contribution->total_amount
;
309 * The function returns the component(Event/Contribute..), given the google-order-no and merchant-private-data
311 * @param xml $xml_response response send by google in xml format
312 * @param array $privateData contains the name value pair of <merchant-private-data>
313 * @param int $orderNo <order-total> send by google
314 * @param string $root root of xml-response
316 * @return array context of this call (test, module, payment processor id)
320 function getContext($xml_response, $privateData, $orderNo, $root) {
321 require_once 'CRM/Contribute/DAO/Contribution.php';
325 if ($root == 'new-order-notification') {
326 $contributionID = $privateData['contributionID'];
327 $contribution = new CRM_Contribute_DAO_Contribution();
328 $contribution->id
= $contributionID;
329 if (!$contribution->find(TRUE)) {
330 CRM_Core_Error
::debug_log_message("Could not find contribution record: $contributionID");
331 echo "Failure: Could not find contribution record for $contributionID<p>";
334 if (stristr($contribution->source
, ts('Online Contribution'))) {
335 $module = 'Contribute';
337 elseif (stristr($contribution->source
, ts('Online Event Registration'))) {
340 $isTest = $contribution->is_test
;
343 $contribution = new CRM_Contribute_DAO_Contribution();
344 $contribution->invoice_id
= $orderNo;
345 if (!$contribution->find(TRUE)) {
346 CRM_Core_Error
::debug_log_message("Could not find contribution record with invoice id: $orderNo");
347 echo "Failure: Could not find contribution record with invoice id: $orderNo <p>";
350 if (stristr($contribution->source
, ts('Online Contribution'))) {
351 $module = 'Contribute';
353 elseif (stristr($contribution->source
, ts('Online Event Registration'))) {
356 $isTest = $contribution->is_test
;
359 if ($contribution->contribution_status_id
== 1) {
360 //contribution already handled.
364 if ($module == 'Contribute') {
365 if (!$contribution->contribution_page_id
) {
366 CRM_Core_Error
::debug_log_message("Could not find contribution page for contribution record: $contributionID");
367 echo "Failure: Could not find contribution page for contribution record: $contributionID<p>";
371 // get the payment processor id from contribution page
372 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
373 $contribution->contribution_page_id
,
374 'payment_processor_id'
378 if ($root == 'new-order-notification') {
379 $eventID = $privateData['eventID'];
382 list($eventID, $participantID) = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
383 $contribution->trxn_id
387 CRM_Core_Error
::debug_log_message("Could not find event ID");
388 echo "Failure: Could not find eventID<p>";
392 // we are in event mode
393 // make sure event exists and is valid
394 require_once 'CRM/Event/DAO/Event.php';
395 $event = new CRM_Event_DAO_Event();
396 $event->id
= $eventID;
397 if (!$event->find(TRUE)) {
398 CRM_Core_Error
::debug_log_message("Could not find event: $eventID");
399 echo "Failure: Could not find event: $eventID<p>";
403 // get the payment processor id from contribution page
404 $paymentProcessorID = $event->payment_processor_id
;
407 if (!$paymentProcessorID) {
408 CRM_Core_Error
::debug_log_message("Could not find payment processor for contribution record: $contributionID");
409 echo "Failure: Could not find payment processor for contribution record: $contributionID<p>";
413 return array($isTest, $module, $paymentProcessorID);
417 * This method is handles the response that will be invoked (from extern/googleNotify) every time
418 * a notification or request is sent by the Google Server.
422 function main($xml_response) {
423 require_once ('Google/library/googleresponse.php');
424 require_once ('Google/library/googlemerchantcalculations.php');
425 require_once ('Google/library/googleresult.php');
426 require_once ('Google/library/xml-processing/xmlparser.php');
428 $config = CRM_Core_Config
::singleton();
430 // Retrieve the XML sent in the HTTP POST request to the ResponseHandler
431 if (get_magic_quotes_gpc()) {
432 $xml_response = stripslashes($xml_response);
435 require_once 'CRM/Utils/System.php';
436 $headers = CRM_Utils_System
::getAllHeaders();
438 if (GOOGLE_DEBUG_PP
) {
439 CRM_Core_Error
::debug_var('RESPONSE', $xml_response, TRUE, TRUE, 'Google');
442 // Retrieve the root and data from the xml response
443 $xmlParser = new XmlParser($xml_response);
444 $root = $xmlParser->GetRoot();
445 $data = $xmlParser->GetData();
447 $orderNo = $data[$root]['google-order-number']['VALUE'];
449 // lets retrieve the private-data
450 $privateData = $data[$root]['shopping-cart']['merchant-private-data']['VALUE'];
451 $privateData = $privateData ? self
::stringToArray($privateData) : '';
453 list($mode, $module, $paymentProcessorID) = self
::getContext($xml_response, $privateData, $orderNo, $root);
454 $mode = $mode ?
'test' : 'live';
456 require_once 'CRM/Financial/BAO/PaymentProcessor.php';
457 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
461 $ipn = &self
::singleton($mode, $module, $paymentProcessor);
463 // Create new response object
464 $merchant_id = $paymentProcessor['user_name'];
465 $merchant_key = $paymentProcessor['password'];
466 $server_type = ($mode == 'test') ?
"sandbox" : '';
468 $response = new GoogleResponse($merchant_id, $merchant_key,
469 $xml_response, $server_type
471 if (GOOGLE_DEBUG_PP
) {
472 CRM_Core_Error
::debug_var('RESPONSE-ROOT', $response->root
, TRUE, TRUE, 'Google');
475 //Check status and take appropriate action
476 $status = $response->HttpAuthentication($headers);
479 case "request-received":
482 case "checkout-redirect":
483 case "merchant-calculation-callback":
486 case "new-order-notification": {
487 $response->SendAck();
488 $ipn->newOrderNotify($data[$root], $privateData, $module);
491 case "order-state-change-notification": {
492 $response->SendAck();
493 $new_financial_state = $data[$root]['new-financial-order-state']['VALUE'];
494 $new_fulfillment_order = $data[$root]['new-fulfillment-order-state']['VALUE'];
496 switch ($new_financial_state) {
498 $amount = $ipn->getAmount($orderNo);
500 $response->SendChargeOrder($data[$root]['google-order-number']['VALUE'],
501 $amount, $message_log
503 $response->SendProcessOrder($data[$root]['google-order-number']['VALUE'],
510 case 'PAYMENT_DECLINED':
512 $ipn->orderStateChange($new_financial_state, $data[$root], $module);
517 case 'CANCELLED_BY_GOOGLE':
524 case "charge-amount-notification":
525 case "chargeback-amount-notification":
526 case "refund-amount-notification":
527 case "risk-information-notification":
528 $response->SendAck();
542 function getInput(&$input, &$ids) {
543 if (!$this->getBillingID($ids)) {
547 $billingID = $ids['billing'];
548 $lookup = array("first_name" => 'contact-name',
549 // "last-name" not available with google (every thing in contact-name)
550 "last_name" => 'last_name',
551 "street_address-{$billingID}" => 'address1',
552 "city-{$billingID}" => 'city',
553 "state-{$billingID}" => 'region',
554 "postal_code-{$billingID}" => 'postal-code',
555 "country-{$billingID}" => 'country-code',
558 foreach ($lookup as $name => $googleName) {
559 $value = $dataRoot['buyer-billing-address'][$googleName]['VALUE'];
560 $input[$name] = $value ?
$value : NULL;
566 * Converts the comma separated name-value pairs in <merchant-private-data>
567 * to an array of name-value pairs.
570 function stringToArray($str) {
571 $vars = $labels = array();
572 $labels = explode(',', $str);
573 foreach ($labels as $label) {
574 $terms = explode('=', $label);
575 $vars[$terms[0]] = $terms[1];