Merge pull request #4607 from samuelsov/CRM-15637
[civicrm-core.git] / tools / extensions / org.civicrm.payment.googlecheckout / GoogleCheckout.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
6a488035 5 +--------------------------------------------------------------------+
34cd78e1 6 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26*/
27
28/**
29 *
30 * @package CRM
34cd78e1 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
32 * $Id$
33 *
34 */
35
36require_once 'CRM/Core/Payment.php';
37require_once ('packages/Google/library/googlecart.php');
38require_once ('packages/Google/library/googleitem.php');
a1a55b61
EM
39
40/**
41 * Class org_civicrm_payment_googlecheckout
42 */
6a488035
TO
43class org_civicrm_payment_googlecheckout extends CRM_Core_Payment {
44
45 /**
46 * We only need one instance of this object. So we use the singleton
47 * pattern and cache the instance in this variable
48 *
49 * @var object
50 * @static
51 */
52 static private $_singleton = NULL;
53
54 /**
55 * mode of operation: live or test
56 *
57 * @var object
58 * @static
59 */
60 static protected $_mode = NULL;
61
62 /**
63 * Constructor
64 *
65 * @param string $mode the mode of operation: live or test
66 *
2a6da8d7
EM
67 * @param $paymentProcessor
68 *
69 * @return \org_civicrm_payment_googlecheckout
70 */
71 function __construct($mode, &$paymentProcessor) {
6a488035
TO
72 $this->_mode = $mode;
73 $this->_paymentProcessor = $paymentProcessor;
74 $this->_processorName = ts('Google Checkout');
75 }
76
77 /**
78 * singleton function used to manage this object
79 *
80 * @param string $mode the mode of operation: live or test
81 *
2a6da8d7 82 * @param object $paymentProcessor
6a488035
TO
83 * @return object
84 * @static
6a488035
TO
85 */
86 static
87 function &singleton($mode, &$paymentProcessor) {
88 $processorName = $paymentProcessor['name'];
89 if (self::$_singleton[$processorName] === NULL) {
90 self::$_singleton[$processorName] = new org_civicrm_payment_googlecheckout($mode, $paymentProcessor);
91 }
92 return self::$_singleton[$processorName];
93 }
94
95 /**
96 * This function checks to see if we have the right config values
97 *
98 * @return string the error message if any
6a488035
TO
99 */
100 function checkConfig() {
101 $config = CRM_Core_Config::singleton();
102
103 $error = array();
104
105 if (empty($this->_paymentProcessor['user_name'])) {
106 $error[] = ts('User Name is not set in the Administer CiviCRM &raquo; Payment Processor.');
107 }
108
109 if (empty($this->_paymentProcessor['password'])) {
110 $error[] = ts('Password is not set in the Administer CiviCRM &raquo; Payment Processor.');
111 }
112
113 if (!empty($error)) {
114 return implode('<p>', $error);
115 }
116 else {
117 return NULL;
118 }
119 }
120
a1a55b61
EM
121 /**
122 * This function collects all the information from a web/api form and invokes
123 * the relevant payment processor specific functions to perform the transaction
124 *
125 * @param array $params assoc array of input parameters for this transaction
126 *
127 * @return array the result in an nice formatted array (or an error object)
128 * @abstract
129 */
6a488035
TO
130 function doDirectPayment(&$params) {
131 CRM_Core_Error::fatal(ts('This function is not implemented'));
132 }
133
134 /**
135 * Sets appropriate parameters for checking out to google
136 *
2a6da8d7 137 * @param array $params name value pair of contribution datat
6a488035 138 *
2a6da8d7
EM
139 * @param $component
140 * @throws Exception
6a488035
TO
141 * @return void
142 * @access public
6a488035
TO
143 */
144 function doTransferCheckout(&$params, $component) {
145 $component = strtolower($component);
146
147 $url = rtrim($this->_paymentProcessor['url_site'], '/') . '/cws/v2/Merchant/' . $this->_paymentProcessor['user_name'] . '/checkout';
148
149 //Create a new shopping cart object
150 // Merchant ID
151 $merchant_id = $this->_paymentProcessor['user_name'];
152 // Merchant Key
153 $merchant_key = $this->_paymentProcessor['password'];
154 $server_type = ($this->_mode == 'test') ? 'sandbox' : '';
155
156 $cart = new GoogleCart($merchant_id, $merchant_key, $server_type);
157 $item1 = new GoogleItem($params['item_name'], '', 1, $params['amount'], $params['currencyID']);
158 $cart->AddItem($item1);
159
160 if ($component == "event") {
161 $privateData = "contactID={$params['contactID']},contributionID={$params['contributionID']},contributionTypeID={$params['contributionTypeID']},eventID={$params['eventID']},participantID={$params['participantID']},invoiceID={$params['invoiceID']}";
162 }
163 elseif ($component == "contribute") {
164 $privateData = "contactID={$params['contactID']},contributionID={$params['contributionID']},contributionTypeID={$params['contributionTypeID']},invoiceID={$params['invoiceID']}";
165
166 $membershipID = CRM_Utils_Array::value('membershipID', $params);
167 if ($membershipID) {
168 $privateData .= ",membershipID=$membershipID";
169 }
170
171 $relatedContactID = CRM_Utils_Array::value('related_contact', $params);
172 if ($relatedContactID) {
173 $privateData .= ",relatedContactID=$relatedContactID";
174
175 $onBehalfDupeAlert = CRM_Utils_Array::value('onbehalf_dupe_alert', $params);
176 if ($onBehalfDupeAlert) {
177 $privateData .= ",onBehalfDupeAlert=$onBehalfDupeAlert";
178 }
179 }
180 }
181
182 // Allow further manipulation of the arguments via custom hooks ..
183 CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $privateData);
184
185 $cart->SetMerchantPrivateData($privateData);
186
187 if ($component == "event") {
188 $returnURL = CRM_Utils_System::url('civicrm/event/register',
189 "_qf_ThankYou_display=1&qfKey={$params['qfKey']}",
190 TRUE, NULL, FALSE
191 );
192 }
193 elseif ($component == "contribute") {
194 $returnURL = CRM_Utils_System::url('civicrm/contribute/transact',
195 "_qf_ThankYou_display=1&qfKey={$params['qfKey']}",
196 TRUE, NULL, FALSE
197 );
198 }
199
200 $cart->SetContinueShoppingUrl($returnURL);
201
202 $cartVal = base64_encode($cart->GetXML());
203 $signatureVal = base64_encode($cart->CalcHmacSha1($cart->GetXML()));
204
205 $googleParams = array('cart' => $cartVal,
206 'signature' => $signatureVal,
207 );
208
209 require_once 'HTTP/Request.php';
210 $params = array('method' => HTTP_REQUEST_METHOD_POST,
211 'allowRedirects' => FALSE,
212 );
213 $request = new HTTP_Request($url, $params);
214 foreach ($googleParams as $key => $value) {
215 $request->addPostData($key, $value);
216 }
217
218 $result = $request->sendRequest();
219
220 if (PEAR::isError($result)) {
221 CRM_Core_Error::fatal($result->getMessage());
222 }
223
224 if ($request->getResponseCode() != 302) {
225 CRM_Core_Error::fatal(ts('Invalid response code received from Google Checkout: %1',
226 array(1 => $request->getResponseCode())
227 ));
228 }
229 CRM_Utils_System::redirect($request->getResponseHeader('location'));
230
231 exit();
232 }
233
234 /**
235 * hash_call: Function to perform the API call to PayPal using API signature
236 * @paymentProcessor is the array of payment processor settings value.
237 * @searchParamsnvpStr is the array of search params.
238 * returns an associtive array containing the response from the server.
239 */
240 function invokeAPI($paymentProcessor, $searchParams) {
241 $merchantID = $paymentProcessor['user_name'];
242 $merchantKey = $paymentProcessor['password'];
243 $siteURL = rtrim(str_replace('https://', '', $paymentProcessor['url_site']), '/');
244
245 $url = "https://{$merchantID}:{$merchantKey}@{$siteURL}/api/checkout/v2/reports/Merchant/{$merchantID}";
246 $xml = self::buildXMLQuery($searchParams);
247
248 if (!function_exists('curl_init')) {
249 CRM_Core_Error::fatal("curl functions NOT available.");
250 }
251
252 $ch = curl_init();
253 curl_setopt($ch, CURLOPT_URL, $url);
254 curl_setopt($ch, CURLOPT_VERBOSE, 1);
255
256 //turning off the server and peer verification(TrustManager Concept).
257 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
258 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
259
260 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
261 curl_setopt($ch, CURLOPT_POST, 1);
262
263 //setting the nvpreq as POST FIELD to curl
264 curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
265
266 //getting response from server
267 $xmlResponse = curl_exec($ch);
268
269 // strip slashes if needed
270 if (get_magic_quotes_gpc()) {
271 $xmlResponse = stripslashes($xmlResponse);
272 }
273
274 if (curl_errno($ch)) {
275 $e = &CRM_Core_Error::singleton();
276 $e->push(curl_errno($ch),
277 0, NULL,
278 curl_error($ch)
279 );
280 return $e;
281 }
282 else {
283 curl_close($ch);
284 }
285
286 return self::getArrayFromXML($xmlResponse);
287 }
288
a1a55b61
EM
289 /**
290 * @param $searchParams
291 *
292 * @return string
293 */
6a488035
TO
294 static
295 function buildXMLQuery($searchParams) {
296 $xml = '<?xml version="1.0" encoding="UTF-8"?>
297<notification-history-request xmlns="http://checkout.google.com/schema/2">';
298
299 if (array_key_exists('next-page-token', $searchParams)) {
300 $xml .= '
301<next-page-token>' . $searchParams['next-page-token'] . '</next-page-token>';
302 }
303 if (array_key_exists('start', $searchParams)) {
304 $xml .= '
305<start-time>' . $searchParams['start'] . '</start-time>
306<end-time>' . $searchParams['end'] . '</end-time>';
307 }
308 if (array_key_exists('notification-types', $searchParams)) {
309 $xml .= '
310<notification-types>
311<notification-type>' . implode($searchParams['notification-types'], '</notification-type>
312<notification-type>') . '</notification-type>
313</notification-types>';
314 }
315 if (array_key_exists('order-numbers', $searchParams)) {
316 $xml .= '
317<order-numbers>
318<google-order-number>' . implode($searchParams['order-numbers'], '</google-order-number>
319<google-order-number>') . '</google-order-number>
320</order-numbers>';
321 }
322 $xml .= '
323</notification-history-request>';
324
325 return $xml;
326 }
327
a1a55b61
EM
328 /**
329 * @param $xmlData
330 *
331 * @return array
332 */
6a488035
TO
333 static
334 function getArrayFromXML($xmlData) {
335 require_once 'Google/library/xml-processing/xmlparser.php';
336 $xmlParser = new XmlParser($xmlData);
337 $root = $xmlParser->GetRoot();
338 $data = $xmlParser->GetData();
339
340 return array($root, $data);
341 }
342}
343