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 define('GOOGLE_DEBUG_PP', 0);
38 class CRM_Core_Payment_GoogleIPN
extends CRM_Core_Payment_BaseIPN
{
41 * We only need one instance of this object. So we use the singleton
42 * pattern and cache the instance in this variable
47 static private $_singleton = NULL;
50 * mode of operation: live or test
54 protected $_mode = NULL;
56 static function retrieve($name, $type, $object, $abort = TRUE) {
57 $value = CRM_Utils_Array
::value($name, $object);
58 if ($abort && $value === NULL) {
59 CRM_Core_Error
::debug_log_message("Could not find an entry for $name");
60 echo "Failure: Missing Parameter<p>";
65 if (!CRM_Utils_Type
::validate($value, $type)) {
66 CRM_Core_Error
::debug_log_message("Could not find a valid entry for $name");
67 echo "Failure: Invalid Parameter<p>";
78 * @param string $mode the mode of operation: live or test
82 function __construct($mode, &$paymentProcessor) {
83 parent
::__construct();
86 $this->_paymentProcessor
= $paymentProcessor;
90 * The function gets called when a new order takes place.
92 * @param xml $dataRoot response send by google in xml format
93 * @param array $privateData contains the name value pair of <merchant-private-data>
98 function newOrderNotify($dataRoot, $privateData, $component) {
99 $ids = $input = $params = array();
101 $input['component'] = strtolower($component);
103 $ids['contact'] = self
::retrieve('contactID', 'Integer', $privateData, TRUE);
104 $ids['contribution'] = self
::retrieve('contributionID', 'Integer', $privateData, TRUE);
106 $ids['contributionRecur'] = $ids['contributionPage'] = NULL;
107 if ($input['component'] == "event") {
108 $ids['event'] = self
::retrieve('eventID', 'Integer', $privateData, TRUE);
109 $ids['participant'] = self
::retrieve('participantID', 'Integer', $privateData, TRUE);
110 $ids['membership'] = NULL;
113 $ids['membership'] = self
::retrieve('membershipID', 'Integer', $privateData, FALSE);
114 $ids['related_contact'] = self
::retrieve('relatedContactID', 'Integer', $privateData, FALSE);
115 $ids['onbehalf_dupe_alert'] = self
::retrieve('onBehalfDupeAlert', 'Integer', $privateData, FALSE);
116 $ids['contributionRecur'] = self
::retrieve('contributionRecurID', 'Integer', $privateData, FALSE);
119 $paymentProcessorID = CRM_Core_DAO
::getFieldValue(
120 'CRM_Financial_DAO_PaymentProcessorType',
123 'payment_processor_type'
126 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
130 $input['invoice'] = $privateData['invoiceID'];
131 $input['newInvoice'] = $dataRoot['google-order-number']['VALUE'];
133 if ($ids['contributionRecur']) {
134 if ($objects['contributionRecur']->invoice_id
== $dataRoot['serial-number']) {
135 CRM_Core_Error
::debug_log_message("The new order notification already handled: {$dataRoot['serial-number']}.");
139 $transaction = new CRM_Core_Transaction();
141 CRM_Core_Error
::debug_log_message("New order for an installment received.");
142 $recur = &$objects['contributionRecur'];
144 // fix dates that already exist
145 $dates = array('create', 'start', 'end', 'cancel', 'modified');
146 foreach ($dates as $date) {
147 $name = "{$date}_date";
149 $recur->$name = CRM_Utils_Date
::isoToMysql($recur->$name);
152 $recur->invoice_id
= $dataRoot['serial-number'];
153 $recur->processor_id
= $input['newInvoice'];
156 if ($objects['contribution']->contribution_status_id
== 1) {
157 // create a contribution and then get it processed
158 $contribution = new CRM_Contribute_DAO_Contribution();
159 $contribution->contact_id
= $ids['contact'];
160 $contribution->financial_type_id
= $objects['contributionType']->id
;
161 $contribution->contribution_page_id
= $objects['contribution']->contribution_page_id
;
162 $contribution->contribution_recur_id
= $ids['contributionRecur'];
163 $contribution->receive_date
= date('YmdHis');
164 $contribution->currency
= $objects['contribution']->currency
;
165 $contribution->payment_instrument_id
= $objects['contribution']->payment_instrument_id
;
166 $contribution->amount_level
= $objects['contribution']->amount_level
;
167 $contribution->address_id
= $objects['contribution']->address_id
;
168 $contribution->invoice_id
= $input['invoice'];
169 $contribution->total_amount
= $dataRoot['order-total']['VALUE'];
170 $contribution->contribution_status_id
= 2;
171 $contribution->campaign_id
= $objects['contribution']->campaign_id
;
173 $objects['contribution'] = $contribution;
175 $transaction->commit();
179 // make sure the invoice is valid and matches what we have in the contribution record
180 $contribution = &$objects['contribution'];
182 if ($contribution->invoice_id
!= $input['invoice']) {
183 CRM_Core_Error
::debug_log_message("Invoice values dont match between database and IPN request");
187 // lets replace invoice-id with google-order-number because thats what is common and unique
188 // in subsequent calls or notifications sent by google.
189 $contribution->invoice_id
= $input['newInvoice'];
191 $input['amount'] = $dataRoot['order-total']['VALUE'];
193 if ($contribution->total_amount
!= $input['amount']) {
194 CRM_Core_Error
::debug_log_message("Amount values dont match between database and IPN request");
198 if (!$this->getInput($input, $ids, $dataRoot)) {
202 $transaction = new CRM_Core_Transaction();
204 // check if contribution is already completed, if so we ignore this ipn
205 if ($contribution->contribution_status_id
== 1) {
206 CRM_Core_Error
::debug_log_message("returning since contribution has already been handled");
210 /* Since trxn_id hasn't got any use here,
211 * lets make use of it by passing the eventID/membershipTypeID to next level.
212 * And change trxn_id to google-order-number before finishing db update */
214 if (!empty($ids['event'])) {
215 $contribution->trxn_id
= $ids['event'] . CRM_Core_DAO
::VALUE_SEPARATOR
. $ids['participant'];
217 elseif (!empty($ids['membership'])) {
218 $contribution->trxn_id
= $ids['membership'][0] . CRM_Core_DAO
::VALUE_SEPARATOR
. $ids['related_contact'] . CRM_Core_DAO
::VALUE_SEPARATOR
. $ids['onbehalf_dupe_alert'];
222 // CRM_Core_Error::debug_var( 'c', $contribution );
223 $contribution->save();
224 $transaction->commit();
230 * The function gets called when the state(CHARGED, CANCELLED..) changes for an order
232 * @param string $status status of the transaction send by google
233 * @param array $privateData contains the name value pair of <merchant-private-data>
238 function orderStateChange($status, $dataRoot, $privateData, $component) {
239 $input = $objects = $ids = array();
240 $input['component'] = strtolower($component);
242 $ids['contributionRecur'] = self
::retrieve('contributionRecurID', 'Integer', $privateData, FALSE);
243 $serial = $dataRoot['serial-number'];
244 $orderNo = $dataRoot['google-order-number']['VALUE'];
246 $contribution = new CRM_Contribute_BAO_Contribution();
247 $contribution->invoice_id
= $orderNo;
249 if (!$contribution->find(TRUE)) {
250 CRM_Core_Error
::debug_log_message("orderStateChange: Could not find contribution record with invoice id: $serial");
254 // Google sends the charged notification twice.
255 // So to make sure, code is not executed again.
256 if ($contribution->contribution_status_id
== 1) {
257 CRM_Core_Error
::debug_log_message("Contribution already handled (ContributionID = {$contribution->id}).");
261 // make sure invoice is set to serial no for recurring payments, to avoid violating uniqueness
262 $contribution->invoice_id
= $ids['contributionRecur'] ?
$serial : $orderNo;
264 $objects['contribution'] = &$contribution;
265 $ids['contribution'] = $contribution->id
;
266 $ids['contact'] = $contribution->contact_id
;
268 $ids['event'] = $ids['participant'] = $ids['membership'] = NULL;
269 $ids['contributionPage'] = NULL;
271 if ($input['component'] == "event") {
272 list($ids['event'], $ids['participant']) = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
273 $contribution->trxn_id
277 $ids['related_contact'] = NULL;
278 $ids['onbehalf_dupe_alert'] = NULL;
279 if ($contribution->trxn_id
) {
280 list($ids['membership'], $ids['related_contact'], $ids['onbehalf_dupe_alert']) = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
281 $contribution->trxn_id
285 'membership', 'related_contact', 'onbehalf_dupe_alert') as $fld) {
286 if (!is_numeric($ids[$fld])) {
292 $paymentProcessorID = CRM_Core_DAO
::getFieldValue(
293 'CRM_Financial_DAO_PaymentProcessorType',
296 'payment_processor_type'
299 $this->loadObjects($input, $ids, $objects, TRUE, $paymentProcessorID);
301 $transaction = new CRM_Core_Transaction();
303 // CRM_Core_Error::debug_var( 'c', $contribution );
304 if ($status == 'PAYMENT_DECLINED' ||
305 $status == 'CANCELLED_BY_GOOGLE' ||
306 $status == 'CANCELLED'
308 return $this->failed($objects, $transaction);
311 $input['amount'] = $contribution->total_amount
;
312 $input['fee_amount'] = NULL;
313 $input['net_amount'] = NULL;
314 $input['trxn_id'] = $ids['contributionRecur'] ?
$serial : $dataRoot['google-order-number']['VALUE'];
315 $input['is_test'] = $contribution->is_test
;
318 if ($ids['contributionRecur']) {
319 $recur = $objects['contributionRecur'];
321 $this->completeTransaction($input, $ids, $objects, $transaction, $recur);
323 $this->completeRecur($input, $ids, $objects);
326 function completeRecur($input, $ids, $objects) {
327 if ($ids['contributionRecur']) {
328 $recur = &$objects['contributionRecur'];
329 $contributionCount = CRM_Core_DAO
::singleValueQuery("
331 FROM civicrm_contribution
332 WHERE contribution_recur_id = {$ids['contributionRecur']}
334 $autoRenewMembership = FALSE;
336 isset($ids['membership']) &&
339 $autoRenewMembership = TRUE;
341 if ($recur->installments
&& ($contributionCount >= $recur->installments
)) {
342 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
344 $recur->create_date
= CRM_Utils_Date
::isoToMysql($recur->create_date
);
345 $recur->start_date
= CRM_Utils_Date
::isoToMysql($recur->start_date
);
346 $recur->cancel_date
= CRM_Utils_Date
::isoToMysql($recur->cancel_date
);
347 $recur->end_date
= date('YmdHis');
348 $recur->modified_date
= date('YmdHis');
349 $recur->contribution_status_id
= array_search('Completed', $contributionStatus);
350 $recur->trnx_id
= $dataRoot['google-order-number']['VALUE'];
353 //send recurring Notification email for user
354 CRM_Contribute_BAO_ContributionPage
::recurringNotify(
355 CRM_Core_Payment
::RECURRING_PAYMENT_END
,
357 $ids['contributionPage'],
362 elseif ($contributionCount == 1) {
363 CRM_Contribute_BAO_ContributionPage
::recurringNotify(
364 CRM_Core_Payment
::RECURRING_PAYMENT_START
,
366 $ids['contributionPage'],
375 * singleton function used to manage this object
377 * @param string $mode the mode of operation: live or test
382 static function &singleton($mode, $component, &$paymentProcessor) {
383 if (self
::$_singleton === NULL) {
384 self
::$_singleton = new CRM_Core_Payment_GoogleIPN($mode, $paymentProcessor);
386 return self
::$_singleton;
390 * The function retrieves the amount the contribution is for, based on the order-no google sends
392 * @param int $orderNo <order-total> send by google
397 function getAmount($orderNo) {
398 $contribution = new CRM_Contribute_DAO_Contribution();
399 $contribution->invoice_id
= $orderNo;
400 if (!$contribution->find(TRUE)) {
401 CRM_Core_Error
::debug_log_message("getAmount: Could not find contribution record with invoice id: $orderNo");
402 echo "Failure: Could not find contribution record with invoice id: $orderNo <p>";
405 return $contribution->total_amount
;
409 * The function returns the component(Event/Contribute..), given the google-order-no and merchant-private-data
411 * @param xml $xml_response response send by google in xml format
412 * @param array $privateData contains the name value pair of <merchant-private-data>
413 * @param int $orderNo <order-total> send by google
414 * @param string $root root of xml-response
416 * @return array context of this call (test, module, payment processor id)
419 function getContext($privateData, $orderNo, $root, $response, $serial) {
420 $contributionID = CRM_Utils_Array
::value('contributionID', $privateData);
421 $contribution = new CRM_Contribute_DAO_Contribution();
422 if ($root == 'new-order-notification') {
423 $contribution->id
= $contributionID;
426 $contribution->invoice_id
= $orderNo;
428 if (!$contribution->find(TRUE)) {
429 CRM_Core_Error
::debug_log_message("getContext: Could not find contribution record with invoice id: $orderNo");
430 $response->SendAck($serial);
433 $module = 'Contribute';
434 if (stristr($contribution->source
, ts('Online Contribution'))) {
435 $module = 'Contribute';
437 elseif (stristr($contribution->source
, ts('Online Event Registration'))) {
440 $isTest = $contribution->is_test
;
442 $ids = $input = $objects = array();
443 $objects['contribution'] = &$contribution;
444 $ids['contributionRecur'] = self
::retrieve('contributionRecurID', 'Integer', $privateData, FALSE);
445 $input['component'] = strtolower($module);
447 if (!$ids['contributionRecur'] && $contribution->contribution_status_id
== 1) {
448 CRM_Core_Error
::debug_log_message("Contribution already handled (ContributionID = {$contribution->id}).");
449 // There is no point in going further. Return ack so we don't receive the same ipn.
450 $response->SendAck($serial);
453 if ($input['component'] == 'event') {
454 if ($root == 'new-order-notification') {
455 $ids['event'] = $privateData['eventID'];
458 list($ids['event'], $ids['participant']) =
459 explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $contribution->trxn_id
);
463 $paymentProcessorID = CRM_Core_DAO
::getFieldValue(
464 'CRM_Financial_DAO_PaymentProcessor',
467 'payment_processor_type'
470 $this->loadObjects($input, $ids, $objects, FALSE, $paymentProcessorID);
472 if (!$ids['paymentProcessor']) {
473 CRM_Core_Error
::debug_log_message("Payment processor could not be retrieved.");
474 // There is no point in going further. Return ack so we don't receive the same ipn.
475 $response->SendAck($serial);
478 return array($isTest, $input['component'], $ids['paymentProcessor']);
482 * This method is handles the response that will be invoked (from extern/googleNotify) every time
483 * a notification or request is sent by the Google Server.
486 static function main($xml_response) {
487 require_once 'Google/library/googleresponse.php';
488 require_once 'Google/library/googlerequest.php';
489 require_once 'Google/library/googlemerchantcalculations.php';
490 require_once 'Google/library/googleresult.php';
491 require_once 'Google/library/xml-processing/gc_xmlparser.php';
493 $config = CRM_Core_Config
::singleton();
495 // Retrieve the XML sent in the HTTP POST request to the ResponseHandler
496 if (get_magic_quotes_gpc()) {
497 $xml_response = stripslashes($xml_response);
500 $headers = CRM_Utils_System
::getAllHeaders();
502 if (GOOGLE_DEBUG_PP
) {
503 CRM_Core_Error
::debug_var('RESPONSE', $xml_response, TRUE, TRUE, 'Google');
506 // Retrieve the root and data from the xml response
507 $response = new GoogleResponse();
508 list($root, $data) = $response->GetParsedXML($xml_response);
509 // lets retrieve the private-data & order-no
511 if (array_key_exists('shopping-cart', $data[$root])) {
512 $privateData = $data[$root]['shopping-cart']['merchant-private-data']['VALUE'];
514 if (empty($privateData) && array_key_exists('order-summary', $data[$root])
515 && array_key_exists('shopping-cart', $data[$root]['order-summary'])) {
516 $privateData = $data[$root]['order-summary']['shopping-cart']['merchant-private-data']['VALUE'];
518 $privateData = $privateData ? self
::stringToArray($privateData) : '';
519 $orderNo = $data[$root]['google-order-number']['VALUE'];
520 $serial = $data[$root]['serial-number'];
522 // a dummy object to call get context and a parent function inside it.
523 $ipn = new CRM_Core_Payment_GoogleIPN('live', $dummyProcessor);
524 list($mode, $module, $paymentProcessorID) = $ipn->getContext($privateData, $orderNo, $root, $response, $serial);
525 $mode = $mode ?
'test' : 'live';
527 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID, $mode);
528 $merchant_id = $paymentProcessor['user_name'];
529 $merchant_key = $paymentProcessor['password'];
530 $response->SetMerchantAuthentication($merchant_id, $merchant_key);
532 $server_type = ($mode == 'test') ?
'sandbox' : 'production';
533 $request = new GoogleRequest($merchant_id, $merchant_key, $server_type);
535 $ipn = self
::singleton($mode, $module, $paymentProcessor);
537 if (GOOGLE_DEBUG_PP
) {
538 CRM_Core_Error
::debug_var('RESPONSE-ROOT', $response->root
, TRUE, TRUE, 'Google');
541 //Check status and take appropriate action
542 $status = $response->HttpAuthentication($headers);
545 case "request-received":
548 case "checkout-redirect":
549 case "merchant-calculation-callback":
552 case "new-order-notification": {
553 $response->SendAck($serial, FALSE);
554 $ipn->newOrderNotify($data[$root], $privateData, $module);
558 case "order-state-change-notification": {
559 $response->SendAck($serial, FALSE);
560 $new_financial_state = $data[$root]['new-financial-order-state']['VALUE'];
561 $new_fulfillment_order = $data[$root]['new-fulfillment-order-state']['VALUE'];
563 switch ($new_financial_state) {
568 case 'PAYMENT_DECLINED':
570 case 'CANCELLED_BY_GOOGLE':
571 $ipn->orderStateChange($new_financial_state, $data[$root], $privateData, $module);
584 case "authorization-amount-notification": {
585 $response->SendAck($serial, FALSE);
586 $new_financial_state = $data[$root]['order-summary']['financial-order-state']['VALUE'];
587 $new_fulfillment_order = $data[$root]['order-summary']['fulfillment-order-state']['VALUE'];
589 switch ($new_financial_state) {
591 // For google-handled subscriptions chargeorder needn't be initiated,
592 // assuming auto-charging is turned on.
593 //$request->SendProcessOrder($data[$root]['google-order-number']['VALUE']);
594 //$request->SendChargeOrder($data[$root]['google-order-number']['VALUE'],'');
598 case 'PAYMENT_DECLINED':
604 case 'CANCELLED_BY_GOOGLE':
613 case "charge-amount-notification":
614 case "chargeback-amount-notification":
615 case "refund-amount-notification":
616 case "risk-information-notification":
617 $response->SendAck($serial);
625 function getInput(&$input, &$ids, $dataRoot) {
626 if (!$this->getBillingID($ids)) {
630 $billingID = $ids['billing'];
632 "first_name" => 'contact-name',
633 // "last-name" not available with google (every thing in contact-name)
634 "last_name" => 'last_name',
635 "street_address-{$billingID}" => 'address1',
636 "city-{$billingID}" => 'city',
637 "state-{$billingID}" => 'region',
638 "postal_code-{$billingID}" => 'postal-code',
639 "country-{$billingID}" => 'country-code',
642 foreach ($lookup as $name => $googleName) {
643 if (array_key_exists($googleName, $dataRoot['buyer-billing-address'])) {
644 $value = $dataRoot['buyer-billing-address'][$googleName]['VALUE'];
646 $input[$name] = $value ?
$value : NULL;
652 * Converts the comma separated name-value pairs in <merchant-private-data>
653 * to an array of name-value pairs.
655 static function stringToArray($str) {
656 $vars = $labels = array();
657 $labels = explode(',', $str);
658 foreach ($labels as $label) {
659 $terms = explode('=', $label);
660 $vars[$terms[0]] = $terms[1];