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
36 define('GOOGLE_DEBUG_PP', 0);
39 * Class CRM_Core_Payment_GoogleIPN
41 class CRM_Core_Payment_GoogleIPN
extends CRM_Core_Payment_BaseIPN
{
44 * We only need one instance of this object. So we use the singleton
45 * pattern and cache the instance in this variable
49 static private $_singleton = NULL;
52 * Mode of operation: live or test
56 protected $_mode = NULL;
66 public static function retrieve($name, $type, $object, $abort = TRUE) {
67 $value = CRM_Utils_Array
::value($name, $object);
68 if ($abort && $value === NULL) {
69 CRM_Core_Error
::debug_log_message("Could not find an entry for $name");
70 echo "Failure: Missing Parameter<p>";
75 if (!CRM_Utils_Type
::validate($value, $type)) {
76 CRM_Core_Error
::debug_log_message("Could not find a valid entry for $name");
77 echo "Failure: Invalid Parameter<p>";
89 * The mode of operation: live or test.
91 * @param $paymentProcessor
93 * @return \CRM_Core_Payment_GoogleIPN
95 public function __construct($mode, &$paymentProcessor) {
96 parent
::__construct();
99 $this->_paymentProcessor
= $paymentProcessor;
103 * The function gets called when a new order takes place.
105 * @param xml $dataRoot
106 * Response send by google in xml format.
107 * @param array $privateData
108 * Contains the name value pair of <merchant-private-data>.
114 public function newOrderNotify($dataRoot, $privateData, $component) {
115 $ids = $input = $params = array();
117 $input['component'] = strtolower($component);
119 $ids['contact'] = self
::retrieve('contactID', 'Integer', $privateData, TRUE);
120 $ids['contribution'] = self
::retrieve('contributionID', 'Integer', $privateData, TRUE);
122 $ids['contributionRecur'] = $ids['contributionPage'] = NULL;
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);
132 $ids['contributionRecur'] = self
::retrieve('contributionRecurID', 'Integer', $privateData, FALSE);
135 $paymentProcessorID = CRM_Core_DAO
::getFieldValue(
136 'CRM_Financial_DAO_PaymentProcessorType',
139 'payment_processor_type'
142 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
146 $input['invoice'] = $privateData['invoiceID'];
147 $input['newInvoice'] = $dataRoot['google-order-number']['VALUE'];
149 if ($ids['contributionRecur']) {
150 if ($objects['contributionRecur']->invoice_id
== $dataRoot['serial-number']) {
151 CRM_Core_Error
::debug_log_message("The new order notification already handled: {$dataRoot['serial-number']}.");
155 $transaction = new CRM_Core_Transaction();
157 CRM_Core_Error
::debug_log_message("New order for an installment received.");
158 $recur = &$objects['contributionRecur'];
160 // fix dates that already exist
161 $dates = array('create', 'start', 'end', 'cancel', 'modified');
162 foreach ($dates as $date) {
163 $name = "{$date}_date";
165 $recur->$name = CRM_Utils_Date
::isoToMysql($recur->$name);
168 $recur->invoice_id
= $dataRoot['serial-number'];
169 $recur->processor_id
= $input['newInvoice'];
172 if ($objects['contribution']->contribution_status_id
== 1) {
173 // create a contribution and then get it processed
174 $contribution = new CRM_Contribute_DAO_Contribution();
175 $contribution->contact_id
= $ids['contact'];
176 $contribution->financial_type_id
= $objects['contributionType']->id
;
177 $contribution->contribution_page_id
= $objects['contribution']->contribution_page_id
;
178 $contribution->contribution_recur_id
= $ids['contributionRecur'];
179 $contribution->receive_date
= date('YmdHis');
180 $contribution->currency
= $objects['contribution']->currency
;
181 $contribution->payment_instrument_id
= $objects['contribution']->payment_instrument_id
;
182 $contribution->amount_level
= $objects['contribution']->amount_level
;
183 $contribution->address_id
= $objects['contribution']->address_id
;
184 $contribution->invoice_id
= $input['invoice'];
185 $contribution->total_amount
= $dataRoot['order-total']['VALUE'];
186 $contribution->contribution_status_id
= 2;
187 $contribution->campaign_id
= $objects['contribution']->campaign_id
;
189 $objects['contribution'] = $contribution;
191 $transaction->commit();
195 // make sure the invoice is valid and matches what we have in the contribution record
196 $contribution = &$objects['contribution'];
198 if ($contribution->invoice_id
!= $input['invoice']) {
199 CRM_Core_Error
::debug_log_message("Invoice values dont match between database and IPN request");
203 // lets replace invoice-id with google-order-number because thats what is common and unique
204 // in subsequent calls or notifications sent by google.
205 $contribution->invoice_id
= $input['newInvoice'];
207 $input['amount'] = $dataRoot['order-total']['VALUE'];
209 if ($contribution->total_amount
!= $input['amount']) {
210 CRM_Core_Error
::debug_log_message("Amount values dont match between database and IPN request");
214 if (!$this->getInput($input, $ids, $dataRoot)) {
218 $transaction = new CRM_Core_Transaction();
220 // check if contribution is already completed, if so we ignore this ipn
221 if ($contribution->contribution_status_id
== 1) {
222 CRM_Core_Error
::debug_log_message("returning since contribution has already been handled");
226 /* Since trxn_id hasn't got any use here,
227 * lets make use of it by passing the eventID/membershipTypeID to next level.
228 * And change trxn_id to google-order-number before finishing db update */
230 if (!empty($ids['event'])) {
231 $contribution->trxn_id
= $ids['event'] . CRM_Core_DAO
::VALUE_SEPARATOR
. $ids['participant'];
233 elseif (!empty($ids['membership'])) {
234 $contribution->trxn_id
= $ids['membership'][0] . CRM_Core_DAO
::VALUE_SEPARATOR
. $ids['related_contact'] . CRM_Core_DAO
::VALUE_SEPARATOR
. $ids['onbehalf_dupe_alert'];
238 $contribution->save();
239 $transaction->commit();
245 * The function gets called when the state(CHARGED, CANCELLED..) changes for an order
247 * @param string $status
248 * Status of the transaction send by google.
250 * @param array $privateData
251 * Contains the name value pair of <merchant-private-data>.
257 public function orderStateChange($status, $dataRoot, $privateData, $component) {
258 $input = $objects = $ids = array();
259 $input['component'] = strtolower($component);
261 $ids['contributionRecur'] = self
::retrieve('contributionRecurID', 'Integer', $privateData, FALSE);
262 $serial = $dataRoot['serial-number'];
263 $orderNo = $dataRoot['google-order-number']['VALUE'];
265 $contribution = new CRM_Contribute_BAO_Contribution();
266 $contribution->invoice_id
= $orderNo;
268 if (!$contribution->find(TRUE)) {
269 CRM_Core_Error
::debug_log_message("orderStateChange: Could not find contribution record with invoice id: $serial");
273 // Google sends the charged notification twice.
274 // So to make sure, code is not executed again.
275 if ($contribution->contribution_status_id
== 1) {
276 CRM_Core_Error
::debug_log_message("Contribution already handled (ContributionID = {$contribution->id}).");
280 // make sure invoice is set to serial no for recurring payments, to avoid violating uniqueness
281 $contribution->invoice_id
= $ids['contributionRecur'] ?
$serial : $orderNo;
283 $objects['contribution'] = &$contribution;
284 $ids['contribution'] = $contribution->id
;
285 $ids['contact'] = $contribution->contact_id
;
287 $ids['event'] = $ids['participant'] = $ids['membership'] = NULL;
288 $ids['contributionPage'] = NULL;
290 if ($input['component'] == "event") {
291 list($ids['event'], $ids['participant']) = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
292 $contribution->trxn_id
296 $ids['related_contact'] = NULL;
297 $ids['onbehalf_dupe_alert'] = NULL;
298 if ($contribution->trxn_id
) {
299 list($ids['membership'], $ids['related_contact'], $ids['onbehalf_dupe_alert']) = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
300 $contribution->trxn_id
306 'onbehalf_dupe_alert',
308 if (!is_numeric($ids[$fld])) {
314 $paymentProcessorID = CRM_Core_DAO
::getFieldValue(
315 'CRM_Financial_DAO_PaymentProcessorType',
318 'payment_processor_type'
321 $this->loadObjects($input, $ids, $objects, TRUE, $paymentProcessorID);
323 $transaction = new CRM_Core_Transaction();
325 if ($status == 'PAYMENT_DECLINED' ||
326 $status == 'CANCELLED_BY_GOOGLE' ||
327 $status == 'CANCELLED'
329 return $this->failed($objects, $transaction);
332 $input['amount'] = $contribution->total_amount
;
333 $input['fee_amount'] = NULL;
334 $input['net_amount'] = NULL;
335 $input['trxn_id'] = $ids['contributionRecur'] ?
$serial : $dataRoot['google-order-number']['VALUE'];
336 $input['is_test'] = $contribution->is_test
;
339 if ($ids['contributionRecur']) {
340 $recur = $objects['contributionRecur'];
342 $this->completeTransaction($input, $ids, $objects, $transaction, $recur);
344 $this->completeRecur($input, $ids, $objects);
352 public function completeRecur($input, $ids, $objects) {
353 if ($ids['contributionRecur']) {
354 $recur = &$objects['contributionRecur'];
355 $contributionCount = CRM_Core_DAO
::singleValueQuery("
357 FROM civicrm_contribution
358 WHERE contribution_recur_id = {$ids['contributionRecur']}
360 $autoRenewMembership = FALSE;
362 isset($ids['membership']) &&
365 $autoRenewMembership = TRUE;
367 if ($recur->installments
&& ($contributionCount >= $recur->installments
)) {
368 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
370 $recur->create_date
= CRM_Utils_Date
::isoToMysql($recur->create_date
);
371 $recur->start_date
= CRM_Utils_Date
::isoToMysql($recur->start_date
);
372 $recur->cancel_date
= CRM_Utils_Date
::isoToMysql($recur->cancel_date
);
373 $recur->end_date
= date('YmdHis');
374 $recur->modified_date
= date('YmdHis');
375 $recur->contribution_status_id
= array_search('Completed', $contributionStatus);
376 $recur->trnx_id
= $dataRoot['google-order-number']['VALUE'];
379 //send recurring Notification email for user
380 CRM_Contribute_BAO_ContributionPage
::recurringNotify(
381 CRM_Core_Payment
::RECURRING_PAYMENT_END
,
383 $ids['contributionPage'],
388 elseif ($contributionCount == 1) {
389 CRM_Contribute_BAO_ContributionPage
::recurringNotify(
390 CRM_Core_Payment
::RECURRING_PAYMENT_START
,
392 $ids['contributionPage'],
402 * Payment processor singletons removed - this is an IPN so left but probably can go
403 * Singleton function used to manage this object
405 * @param string $mode
406 * The mode of operation: live or test.
409 * @param $paymentProcessor
413 public static function &singleton($mode, $component, &$paymentProcessor) {
414 if (self
::$_singleton === NULL) {
415 self
::$_singleton = new CRM_Core_Payment_GoogleIPN($mode, $paymentProcessor);
417 return self
::$_singleton;
421 * The function retrieves the amount the contribution is for, based on the order-no google sends
423 * @param int $orderNo
424 * <order-total> send by google.
428 public function getAmount($orderNo) {
429 $contribution = new CRM_Contribute_DAO_Contribution();
430 $contribution->invoice_id
= $orderNo;
431 if (!$contribution->find(TRUE)) {
432 CRM_Core_Error
::debug_log_message("getAmount: Could not find contribution record with invoice id: $orderNo");
433 echo "Failure: Could not find contribution record with invoice id: $orderNo <p>";
436 return $contribution->total_amount
;
440 * The function returns the component(Event/Contribute..), given the google-order-no and merchant-private-data
442 * @param array $privateData
443 * Contains the name value pair of <merchant-private-data>.
444 * @param int $orderNo
445 * <order-total> send by google.
446 * @param string $root
447 * Root of xml-response.
451 * @internal param \xml $xml_response response send by google in xml format
453 * context of this call (test, module, payment processor id)
455 public function getContext($privateData, $orderNo, $root, $response, $serial) {
456 $contributionID = CRM_Utils_Array
::value('contributionID', $privateData);
457 $contribution = new CRM_Contribute_DAO_Contribution();
458 if ($root == 'new-order-notification') {
459 $contribution->id
= $contributionID;
462 $contribution->invoice_id
= $orderNo;
464 if (!$contribution->find(TRUE)) {
465 CRM_Core_Error
::debug_log_message("getContext: Could not find contribution record with invoice id: $orderNo");
466 $response->SendAck($serial);
469 $module = 'Contribute';
470 if (stristr($contribution->source
, ts('Online Contribution'))) {
471 $module = 'Contribute';
473 elseif (stristr($contribution->source
, ts('Online Event Registration'))) {
476 $isTest = $contribution->is_test
;
478 $ids = $input = $objects = array();
479 $objects['contribution'] = &$contribution;
480 $ids['contributionRecur'] = self
::retrieve('contributionRecurID', 'Integer', $privateData, FALSE);
481 $input['component'] = strtolower($module);
483 if (!$ids['contributionRecur'] && $contribution->contribution_status_id
== 1) {
484 CRM_Core_Error
::debug_log_message("Contribution already handled (ContributionID = {$contribution->id}).");
485 // There is no point in going further. Return ack so we don't receive the same ipn.
486 $response->SendAck($serial);
489 if ($input['component'] == 'event') {
490 if ($root == 'new-order-notification') {
491 $ids['event'] = $privateData['eventID'];
494 list($ids['event'], $ids['participant']) = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $contribution->trxn_id
);
498 $paymentProcessorID = CRM_Core_DAO
::getFieldValue(
499 'CRM_Financial_DAO_PaymentProcessor',
502 'payment_processor_type'
505 $this->loadObjects($input, $ids, $objects, FALSE, $paymentProcessorID);
507 if (!$ids['paymentProcessor']) {
508 CRM_Core_Error
::debug_log_message("Payment processor could not be retrieved.");
509 // There is no point in going further. Return ack so we don't receive the same ipn.
510 $response->SendAck($serial);
513 return array($isTest, $input['component'], $ids['paymentProcessor']);
517 * This method is handles the response that will be invoked (from extern/googleNotify) every time
518 * a notification or request is sent by the Google Server.
520 public static function main($xml_response) {
521 require_once 'Google/library/googleresponse.php';
522 require_once 'Google/library/googlerequest.php';
523 require_once 'Google/library/googlemerchantcalculations.php';
524 require_once 'Google/library/googleresult.php';
525 require_once 'Google/library/xml-processing/gc_xmlparser.php';
527 $config = CRM_Core_Config
::singleton();
529 // Retrieve the XML sent in the HTTP POST request to the ResponseHandler
530 if (get_magic_quotes_gpc()) {
531 $xml_response = stripslashes($xml_response);
534 $headers = CRM_Utils_System
::getAllHeaders();
536 if (GOOGLE_DEBUG_PP
) {
537 CRM_Core_Error
::debug_var('RESPONSE', $xml_response, TRUE, TRUE, 'Google');
540 // Retrieve the root and data from the xml response
541 $response = new GoogleResponse();
542 list($root, $data) = $response->GetParsedXML($xml_response);
543 // lets retrieve the private-data & order-no
545 if (array_key_exists('shopping-cart', $data[$root])) {
546 $privateData = $data[$root]['shopping-cart']['merchant-private-data']['VALUE'];
548 if (empty($privateData) && array_key_exists('order-summary', $data[$root])
549 && array_key_exists('shopping-cart', $data[$root]['order-summary'])
551 $privateData = $data[$root]['order-summary']['shopping-cart']['merchant-private-data']['VALUE'];
553 $privateData = $privateData ? self
::stringToArray($privateData) : '';
554 $orderNo = $data[$root]['google-order-number']['VALUE'];
555 $serial = $data[$root]['serial-number'];
557 // a dummy object to call get context and a parent function inside it.
558 $ipn = new CRM_Core_Payment_GoogleIPN('live', $dummyProcessor);
559 list($mode, $module, $paymentProcessorID) = $ipn->getContext($privateData, $orderNo, $root, $response, $serial);
560 $mode = $mode ?
'test' : 'live';
562 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID, $mode);
563 $merchant_id = $paymentProcessor['user_name'];
564 $merchant_key = $paymentProcessor['password'];
565 $response->SetMerchantAuthentication($merchant_id, $merchant_key);
567 $server_type = ($mode == 'test') ?
'sandbox' : 'production';
568 $request = new GoogleRequest($merchant_id, $merchant_key, $server_type);
570 $ipn = self
::singleton($mode, $module, $paymentProcessor);
572 if (GOOGLE_DEBUG_PP
) {
573 CRM_Core_Error
::debug_var('RESPONSE-ROOT', $response->root
, TRUE, TRUE, 'Google');
576 //Check status and take appropriate action
577 $status = $response->HttpAuthentication($headers);
580 case "request-received":
583 case "checkout-redirect":
584 case "merchant-calculation-callback":
587 case "new-order-notification":
588 $response->SendAck($serial, FALSE);
589 $ipn->newOrderNotify($data[$root], $privateData, $module);
592 case "order-state-change-notification":
593 $response->SendAck($serial, FALSE);
594 $new_financial_state = $data[$root]['new-financial-order-state']['VALUE'];
595 $new_fulfillment_order = $data[$root]['new-fulfillment-order-state']['VALUE'];
597 switch ($new_financial_state) {
602 case 'PAYMENT_DECLINED':
604 case 'CANCELLED_BY_GOOGLE':
605 $ipn->orderStateChange($new_financial_state, $data[$root], $privateData, $module);
617 case "authorization-amount-notification":
618 $response->SendAck($serial, FALSE);
619 $new_financial_state = $data[$root]['order-summary']['financial-order-state']['VALUE'];
620 $new_fulfillment_order = $data[$root]['order-summary']['fulfillment-order-state']['VALUE'];
622 switch ($new_financial_state) {
624 // For google-handled subscriptions chargeorder needn't be initiated,
625 // assuming auto-charging is turned on.
626 //$request->SendProcessOrder($data[$root]['google-order-number']['VALUE']);
627 //$request->SendChargeOrder($data[$root]['google-order-number']['VALUE'],'');
631 case 'PAYMENT_DECLINED':
637 case 'CANCELLED_BY_GOOGLE':
645 case "charge-amount-notification":
646 case "chargeback-amount-notification":
647 case "refund-amount-notification":
648 case "risk-information-notification":
649 $response->SendAck($serial);
664 public function getInput(&$input, &$ids, $dataRoot) {
665 if (!$this->getBillingID($ids)) {
669 $billingID = $ids['billing'];
671 "first_name" => 'contact-name',
672 // "last-name" not available with google (every thing in contact-name)
673 "last_name" => 'last_name',
674 "street_address-{$billingID}" => 'address1',
675 "city-{$billingID}" => 'city',
676 "state-{$billingID}" => 'region',
677 "postal_code-{$billingID}" => 'postal-code',
678 "country-{$billingID}" => 'country-code',
681 foreach ($lookup as $name => $googleName) {
682 if (array_key_exists($googleName, $dataRoot['buyer-billing-address'])) {
683 $value = $dataRoot['buyer-billing-address'][$googleName]['VALUE'];
685 $input[$name] = $value ?
$value : NULL;
691 * Converts the comma separated name-value pairs in <merchant-private-data>
692 * to an array of name-value pairs.
694 public static function stringToArray($str) {
695 $vars = $labels = array();
696 $labels = explode(',', $str);
697 foreach ($labels as $label) {
698 $terms = explode('=', $label);
699 $vars[$terms[0]] = $terms[1];