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 public 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>";
91 * The mode of operation: live or test.
93 * @param $paymentProcessor
95 * @return \CRM_Core_Payment_GoogleIPN
97 public function __construct($mode, &$paymentProcessor) {
98 parent
::__construct();
100 $this->_mode
= $mode;
101 $this->_paymentProcessor
= $paymentProcessor;
105 * The function gets called when a new order takes place.
107 * @param xml $dataRoot
108 * Response send by google in xml format.
109 * @param array $privateData
110 * Contains the name value pair of <merchant-private-data>.
116 public function newOrderNotify($dataRoot, $privateData, $component) {
117 $ids = $input = $params = array();
119 $input['component'] = strtolower($component);
121 $ids['contact'] = self
::retrieve('contactID', 'Integer', $privateData, TRUE);
122 $ids['contribution'] = self
::retrieve('contributionID', 'Integer', $privateData, TRUE);
124 $ids['contributionRecur'] = $ids['contributionPage'] = NULL;
125 if ($input['component'] == "event") {
126 $ids['event'] = self
::retrieve('eventID', 'Integer', $privateData, TRUE);
127 $ids['participant'] = self
::retrieve('participantID', 'Integer', $privateData, TRUE);
128 $ids['membership'] = NULL;
131 $ids['membership'] = self
::retrieve('membershipID', 'Integer', $privateData, FALSE);
132 $ids['related_contact'] = self
::retrieve('relatedContactID', 'Integer', $privateData, FALSE);
133 $ids['onbehalf_dupe_alert'] = self
::retrieve('onBehalfDupeAlert', 'Integer', $privateData, FALSE);
134 $ids['contributionRecur'] = self
::retrieve('contributionRecurID', 'Integer', $privateData, FALSE);
137 $paymentProcessorID = CRM_Core_DAO
::getFieldValue(
138 'CRM_Financial_DAO_PaymentProcessorType',
141 'payment_processor_type'
144 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
148 $input['invoice'] = $privateData['invoiceID'];
149 $input['newInvoice'] = $dataRoot['google-order-number']['VALUE'];
151 if ($ids['contributionRecur']) {
152 if ($objects['contributionRecur']->invoice_id
== $dataRoot['serial-number']) {
153 CRM_Core_Error
::debug_log_message("The new order notification already handled: {$dataRoot['serial-number']}.");
157 $transaction = new CRM_Core_Transaction();
159 CRM_Core_Error
::debug_log_message("New order for an installment received.");
160 $recur = &$objects['contributionRecur'];
162 // fix dates that already exist
163 $dates = array('create', 'start', 'end', 'cancel', 'modified');
164 foreach ($dates as $date) {
165 $name = "{$date}_date";
167 $recur->$name = CRM_Utils_Date
::isoToMysql($recur->$name);
170 $recur->invoice_id
= $dataRoot['serial-number'];
171 $recur->processor_id
= $input['newInvoice'];
174 if ($objects['contribution']->contribution_status_id
== 1) {
175 // create a contribution and then get it processed
176 $contribution = new CRM_Contribute_DAO_Contribution();
177 $contribution->contact_id
= $ids['contact'];
178 $contribution->financial_type_id
= $objects['contributionType']->id
;
179 $contribution->contribution_page_id
= $objects['contribution']->contribution_page_id
;
180 $contribution->contribution_recur_id
= $ids['contributionRecur'];
181 $contribution->receive_date
= date('YmdHis');
182 $contribution->currency
= $objects['contribution']->currency
;
183 $contribution->payment_instrument_id
= $objects['contribution']->payment_instrument_id
;
184 $contribution->amount_level
= $objects['contribution']->amount_level
;
185 $contribution->address_id
= $objects['contribution']->address_id
;
186 $contribution->invoice_id
= $input['invoice'];
187 $contribution->total_amount
= $dataRoot['order-total']['VALUE'];
188 $contribution->contribution_status_id
= 2;
189 $contribution->campaign_id
= $objects['contribution']->campaign_id
;
191 $objects['contribution'] = $contribution;
193 $transaction->commit();
197 // make sure the invoice is valid and matches what we have in the contribution record
198 $contribution = &$objects['contribution'];
200 if ($contribution->invoice_id
!= $input['invoice']) {
201 CRM_Core_Error
::debug_log_message("Invoice values dont match between database and IPN request");
205 // lets replace invoice-id with google-order-number because thats what is common and unique
206 // in subsequent calls or notifications sent by google.
207 $contribution->invoice_id
= $input['newInvoice'];
209 $input['amount'] = $dataRoot['order-total']['VALUE'];
211 if ($contribution->total_amount
!= $input['amount']) {
212 CRM_Core_Error
::debug_log_message("Amount values dont match between database and IPN request");
216 if (!$this->getInput($input, $ids, $dataRoot)) {
220 $transaction = new CRM_Core_Transaction();
222 // check if contribution is already completed, if so we ignore this ipn
223 if ($contribution->contribution_status_id
== 1) {
224 CRM_Core_Error
::debug_log_message("returning since contribution has already been handled");
228 /* Since trxn_id hasn't got any use here,
229 * lets make use of it by passing the eventID/membershipTypeID to next level.
230 * And change trxn_id to google-order-number before finishing db update */
232 if (!empty($ids['event'])) {
233 $contribution->trxn_id
= $ids['event'] . CRM_Core_DAO
::VALUE_SEPARATOR
. $ids['participant'];
235 elseif (!empty($ids['membership'])) {
236 $contribution->trxn_id
= $ids['membership'][0] . CRM_Core_DAO
::VALUE_SEPARATOR
. $ids['related_contact'] . CRM_Core_DAO
::VALUE_SEPARATOR
. $ids['onbehalf_dupe_alert'];
240 $contribution->save();
241 $transaction->commit();
247 * The function gets called when the state(CHARGED, CANCELLED..) changes for an order
249 * @param string $status
250 * Status of the transaction send by google.
252 * @param array $privateData
253 * Contains the name value pair of <merchant-private-data>.
259 public function orderStateChange($status, $dataRoot, $privateData, $component) {
260 $input = $objects = $ids = array();
261 $input['component'] = strtolower($component);
263 $ids['contributionRecur'] = self
::retrieve('contributionRecurID', 'Integer', $privateData, FALSE);
264 $serial = $dataRoot['serial-number'];
265 $orderNo = $dataRoot['google-order-number']['VALUE'];
267 $contribution = new CRM_Contribute_BAO_Contribution();
268 $contribution->invoice_id
= $orderNo;
270 if (!$contribution->find(TRUE)) {
271 CRM_Core_Error
::debug_log_message("orderStateChange: Could not find contribution record with invoice id: $serial");
275 // Google sends the charged notification twice.
276 // So to make sure, code is not executed again.
277 if ($contribution->contribution_status_id
== 1) {
278 CRM_Core_Error
::debug_log_message("Contribution already handled (ContributionID = {$contribution->id}).");
282 // make sure invoice is set to serial no for recurring payments, to avoid violating uniqueness
283 $contribution->invoice_id
= $ids['contributionRecur'] ?
$serial : $orderNo;
285 $objects['contribution'] = &$contribution;
286 $ids['contribution'] = $contribution->id
;
287 $ids['contact'] = $contribution->contact_id
;
289 $ids['event'] = $ids['participant'] = $ids['membership'] = NULL;
290 $ids['contributionPage'] = NULL;
292 if ($input['component'] == "event") {
293 list($ids['event'], $ids['participant']) = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
294 $contribution->trxn_id
298 $ids['related_contact'] = NULL;
299 $ids['onbehalf_dupe_alert'] = NULL;
300 if ($contribution->trxn_id
) {
301 list($ids['membership'], $ids['related_contact'], $ids['onbehalf_dupe_alert']) = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
302 $contribution->trxn_id
306 'membership', 'related_contact', 'onbehalf_dupe_alert') as $fld) {
307 if (!is_numeric($ids[$fld])) {
313 $paymentProcessorID = CRM_Core_DAO
::getFieldValue(
314 'CRM_Financial_DAO_PaymentProcessorType',
317 'payment_processor_type'
320 $this->loadObjects($input, $ids, $objects, TRUE, $paymentProcessorID);
322 $transaction = new CRM_Core_Transaction();
324 if ($status == 'PAYMENT_DECLINED' ||
325 $status == 'CANCELLED_BY_GOOGLE' ||
326 $status == 'CANCELLED'
328 return $this->failed($objects, $transaction);
331 $input['amount'] = $contribution->total_amount
;
332 $input['fee_amount'] = NULL;
333 $input['net_amount'] = NULL;
334 $input['trxn_id'] = $ids['contributionRecur'] ?
$serial : $dataRoot['google-order-number']['VALUE'];
335 $input['is_test'] = $contribution->is_test
;
338 if ($ids['contributionRecur']) {
339 $recur = $objects['contributionRecur'];
341 $this->completeTransaction($input, $ids, $objects, $transaction, $recur);
343 $this->completeRecur($input, $ids, $objects);
351 public function completeRecur($input, $ids, $objects) {
352 if ($ids['contributionRecur']) {
353 $recur = &$objects['contributionRecur'];
354 $contributionCount = CRM_Core_DAO
::singleValueQuery("
356 FROM civicrm_contribution
357 WHERE contribution_recur_id = {$ids['contributionRecur']}
359 $autoRenewMembership = FALSE;
361 isset($ids['membership']) &&
364 $autoRenewMembership = TRUE;
366 if ($recur->installments
&& ($contributionCount >= $recur->installments
)) {
367 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
369 $recur->create_date
= CRM_Utils_Date
::isoToMysql($recur->create_date
);
370 $recur->start_date
= CRM_Utils_Date
::isoToMysql($recur->start_date
);
371 $recur->cancel_date
= CRM_Utils_Date
::isoToMysql($recur->cancel_date
);
372 $recur->end_date
= date('YmdHis');
373 $recur->modified_date
= date('YmdHis');
374 $recur->contribution_status_id
= array_search('Completed', $contributionStatus);
375 $recur->trnx_id
= $dataRoot['google-order-number']['VALUE'];
378 //send recurring Notification email for user
379 CRM_Contribute_BAO_ContributionPage
::recurringNotify(
380 CRM_Core_Payment
::RECURRING_PAYMENT_END
,
382 $ids['contributionPage'],
387 elseif ($contributionCount == 1) {
388 CRM_Contribute_BAO_ContributionPage
::recurringNotify(
389 CRM_Core_Payment
::RECURRING_PAYMENT_START
,
391 $ids['contributionPage'],
401 * Payment processor singletons removed - this is an IPN so left but probably can go
402 * Singleton function used to manage this object
404 * @param string $mode
405 * The mode of operation: live or test.
408 * @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)
456 public function getContext($privateData, $orderNo, $root, $response, $serial) {
457 $contributionID = CRM_Utils_Array
::value('contributionID', $privateData);
458 $contribution = new CRM_Contribute_DAO_Contribution();
459 if ($root == 'new-order-notification') {
460 $contribution->id
= $contributionID;
463 $contribution->invoice_id
= $orderNo;
465 if (!$contribution->find(TRUE)) {
466 CRM_Core_Error
::debug_log_message("getContext: Could not find contribution record with invoice id: $orderNo");
467 $response->SendAck($serial);
470 $module = 'Contribute';
471 if (stristr($contribution->source
, ts('Online Contribution'))) {
472 $module = 'Contribute';
474 elseif (stristr($contribution->source
, ts('Online Event Registration'))) {
477 $isTest = $contribution->is_test
;
479 $ids = $input = $objects = array();
480 $objects['contribution'] = &$contribution;
481 $ids['contributionRecur'] = self
::retrieve('contributionRecurID', 'Integer', $privateData, FALSE);
482 $input['component'] = strtolower($module);
484 if (!$ids['contributionRecur'] && $contribution->contribution_status_id
== 1) {
485 CRM_Core_Error
::debug_log_message("Contribution already handled (ContributionID = {$contribution->id}).");
486 // There is no point in going further. Return ack so we don't receive the same ipn.
487 $response->SendAck($serial);
490 if ($input['component'] == 'event') {
491 if ($root == 'new-order-notification') {
492 $ids['event'] = $privateData['eventID'];
495 list($ids['event'], $ids['participant']) =
496 explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $contribution->trxn_id
);
500 $paymentProcessorID = CRM_Core_DAO
::getFieldValue(
501 'CRM_Financial_DAO_PaymentProcessor',
504 'payment_processor_type'
507 $this->loadObjects($input, $ids, $objects, FALSE, $paymentProcessorID);
509 if (!$ids['paymentProcessor']) {
510 CRM_Core_Error
::debug_log_message("Payment processor could not be retrieved.");
511 // There is no point in going further. Return ack so we don't receive the same ipn.
512 $response->SendAck($serial);
515 return array($isTest, $input['component'], $ids['paymentProcessor']);
519 * This method is handles the response that will be invoked (from extern/googleNotify) every time
520 * a notification or request is sent by the Google Server.
522 public static function main($xml_response) {
523 require_once 'Google/library/googleresponse.php';
524 require_once 'Google/library/googlerequest.php';
525 require_once 'Google/library/googlemerchantcalculations.php';
526 require_once 'Google/library/googleresult.php';
527 require_once 'Google/library/xml-processing/gc_xmlparser.php';
529 $config = CRM_Core_Config
::singleton();
531 // Retrieve the XML sent in the HTTP POST request to the ResponseHandler
532 if (get_magic_quotes_gpc()) {
533 $xml_response = stripslashes($xml_response);
536 $headers = CRM_Utils_System
::getAllHeaders();
538 if (GOOGLE_DEBUG_PP
) {
539 CRM_Core_Error
::debug_var('RESPONSE', $xml_response, TRUE, TRUE, 'Google');
542 // Retrieve the root and data from the xml response
543 $response = new GoogleResponse();
544 list($root, $data) = $response->GetParsedXML($xml_response);
545 // lets retrieve the private-data & order-no
547 if (array_key_exists('shopping-cart', $data[$root])) {
548 $privateData = $data[$root]['shopping-cart']['merchant-private-data']['VALUE'];
550 if (empty($privateData) && array_key_exists('order-summary', $data[$root])
551 && array_key_exists('shopping-cart', $data[$root]['order-summary'])) {
552 $privateData = $data[$root]['order-summary']['shopping-cart']['merchant-private-data']['VALUE'];
554 $privateData = $privateData ? self
::stringToArray($privateData) : '';
555 $orderNo = $data[$root]['google-order-number']['VALUE'];
556 $serial = $data[$root]['serial-number'];
558 // a dummy object to call get context and a parent function inside it.
559 $ipn = new CRM_Core_Payment_GoogleIPN('live', $dummyProcessor);
560 list($mode, $module, $paymentProcessorID) = $ipn->getContext($privateData, $orderNo, $root, $response, $serial);
561 $mode = $mode ?
'test' : 'live';
563 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID, $mode);
564 $merchant_id = $paymentProcessor['user_name'];
565 $merchant_key = $paymentProcessor['password'];
566 $response->SetMerchantAuthentication($merchant_id, $merchant_key);
568 $server_type = ($mode == 'test') ?
'sandbox' : 'production';
569 $request = new GoogleRequest($merchant_id, $merchant_key, $server_type);
571 $ipn = self
::singleton($mode, $module, $paymentProcessor);
573 if (GOOGLE_DEBUG_PP
) {
574 CRM_Core_Error
::debug_var('RESPONSE-ROOT', $response->root
, TRUE, TRUE, 'Google');
577 //Check status and take appropriate action
578 $status = $response->HttpAuthentication($headers);
581 case "request-received":
584 case "checkout-redirect":
585 case "merchant-calculation-callback":
588 case "new-order-notification":{
589 $response->SendAck($serial, FALSE);
590 $ipn->newOrderNotify($data[$root], $privateData, $module);
594 case "order-state-change-notification":{
595 $response->SendAck($serial, FALSE);
596 $new_financial_state = $data[$root]['new-financial-order-state']['VALUE'];
597 $new_fulfillment_order = $data[$root]['new-fulfillment-order-state']['VALUE'];
599 switch ($new_financial_state) {
604 case 'PAYMENT_DECLINED':
606 case 'CANCELLED_BY_GOOGLE':
607 $ipn->orderStateChange($new_financial_state, $data[$root], $privateData, $module);
620 case "authorization-amount-notification":{
621 $response->SendAck($serial, FALSE);
622 $new_financial_state = $data[$root]['order-summary']['financial-order-state']['VALUE'];
623 $new_fulfillment_order = $data[$root]['order-summary']['fulfillment-order-state']['VALUE'];
625 switch ($new_financial_state) {
627 // For google-handled subscriptions chargeorder needn't be initiated,
628 // assuming auto-charging is turned on.
629 //$request->SendProcessOrder($data[$root]['google-order-number']['VALUE']);
630 //$request->SendChargeOrder($data[$root]['google-order-number']['VALUE'],'');
634 case 'PAYMENT_DECLINED':
640 case 'CANCELLED_BY_GOOGLE':
649 case "charge-amount-notification":
650 case "chargeback-amount-notification":
651 case "refund-amount-notification":
652 case "risk-information-notification":
653 $response->SendAck($serial);
668 public function getInput(&$input, &$ids, $dataRoot) {
669 if (!$this->getBillingID($ids)) {
673 $billingID = $ids['billing'];
675 "first_name" => 'contact-name',
676 // "last-name" not available with google (every thing in contact-name)
677 "last_name" => 'last_name',
678 "street_address-{$billingID}" => 'address1',
679 "city-{$billingID}" => 'city',
680 "state-{$billingID}" => 'region',
681 "postal_code-{$billingID}" => 'postal-code',
682 "country-{$billingID}" => 'country-code',
685 foreach ($lookup as $name => $googleName) {
686 if (array_key_exists($googleName, $dataRoot['buyer-billing-address'])) {
687 $value = $dataRoot['buyer-billing-address'][$googleName]['VALUE'];
689 $input[$name] = $value ?
$value : NULL;
695 * Converts the comma separated name-value pairs in <merchant-private-data>
696 * to an array of name-value pairs.
698 public static function stringToArray($str) {
699 $vars = $labels = array();
700 $labels = explode(',', $str);
701 foreach ($labels as $label) {
702 $terms = explode('=', $label);
703 $vars[$terms[0]] = $terms[1];