ca2d49e708cfbcdad02e3500f40ad4acbfb7a8b6
[civicrm-core.git] / CRM / Core / Payment / Google.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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
31 * @copyright CiviCRM LLC (c) 2004-2014
32 * $Id$
33 *
34 */
35
36 require_once 'Google/library/googlecart.php';
37 require_once 'Google/library/googleitem.php';
38 require_once 'Google/library/googlesubscription.php';
39 require_once 'Google/library/googlerequest.php';
40
41 /**
42 * Class CRM_Core_Payment_Google
43 */
44 class CRM_Core_Payment_Google extends CRM_Core_Payment {
45
46 /**
47 * mode of operation: live or test
48 *
49 * @var object
50 */
51 protected $_mode = NULL;
52
53 /**
54 * We only need one instance of this object. So we use the singleton
55 * pattern and cache the instance in this variable
56 *
57 * @var object
58 * @static
59 */
60 static private $_singleton = NULL;
61
62 /**
63 * Constructor
64 *
65 * @param string $mode the mode of operation: live or test
66 *
67 * @param $paymentProcessor
68 *
69 * @return \CRM_Core_Payment_Google
70 */
71 function __construct($mode, &$paymentProcessor) {
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 *
82 * @param object $paymentProcessor
83 *
84 * @return object
85 * @static
86 */
87 static function &singleton($mode, &$paymentProcessor) {
88 $processorName = $paymentProcessor['name'];
89 if (!isset(self::$_singleton[$processorName]) || self::$_singleton[$processorName] === NULL) {
90 self::$_singleton[$processorName] = new CRM_Core_Payment_Google($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
99 * @public
100 */
101 function checkConfig() {
102 $config = CRM_Core_Config::singleton();
103
104 $error = array();
105
106 if (empty($this->_paymentProcessor['user_name'])) {
107 $error[] = ts('User Name is not set in the Administer CiviCRM &raquo; System Settings &raquo; Payment Processors.');
108 }
109
110 if (empty($this->_paymentProcessor['password'])) {
111 $error[] = ts('Password is not set in the Administer CiviCRM &raquo; System Settings &raquo; Payment Processors.');
112 }
113
114 if (!empty($error)) {
115 return implode('<p>', $error);
116 }
117 else {
118 return NULL;
119 }
120 }
121
122 /**
123 * This function collects all the information from a web/api form and invokes
124 * the relevant payment processor specific functions to perform the transaction
125 *
126 * @param array $params assoc array of input parameters for this transaction
127 *
128 * @return array the result in an nice formatted array (or an error object)
129 * @abstract
130 */
131 function doDirectPayment(&$params) {
132 CRM_Core_Error::fatal(ts('This function is not implemented'));
133 }
134
135 /**
136 * Sets appropriate parameters for checking out to google
137 *
138 * @param array $params name value pair of contribution datat
139 *
140 * @param $component
141 *
142 * @return void
143 * @access public
144 */
145 function doTransferCheckout(&$params, $component) {
146 $component = strtolower($component);
147
148 if (!empty($params['is_recur']) &&
149 $params['contributionRecurID']
150 ) {
151 return $this->doRecurCheckout($params, $component);
152 }
153
154 //Create a new shopping cart object
155 // Merchant ID
156 $merchant_id = $this->_paymentProcessor['user_name'];
157 // Merchant Key
158 $merchant_key = $this->_paymentProcessor['password'];
159 $server_type = ($this->_mode == 'test') ? 'sandbox' : '';
160
161 $cart = new GoogleCart($merchant_id, $merchant_key, $server_type, $params['currencyID']);
162 $item1 = new GoogleItem($params['item_name'], '', 1, $params['amount']);
163 $cart->AddItem($item1);
164
165 $this->submitPostParams($params, $component, $cart);
166 }
167
168 function doRecurCheckout(&$params, $component) {
169 $intervalUnit = CRM_Utils_Array::value('frequency_unit', $params);
170 if ($intervalUnit == 'week') {
171 $intervalUnit = 'WEEKLY';
172 }
173 elseif ($intervalUnit == 'year') {
174 $intervalUnit = 'YEARLY';
175 }
176 elseif ($intervalUnit == 'day') {
177 $intervalUnit = 'DAILY';
178 }
179 elseif ($intervalUnit == 'month') {
180 $intervalUnit = 'MONTHLY';
181 }
182
183 // Merchant ID
184 $merchant_id = $this->_paymentProcessor['user_name'];
185 // Merchant Key
186 $merchant_key = $this->_paymentProcessor['password'];
187 $server_type = ($this->_mode == 'test') ? 'sandbox' : '';
188
189 $itemName = CRM_Utils_Array::value('item_name', $params);
190 $description = CRM_Utils_Array::value('description', $params);
191 $amount = CRM_Utils_Array::value('amount', $params);
192 $installments = CRM_Utils_Array::value('installments', $params);
193
194 $cart = new GoogleCart($merchant_id, $merchant_key, $server_type, $params['currencyID']);
195 $item = new GoogleItem($itemName, $description, 1, $amount);
196 $subscription_item = new GoogleSubscription("merchant", $intervalUnit, $amount, $installments);
197
198 $item->SetSubscription($subscription_item);
199 $cart->AddItem($item);
200
201 $this->submitPostParams($params, $component, $cart);
202 }
203
204 /**
205 * Builds appropriate parameters for checking out to google and submits the post params
206 *
207 * @param array $params name value pair of contribution data
208 * @param string $component event/contribution
209 * @param object $cart object of googel cart
210 *
211 * @return void
212 * @access public
213 *
214 */
215 function submitPostParams($params, $component, $cart) {
216 $url = rtrim($this->_paymentProcessor['url_site'], '/') . '/cws/v2/Merchant/' . $this->_paymentProcessor['user_name'] . '/checkout';
217
218 if ($component == "event") {
219 $privateData = "contactID={$params['contactID']},contributionID={$params['contributionID']},contributionTypeID={$params['contributionTypeID']},eventID={$params['eventID']},participantID={$params['participantID']},invoiceID={$params['invoiceID']}";
220 }
221 elseif ($component == "contribute") {
222 $privateData = "contactID={$params['contactID']},contributionID={$params['contributionID']},contributionTypeID={$params['contributionTypeID']},invoiceID={$params['invoiceID']}";
223
224 $contributionRecurID = CRM_Utils_Array::value('contributionRecurID', $params);
225 if ($contributionRecurID) {
226 $privateData .= ",contributionRecurID=$contributionRecurID";
227 }
228
229 $membershipID = CRM_Utils_Array::value('membershipID', $params);
230 if ($membershipID) {
231 $privateData .= ",membershipID=$membershipID";
232 }
233
234 $relatedContactID = CRM_Utils_Array::value('related_contact', $params);
235 if ($relatedContactID) {
236 $privateData .= ",relatedContactID=$relatedContactID";
237
238 $onBehalfDupeAlert = CRM_Utils_Array::value('onbehalf_dupe_alert', $params);
239 if ($onBehalfDupeAlert) {
240 $privateData .= ",onBehalfDupeAlert=$onBehalfDupeAlert";
241 }
242 }
243 }
244
245 // Allow further manipulation of the arguments via custom hooks ..
246 CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $privateData);
247
248 $cart->SetMerchantPrivateData($privateData);
249
250 if ($component == "event") {
251 $returnURL = CRM_Utils_System::url('civicrm/event/register',
252 "_qf_ThankYou_display=1&qfKey={$params['qfKey']}",
253 TRUE, NULL, FALSE
254 );
255 }
256 elseif ($component == "contribute") {
257 $returnURL = CRM_Utils_System::url('civicrm/contribute/transact',
258 "_qf_ThankYou_display=1&qfKey={$params['qfKey']}",
259 TRUE, NULL, FALSE
260 );
261 }
262 $cart->SetContinueShoppingUrl($returnURL);
263
264 $cartVal = base64_encode($cart->GetXML());
265 $signatureVal = base64_encode($cart->CalcHmacSha1($cart->GetXML()));
266
267 $googleParams = array(
268 'cart' => $cartVal,
269 'signature' => $signatureVal,
270 );
271
272 require_once 'HTTP/Request.php';
273 $params = array(
274 'method' => HTTP_REQUEST_METHOD_POST,
275 'allowRedirects' => FALSE,
276 );
277 $request = new HTTP_Request($url, $params);
278 foreach ($googleParams as $key => $value) {
279 $request->addPostData($key, $value);
280 }
281
282 $result = $request->sendRequest();
283
284 if (PEAR::isError($result)) {
285 CRM_Core_Error::fatal($result->getMessage());
286 }
287
288 if ($request->getResponseCode() != 302) {
289 CRM_Core_Error::fatal(ts('Invalid response code received from Google Checkout: %1',
290 array(1 => $request->getResponseCode())
291 ));
292 }
293 CRM_Utils_System::redirect($request->getResponseHeader('location'));
294 CRM_Utils_System::civiExit();
295 }
296
297 /**
298 * hash_call: Function to perform the API call to PayPal using API signature
299 * @paymentProcessor is the array of payment processor settings value.
300 * @searchParamsnvpStr is the array of search params.
301 * returns an associtive array containing the response from the server.
302 */
303 function invokeAPI($paymentProcessor, $searchParams) {
304 $merchantID = $paymentProcessor['user_name'];
305 $merchantKey = $paymentProcessor['password'];
306 $siteURL = rtrim(str_replace('https://', '', $paymentProcessor['url_site']), '/');
307
308 $url = "https://{$merchantID}:{$merchantKey}@{$siteURL}/api/checkout/v2/reports/Merchant/{$merchantID}";
309 $xml = self::buildXMLQuery($searchParams);
310
311 if (!function_exists('curl_init')) {
312 CRM_Core_Error::fatal("curl functions NOT available.");
313 }
314
315 $ch = curl_init();
316 curl_setopt($ch, CURLOPT_URL, $url);
317 curl_setopt($ch, CURLOPT_VERBOSE, 1);
318
319 //turning off the server and peer verification(TrustManager Concept).
320 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'verifySSL'));
321 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'verifySSL') ? 2 : 0);
322
323 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
324 curl_setopt($ch, CURLOPT_POST, 1);
325
326 //setting the nvpreq as POST FIELD to curl
327 curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
328
329 //getting response from server
330 $xmlResponse = curl_exec($ch);
331
332 // strip slashes if needed
333 if (get_magic_quotes_gpc()) {
334 $xmlResponse = stripslashes($xmlResponse);
335 }
336
337 if (curl_errno($ch)) {
338 $e = CRM_Core_Error::singleton();
339 $e->push(curl_errno($ch),
340 0, NULL,
341 curl_error($ch)
342 );
343 return $e;
344 }
345 else {
346 curl_close($ch);
347 }
348
349 return self::getArrayFromXML($xmlResponse);
350 }
351
352 static function buildXMLQuery($searchParams) {
353 $xml = '<?xml version="1.0" encoding="UTF-8"?>
354 <notification-history-request xmlns="http://checkout.google.com/schema/2">';
355
356 if (array_key_exists('next-page-token', $searchParams)) {
357 $xml .= '
358 <next-page-token>' . $searchParams['next-page-token'] . '</next-page-token>';
359 }
360 if (array_key_exists('start', $searchParams)) {
361 $xml .= '
362 <start-time>' . $searchParams['start'] . '</start-time>
363 <end-time>' . $searchParams['end'] . '</end-time>';
364 }
365 if (array_key_exists('notification-types', $searchParams)) {
366 $xml .= '
367 <notification-types>
368 <notification-type>' . implode($searchParams['notification-types'], '</notification-type>
369 <notification-type>') . '</notification-type>
370 </notification-types>';
371 }
372 if (array_key_exists('order-numbers', $searchParams)) {
373 $xml .= '
374 <order-numbers>
375 <google-order-number>' . implode($searchParams['order-numbers'], '</google-order-number>
376 <google-order-number>') . '</google-order-number>
377 </order-numbers>';
378 }
379 $xml .= '
380 </notification-history-request>';
381
382 return $xml;
383 }
384
385 static function getArrayFromXML($xmlData) {
386 require_once 'Google/library/xml-processing/gc_xmlparser.php';
387 $xmlParser = new gc_XmlParser($xmlData);
388 $root = $xmlParser->GetRoot();
389 $data = $xmlParser->GetData();
390
391 return array($root, $data);
392 }
393
394 function &error($errorCode = NULL, $errorMessage = NULL) {
395 $e = &CRM_Core_Error::singleton();
396 if ($errorCode) {
397 $e->push($errorCode, 0, NULL, $errorMessage);
398 }
399 else {
400 $e->push(9001, 0, NULL, 'Unknown System Error.');
401 }
402 return $e;
403 }
404
405 function accountLoginURL() {
406 return ($this->_mode == 'test') ? 'https://sandbox.google.com/checkout/sell' : 'https://checkout.google.com/';
407 }
408
409 function cancelSubscription(&$message = '', $params = array(
410 )) {
411 $orderNo = CRM_Utils_Array::value('subscriptionId', $params);
412
413 $merchant_id = $this->_paymentProcessor['user_name'];
414 $merchant_key = $this->_paymentProcessor['password'];
415 $server_type = ($this->_mode == 'test') ? 'sandbox' : '';
416
417 $googleRequest = new GoogleRequest($merchant_id, $merchant_key, $server_type);
418 $result = $googleRequest->SendCancelItems($orderNo, array(), 'Cancelled by admin', '');
419 $message = "{$result[0]}: {$result[1]}";
420
421 if ($result[0] != 200) {
422 return self::error($result[0], $result[1]);
423 }
424 return TRUE;
425 }
426 }
427