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);
40 * Class CRM_Core_Payment_GoogleIPN
42 class CRM_Core_Payment_GoogleIPN
extends CRM_Core_Payment_BaseIPN
{
45 * We only need one instance of this object. So we use the singleton
46 * pattern and cache the instance in this variable
51 static private $_singleton = NULL;
54 * Mode of operation: live or test
58 protected $_mode = NULL;
68 static function retrieve($name, $type, $object, $abort = TRUE) {
69 $value = CRM_Utils_Array
::value($name, $object);
70 if ($abort && $value === NULL) {
71 CRM_Core_Error
::debug_log_message("Could not find an entry for $name");
72 echo "Failure: Missing Parameter<p>";
77 if (!CRM_Utils_Type
::validate($value, $type)) {
78 CRM_Core_Error
::debug_log_message("Could not find a valid entry for $name");
79 echo "Failure: Invalid Parameter<p>";
90 * @param string $mode the mode of operation: live or test
92 * @param $paymentProcessor
94 * @return \CRM_Core_Payment_GoogleIPN
96 function __construct($mode, &$paymentProcessor) {
97 parent
::__construct();
100 $this->_paymentProcessor
= $paymentProcessor;
104 * The function gets called when a new order takes place.
106 * @param xml $dataRoot response send by google in xml format
107 * @param array $privateData contains the name value pair of <merchant-private-data>
113 function newOrderNotify($dataRoot, $privateData, $component) {
114 $ids = $input = $params = array();
116 $input['component'] = strtolower($component);
118 $ids['contact'] = self
::retrieve('contactID', 'Integer', $privateData, TRUE);
119 $ids['contribution'] = self
::retrieve('contributionID', 'Integer', $privateData, TRUE);
121 $ids['contributionRecur'] = $ids['contributionPage'] = NULL;
122 if ($input['component'] == "event") {
123 $ids['event'] = self
::retrieve('eventID', 'Integer', $privateData, TRUE);
124 $ids['participant'] = self
::retrieve('participantID', 'Integer', $privateData, TRUE);
125 $ids['membership'] = NULL;
128 $ids['membership'] = self
::retrieve('membershipID', 'Integer', $privateData, FALSE);
129 $ids['related_contact'] = self
::retrieve('relatedContactID', 'Integer', $privateData, FALSE);
130 $ids['onbehalf_dupe_alert'] = self
::retrieve('onBehalfDupeAlert', 'Integer', $privateData, FALSE);
131 $ids['contributionRecur'] = self
::retrieve('contributionRecurID', 'Integer', $privateData, FALSE);
134 $paymentProcessorID = CRM_Core_DAO
::getFieldValue(
135 'CRM_Financial_DAO_PaymentProcessorType',
138 'payment_processor_type'
141 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
145 $input['invoice'] = $privateData['invoiceID'];
146 $input['newInvoice'] = $dataRoot['google-order-number']['VALUE'];
148 if ($ids['contributionRecur']) {
149 if ($objects['contributionRecur']->invoice_id
== $dataRoot['serial-number']) {
150 CRM_Core_Error
::debug_log_message("The new order notification already handled: {$dataRoot['serial-number']}.");
154 $transaction = new CRM_Core_Transaction();
156 CRM_Core_Error
::debug_log_message("New order for an installment received.");
157 $recur = &$objects['contributionRecur'];
159 // fix dates that already exist
160 $dates = array('create', 'start', 'end', 'cancel', 'modified');
161 foreach ($dates as $date) {
162 $name = "{$date}_date";
164 $recur->$name = CRM_Utils_Date
::isoToMysql($recur->$name);
167 $recur->invoice_id
= $dataRoot['serial-number'];
168 $recur->processor_id
= $input['newInvoice'];
171 if ($objects['contribution']->contribution_status_id
== 1) {
172 // create a contribution and then get it processed
173 $contribution = new CRM_Contribute_DAO_Contribution();
174 $contribution->contact_id
= $ids['contact'];
175 $contribution->financial_type_id
= $objects['contributionType']->id
;
176 $contribution->contribution_page_id
= $objects['contribution']->contribution_page_id
;
177 $contribution->contribution_recur_id
= $ids['contributionRecur'];
178 $contribution->receive_date
= date('YmdHis');
179 $contribution->currency
= $objects['contribution']->currency
;
180 $contribution->payment_instrument_id
= $objects['contribution']->payment_instrument_id
;
181 $contribution->amount_level
= $objects['contribution']->amount_level
;
182 $contribution->address_id
= $objects['contribution']->address_id
;
183 $contribution->invoice_id
= $input['invoice'];
184 $contribution->total_amount
= $dataRoot['order-total']['VALUE'];
185 $contribution->contribution_status_id
= 2;
186 $contribution->campaign_id
= $objects['contribution']->campaign_id
;
188 $objects['contribution'] = $contribution;
190 $transaction->commit();
194 // make sure the invoice is valid and matches what we have in the contribution record
195 $contribution = &$objects['contribution'];
197 if ($contribution->invoice_id
!= $input['invoice']) {
198 CRM_Core_Error
::debug_log_message("Invoice values dont match between database and IPN request");
202 // lets replace invoice-id with google-order-number because thats what is common and unique
203 // in subsequent calls or notifications sent by google.
204 $contribution->invoice_id
= $input['newInvoice'];
206 $input['amount'] = $dataRoot['order-total']['VALUE'];
208 if ($contribution->total_amount
!= $input['amount']) {
209 CRM_Core_Error
::debug_log_message("Amount values dont match between database and IPN request");
213 if (!$this->getInput($input, $ids, $dataRoot)) {
217 $transaction = new CRM_Core_Transaction();
219 // check if contribution is already completed, if so we ignore this ipn
220 if ($contribution->contribution_status_id
== 1) {
221 CRM_Core_Error
::debug_log_message("returning since contribution has already been handled");
225 /* Since trxn_id hasn't got any use here,
226 * lets make use of it by passing the eventID/membershipTypeID to next level.
227 * And change trxn_id to google-order-number before finishing db update */
229 if (!empty($ids['event'])) {
230 $contribution->trxn_id
= $ids['event'] . CRM_Core_DAO
::VALUE_SEPARATOR
. $ids['participant'];
232 elseif (!empty($ids['membership'])) {
233 $contribution->trxn_id
= $ids['membership'][0] . CRM_Core_DAO
::VALUE_SEPARATOR
. $ids['related_contact'] . CRM_Core_DAO
::VALUE_SEPARATOR
. $ids['onbehalf_dupe_alert'];
237 $contribution->save();
238 $transaction->commit();
244 * The function gets called when the state(CHARGED, CANCELLED..) changes for an order
246 * @param string $status status of the transaction send by google
248 * @param array $privateData contains the name value pair of <merchant-private-data>
254 function orderStateChange($status, $dataRoot, $privateData, $component) {
255 $input = $objects = $ids = array();
256 $input['component'] = strtolower($component);
258 $ids['contributionRecur'] = self
::retrieve('contributionRecurID', 'Integer', $privateData, FALSE);
259 $serial = $dataRoot['serial-number'];
260 $orderNo = $dataRoot['google-order-number']['VALUE'];
262 $contribution = new CRM_Contribute_BAO_Contribution();
263 $contribution->invoice_id
= $orderNo;
265 if (!$contribution->find(TRUE)) {
266 CRM_Core_Error
::debug_log_message("orderStateChange: Could not find contribution record with invoice id: $serial");
270 // Google sends the charged notification twice.
271 // So to make sure, code is not executed again.
272 if ($contribution->contribution_status_id
== 1) {
273 CRM_Core_Error
::debug_log_message("Contribution already handled (ContributionID = {$contribution->id}).");
277 // make sure invoice is set to serial no for recurring payments, to avoid violating uniqueness
278 $contribution->invoice_id
= $ids['contributionRecur'] ?
$serial : $orderNo;
280 $objects['contribution'] = &$contribution;
281 $ids['contribution'] = $contribution->id
;
282 $ids['contact'] = $contribution->contact_id
;
284 $ids['event'] = $ids['participant'] = $ids['membership'] = NULL;
285 $ids['contributionPage'] = NULL;
287 if ($input['component'] == "event") {
288 list($ids['event'], $ids['participant']) = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
289 $contribution->trxn_id
293 $ids['related_contact'] = NULL;
294 $ids['onbehalf_dupe_alert'] = NULL;
295 if ($contribution->trxn_id
) {
296 list($ids['membership'], $ids['related_contact'], $ids['onbehalf_dupe_alert']) = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
297 $contribution->trxn_id
301 'membership', 'related_contact', 'onbehalf_dupe_alert') as $fld) {
302 if (!is_numeric($ids[$fld])) {
308 $paymentProcessorID = CRM_Core_DAO
::getFieldValue(
309 'CRM_Financial_DAO_PaymentProcessorType',
312 'payment_processor_type'
315 $this->loadObjects($input, $ids, $objects, TRUE, $paymentProcessorID);
317 $transaction = new CRM_Core_Transaction();
319 if ($status == 'PAYMENT_DECLINED' ||
320 $status == 'CANCELLED_BY_GOOGLE' ||
321 $status == 'CANCELLED'
323 return $this->failed($objects, $transaction);
326 $input['amount'] = $contribution->total_amount
;
327 $input['fee_amount'] = NULL;
328 $input['net_amount'] = NULL;
329 $input['trxn_id'] = $ids['contributionRecur'] ?
$serial : $dataRoot['google-order-number']['VALUE'];
330 $input['is_test'] = $contribution->is_test
;
333 if ($ids['contributionRecur']) {
334 $recur = $objects['contributionRecur'];
336 $this->completeTransaction($input, $ids, $objects, $transaction, $recur);
338 $this->completeRecur($input, $ids, $objects);
346 function completeRecur($input, $ids, $objects) {
347 if ($ids['contributionRecur']) {
348 $recur = &$objects['contributionRecur'];
349 $contributionCount = CRM_Core_DAO
::singleValueQuery("
351 FROM civicrm_contribution
352 WHERE contribution_recur_id = {$ids['contributionRecur']}
354 $autoRenewMembership = FALSE;
356 isset($ids['membership']) &&
359 $autoRenewMembership = TRUE;
361 if ($recur->installments
&& ($contributionCount >= $recur->installments
)) {
362 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
364 $recur->create_date
= CRM_Utils_Date
::isoToMysql($recur->create_date
);
365 $recur->start_date
= CRM_Utils_Date
::isoToMysql($recur->start_date
);
366 $recur->cancel_date
= CRM_Utils_Date
::isoToMysql($recur->cancel_date
);
367 $recur->end_date
= date('YmdHis');
368 $recur->modified_date
= date('YmdHis');
369 $recur->contribution_status_id
= array_search('Completed', $contributionStatus);
370 $recur->trnx_id
= $dataRoot['google-order-number']['VALUE'];
373 //send recurring Notification email for user
374 CRM_Contribute_BAO_ContributionPage
::recurringNotify(
375 CRM_Core_Payment
::RECURRING_PAYMENT_END
,
377 $ids['contributionPage'],
382 elseif ($contributionCount == 1) {
383 CRM_Contribute_BAO_ContributionPage
::recurringNotify(
384 CRM_Core_Payment
::RECURRING_PAYMENT_START
,
386 $ids['contributionPage'],
395 * Singleton function used to manage this object
397 * @param string $mode the mode of operation: live or test
400 * @param $paymentProcessor
405 static function &singleton($mode, $component, &$paymentProcessor) {
406 if (self
::$_singleton === NULL) {
407 self
::$_singleton = new CRM_Core_Payment_GoogleIPN($mode, $paymentProcessor);
409 return self
::$_singleton;
413 * The function retrieves the amount the contribution is for, based on the order-no google sends
415 * @param int $orderNo <order-total> send by google
420 function getAmount($orderNo) {
421 $contribution = new CRM_Contribute_DAO_Contribution();
422 $contribution->invoice_id
= $orderNo;
423 if (!$contribution->find(TRUE)) {
424 CRM_Core_Error
::debug_log_message("getAmount: Could not find contribution record with invoice id: $orderNo");
425 echo "Failure: Could not find contribution record with invoice id: $orderNo <p>";
428 return $contribution->total_amount
;
432 * The function returns the component(Event/Contribute..), given the google-order-no and merchant-private-data
434 * @param array $privateData contains the name value pair of <merchant-private-data>
435 * @param int $orderNo <order-total> send by google
436 * @param string $root root of xml-response
440 * @internal param \xml $xml_response response send by google in xml format
441 * @return array context of this call (test, module, payment processor id)
444 function getContext($privateData, $orderNo, $root, $response, $serial) {
445 $contributionID = CRM_Utils_Array
::value('contributionID', $privateData);
446 $contribution = new CRM_Contribute_DAO_Contribution();
447 if ($root == 'new-order-notification') {
448 $contribution->id
= $contributionID;
451 $contribution->invoice_id
= $orderNo;
453 if (!$contribution->find(TRUE)) {
454 CRM_Core_Error
::debug_log_message("getContext: Could not find contribution record with invoice id: $orderNo");
455 $response->SendAck($serial);
458 $module = 'Contribute';
459 if (stristr($contribution->source
, ts('Online Contribution'))) {
460 $module = 'Contribute';
462 elseif (stristr($contribution->source
, ts('Online Event Registration'))) {
465 $isTest = $contribution->is_test
;
467 $ids = $input = $objects = array();
468 $objects['contribution'] = &$contribution;
469 $ids['contributionRecur'] = self
::retrieve('contributionRecurID', 'Integer', $privateData, FALSE);
470 $input['component'] = strtolower($module);
472 if (!$ids['contributionRecur'] && $contribution->contribution_status_id
== 1) {
473 CRM_Core_Error
::debug_log_message("Contribution already handled (ContributionID = {$contribution->id}).");
474 // There is no point in going further. Return ack so we don't receive the same ipn.
475 $response->SendAck($serial);
478 if ($input['component'] == 'event') {
479 if ($root == 'new-order-notification') {
480 $ids['event'] = $privateData['eventID'];
483 list($ids['event'], $ids['participant']) =
484 explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $contribution->trxn_id
);
488 $paymentProcessorID = CRM_Core_DAO
::getFieldValue(
489 'CRM_Financial_DAO_PaymentProcessor',
492 'payment_processor_type'
495 $this->loadObjects($input, $ids, $objects, FALSE, $paymentProcessorID);
497 if (!$ids['paymentProcessor']) {
498 CRM_Core_Error
::debug_log_message("Payment processor could not be retrieved.");
499 // There is no point in going further. Return ack so we don't receive the same ipn.
500 $response->SendAck($serial);
503 return array($isTest, $input['component'], $ids['paymentProcessor']);
507 * This method is handles the response that will be invoked (from extern/googleNotify) every time
508 * a notification or request is sent by the Google Server.
511 static function main($xml_response) {
512 require_once 'Google/library/googleresponse.php';
513 require_once 'Google/library/googlerequest.php';
514 require_once 'Google/library/googlemerchantcalculations.php';
515 require_once 'Google/library/googleresult.php';
516 require_once 'Google/library/xml-processing/gc_xmlparser.php';
518 $config = CRM_Core_Config
::singleton();
520 // Retrieve the XML sent in the HTTP POST request to the ResponseHandler
521 if (get_magic_quotes_gpc()) {
522 $xml_response = stripslashes($xml_response);
525 $headers = CRM_Utils_System
::getAllHeaders();
527 if (GOOGLE_DEBUG_PP
) {
528 CRM_Core_Error
::debug_var('RESPONSE', $xml_response, TRUE, TRUE, 'Google');
531 // Retrieve the root and data from the xml response
532 $response = new GoogleResponse();
533 list($root, $data) = $response->GetParsedXML($xml_response);
534 // lets retrieve the private-data & order-no
536 if (array_key_exists('shopping-cart', $data[$root])) {
537 $privateData = $data[$root]['shopping-cart']['merchant-private-data']['VALUE'];
539 if (empty($privateData) && array_key_exists('order-summary', $data[$root])
540 && array_key_exists('shopping-cart', $data[$root]['order-summary'])) {
541 $privateData = $data[$root]['order-summary']['shopping-cart']['merchant-private-data']['VALUE'];
543 $privateData = $privateData ? self
::stringToArray($privateData) : '';
544 $orderNo = $data[$root]['google-order-number']['VALUE'];
545 $serial = $data[$root]['serial-number'];
547 // a dummy object to call get context and a parent function inside it.
548 $ipn = new CRM_Core_Payment_GoogleIPN('live', $dummyProcessor);
549 list($mode, $module, $paymentProcessorID) = $ipn->getContext($privateData, $orderNo, $root, $response, $serial);
550 $mode = $mode ?
'test' : 'live';
552 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID, $mode);
553 $merchant_id = $paymentProcessor['user_name'];
554 $merchant_key = $paymentProcessor['password'];
555 $response->SetMerchantAuthentication($merchant_id, $merchant_key);
557 $server_type = ($mode == 'test') ?
'sandbox' : 'production';
558 $request = new GoogleRequest($merchant_id, $merchant_key, $server_type);
560 $ipn = self
::singleton($mode, $module, $paymentProcessor);
562 if (GOOGLE_DEBUG_PP
) {
563 CRM_Core_Error
::debug_var('RESPONSE-ROOT', $response->root
, TRUE, TRUE, 'Google');
566 //Check status and take appropriate action
567 $status = $response->HttpAuthentication($headers);
570 case "request-received":
573 case "checkout-redirect":
574 case "merchant-calculation-callback":
577 case "new-order-notification": {
578 $response->SendAck($serial, FALSE);
579 $ipn->newOrderNotify($data[$root], $privateData, $module);
583 case "order-state-change-notification": {
584 $response->SendAck($serial, FALSE);
585 $new_financial_state = $data[$root]['new-financial-order-state']['VALUE'];
586 $new_fulfillment_order = $data[$root]['new-fulfillment-order-state']['VALUE'];
588 switch ($new_financial_state) {
593 case 'PAYMENT_DECLINED':
595 case 'CANCELLED_BY_GOOGLE':
596 $ipn->orderStateChange($new_financial_state, $data[$root], $privateData, $module);
609 case "authorization-amount-notification": {
610 $response->SendAck($serial, FALSE);
611 $new_financial_state = $data[$root]['order-summary']['financial-order-state']['VALUE'];
612 $new_fulfillment_order = $data[$root]['order-summary']['fulfillment-order-state']['VALUE'];
614 switch ($new_financial_state) {
616 // For google-handled subscriptions chargeorder needn't be initiated,
617 // assuming auto-charging is turned on.
618 //$request->SendProcessOrder($data[$root]['google-order-number']['VALUE']);
619 //$request->SendChargeOrder($data[$root]['google-order-number']['VALUE'],'');
623 case 'PAYMENT_DECLINED':
629 case 'CANCELLED_BY_GOOGLE':
638 case "charge-amount-notification":
639 case "chargeback-amount-notification":
640 case "refund-amount-notification":
641 case "risk-information-notification":
642 $response->SendAck($serial);
657 function getInput(&$input, &$ids, $dataRoot) {
658 if (!$this->getBillingID($ids)) {
662 $billingID = $ids['billing'];
664 "first_name" => 'contact-name',
665 // "last-name" not available with google (every thing in contact-name)
666 "last_name" => 'last_name',
667 "street_address-{$billingID}" => 'address1',
668 "city-{$billingID}" => 'city',
669 "state-{$billingID}" => 'region',
670 "postal_code-{$billingID}" => 'postal-code',
671 "country-{$billingID}" => 'country-code',
674 foreach ($lookup as $name => $googleName) {
675 if (array_key_exists($googleName, $dataRoot['buyer-billing-address'])) {
676 $value = $dataRoot['buyer-billing-address'][$googleName]['VALUE'];
678 $input[$name] = $value ?
$value : NULL;
684 * Converts the comma separated name-value pairs in <merchant-private-data>
685 * to an array of name-value pairs.
687 static function stringToArray($str) {
688 $vars = $labels = array();
689 $labels = explode(',', $str);
690 foreach ($labels as $label) {
691 $terms = explode('=', $label);
692 $vars[$terms[0]] = $terms[1];