CRM/Core/Payment add missing code blocks (autogenerated)
[civicrm-core.git] / CRM / Core / Payment / Google.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
06b69b18 4 | CiviCRM version 4.5 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 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
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
32 * $Id$
33 *
34 */
35
36require_once 'Google/library/googlecart.php';
37require_once 'Google/library/googleitem.php';
38require_once 'Google/library/googlesubscription.php';
39require_once 'Google/library/googlerequest.php';
28518c90
EM
40
41/**
42 * Class CRM_Core_Payment_Google
43 */
6a488035
TO
44class 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 *
77b97be7
EM
67 * @param $paymentProcessor
68 *
69 * @return \CRM_Core_Payment_Google
6a488035
TO
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 *
77b97be7
EM
82 * @param object $paymentProcessor
83 *
6a488035
TO
84 * @return object
85 * @static
6a488035
TO
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
b5c2afd0
EM
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 */
6a488035
TO
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 *
6c8f6e67
EM
138 * @param array $params name value pair of contribution datat
139 *
140 * @param $component
6a488035
TO
141 *
142 * @return void
143 * @access public
6a488035
TO
144 */
145 function doTransferCheckout(&$params, $component) {
146 $component = strtolower($component);
147
a7488080 148 if (!empty($params['is_recur']) &&
6a488035
TO
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
6c786a9b
EM
168 /**
169 * @param $params
170 * @param $component
171 */
6a488035
TO
172 function doRecurCheckout(&$params, $component) {
173 $intervalUnit = CRM_Utils_Array::value('frequency_unit', $params);
174 if ($intervalUnit == 'week') {
175 $intervalUnit = 'WEEKLY';
176 }
177 elseif ($intervalUnit == 'year') {
178 $intervalUnit = 'YEARLY';
179 }
180 elseif ($intervalUnit == 'day') {
181 $intervalUnit = 'DAILY';
182 }
183 elseif ($intervalUnit == 'month') {
184 $intervalUnit = 'MONTHLY';
185 }
186
187 // Merchant ID
188 $merchant_id = $this->_paymentProcessor['user_name'];
189 // Merchant Key
190 $merchant_key = $this->_paymentProcessor['password'];
191 $server_type = ($this->_mode == 'test') ? 'sandbox' : '';
192
193 $itemName = CRM_Utils_Array::value('item_name', $params);
194 $description = CRM_Utils_Array::value('description', $params);
195 $amount = CRM_Utils_Array::value('amount', $params);
196 $installments = CRM_Utils_Array::value('installments', $params);
197
198 $cart = new GoogleCart($merchant_id, $merchant_key, $server_type, $params['currencyID']);
199 $item = new GoogleItem($itemName, $description, 1, $amount);
200 $subscription_item = new GoogleSubscription("merchant", $intervalUnit, $amount, $installments);
201
202 $item->SetSubscription($subscription_item);
203 $cart->AddItem($item);
204
205 $this->submitPostParams($params, $component, $cart);
206 }
207
208 /**
209 * Builds appropriate parameters for checking out to google and submits the post params
210 *
211 * @param array $params name value pair of contribution data
212 * @param string $component event/contribution
213 * @param object $cart object of googel cart
214 *
215 * @return void
216 * @access public
217 *
218 */
219 function submitPostParams($params, $component, $cart) {
220 $url = rtrim($this->_paymentProcessor['url_site'], '/') . '/cws/v2/Merchant/' . $this->_paymentProcessor['user_name'] . '/checkout';
221
222 if ($component == "event") {
223 $privateData = "contactID={$params['contactID']},contributionID={$params['contributionID']},contributionTypeID={$params['contributionTypeID']},eventID={$params['eventID']},participantID={$params['participantID']},invoiceID={$params['invoiceID']}";
224 }
225 elseif ($component == "contribute") {
226 $privateData = "contactID={$params['contactID']},contributionID={$params['contributionID']},contributionTypeID={$params['contributionTypeID']},invoiceID={$params['invoiceID']}";
227
228 $contributionRecurID = CRM_Utils_Array::value('contributionRecurID', $params);
229 if ($contributionRecurID) {
230 $privateData .= ",contributionRecurID=$contributionRecurID";
231 }
232
233 $membershipID = CRM_Utils_Array::value('membershipID', $params);
234 if ($membershipID) {
235 $privateData .= ",membershipID=$membershipID";
236 }
237
238 $relatedContactID = CRM_Utils_Array::value('related_contact', $params);
239 if ($relatedContactID) {
240 $privateData .= ",relatedContactID=$relatedContactID";
241
242 $onBehalfDupeAlert = CRM_Utils_Array::value('onbehalf_dupe_alert', $params);
243 if ($onBehalfDupeAlert) {
244 $privateData .= ",onBehalfDupeAlert=$onBehalfDupeAlert";
245 }
246 }
247 }
248
249 // Allow further manipulation of the arguments via custom hooks ..
250 CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $privateData);
251
252 $cart->SetMerchantPrivateData($privateData);
253
254 if ($component == "event") {
255 $returnURL = CRM_Utils_System::url('civicrm/event/register',
256 "_qf_ThankYou_display=1&qfKey={$params['qfKey']}",
257 TRUE, NULL, FALSE
258 );
259 }
260 elseif ($component == "contribute") {
261 $returnURL = CRM_Utils_System::url('civicrm/contribute/transact',
262 "_qf_ThankYou_display=1&qfKey={$params['qfKey']}",
263 TRUE, NULL, FALSE
264 );
265 }
266 $cart->SetContinueShoppingUrl($returnURL);
267
268 $cartVal = base64_encode($cart->GetXML());
269 $signatureVal = base64_encode($cart->CalcHmacSha1($cart->GetXML()));
270
271 $googleParams = array(
272 'cart' => $cartVal,
273 'signature' => $signatureVal,
274 );
275
276 require_once 'HTTP/Request.php';
277 $params = array(
278 'method' => HTTP_REQUEST_METHOD_POST,
279 'allowRedirects' => FALSE,
280 );
281 $request = new HTTP_Request($url, $params);
282 foreach ($googleParams as $key => $value) {
283 $request->addPostData($key, $value);
284 }
285
286 $result = $request->sendRequest();
287
288 if (PEAR::isError($result)) {
289 CRM_Core_Error::fatal($result->getMessage());
290 }
291
292 if ($request->getResponseCode() != 302) {
293 CRM_Core_Error::fatal(ts('Invalid response code received from Google Checkout: %1',
294 array(1 => $request->getResponseCode())
295 ));
296 }
297 CRM_Utils_System::redirect($request->getResponseHeader('location'));
298 CRM_Utils_System::civiExit();
299 }
300
301 /**
302 * hash_call: Function to perform the API call to PayPal using API signature
303 * @paymentProcessor is the array of payment processor settings value.
304 * @searchParamsnvpStr is the array of search params.
305 * returns an associtive array containing the response from the server.
306 */
307 function invokeAPI($paymentProcessor, $searchParams) {
308 $merchantID = $paymentProcessor['user_name'];
309 $merchantKey = $paymentProcessor['password'];
310 $siteURL = rtrim(str_replace('https://', '', $paymentProcessor['url_site']), '/');
311
312 $url = "https://{$merchantID}:{$merchantKey}@{$siteURL}/api/checkout/v2/reports/Merchant/{$merchantID}";
313 $xml = self::buildXMLQuery($searchParams);
314
315 if (!function_exists('curl_init')) {
316 CRM_Core_Error::fatal("curl functions NOT available.");
317 }
318
319 $ch = curl_init();
320 curl_setopt($ch, CURLOPT_URL, $url);
321 curl_setopt($ch, CURLOPT_VERBOSE, 1);
322
323 //turning off the server and peer verification(TrustManager Concept).
324 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'verifySSL'));
17c04b52 325 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'verifySSL') ? 2 : 0);
6a488035
TO
326
327 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
328 curl_setopt($ch, CURLOPT_POST, 1);
329
330 //setting the nvpreq as POST FIELD to curl
331 curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
332
333 //getting response from server
334 $xmlResponse = curl_exec($ch);
335
336 // strip slashes if needed
337 if (get_magic_quotes_gpc()) {
338 $xmlResponse = stripslashes($xmlResponse);
339 }
340
341 if (curl_errno($ch)) {
342 $e = CRM_Core_Error::singleton();
343 $e->push(curl_errno($ch),
344 0, NULL,
345 curl_error($ch)
346 );
347 return $e;
348 }
349 else {
350 curl_close($ch);
351 }
352
353 return self::getArrayFromXML($xmlResponse);
354 }
355
6c786a9b
EM
356 /**
357 * @param $searchParams
358 *
359 * @return string
360 */
6a488035
TO
361 static function buildXMLQuery($searchParams) {
362 $xml = '<?xml version="1.0" encoding="UTF-8"?>
363<notification-history-request xmlns="http://checkout.google.com/schema/2">';
364
365 if (array_key_exists('next-page-token', $searchParams)) {
366 $xml .= '
367<next-page-token>' . $searchParams['next-page-token'] . '</next-page-token>';
368 }
369 if (array_key_exists('start', $searchParams)) {
370 $xml .= '
371<start-time>' . $searchParams['start'] . '</start-time>
372<end-time>' . $searchParams['end'] . '</end-time>';
373 }
374 if (array_key_exists('notification-types', $searchParams)) {
375 $xml .= '
376<notification-types>
377<notification-type>' . implode($searchParams['notification-types'], '</notification-type>
378<notification-type>') . '</notification-type>
379</notification-types>';
380 }
381 if (array_key_exists('order-numbers', $searchParams)) {
382 $xml .= '
383<order-numbers>
384<google-order-number>' . implode($searchParams['order-numbers'], '</google-order-number>
385<google-order-number>') . '</google-order-number>
386</order-numbers>';
387 }
388 $xml .= '
389</notification-history-request>';
390
391 return $xml;
392 }
393
6c786a9b
EM
394 /**
395 * @param $xmlData
396 *
397 * @return array
398 */
6a488035
TO
399 static function getArrayFromXML($xmlData) {
400 require_once 'Google/library/xml-processing/gc_xmlparser.php';
401 $xmlParser = new gc_XmlParser($xmlData);
402 $root = $xmlParser->GetRoot();
403 $data = $xmlParser->GetData();
404
405 return array($root, $data);
406 }
407
6c786a9b
EM
408 /**
409 * @param null $errorCode
410 * @param null $errorMessage
411 *
412 * @return object
413 */
6a488035
TO
414 function &error($errorCode = NULL, $errorMessage = NULL) {
415 $e = &CRM_Core_Error::singleton();
416 if ($errorCode) {
417 $e->push($errorCode, 0, NULL, $errorMessage);
418 }
419 else {
420 $e->push(9001, 0, NULL, 'Unknown System Error.');
421 }
422 return $e;
423 }
424
6c786a9b
EM
425 /**
426 * @return string
427 */
6a488035
TO
428 function accountLoginURL() {
429 return ($this->_mode == 'test') ? 'https://sandbox.google.com/checkout/sell' : 'https://checkout.google.com/';
430 }
431
6c786a9b
EM
432 /**
433 * @param string $message
434 * @param array $params
435 *
436 * @return bool|object
437 */
6a488035
TO
438 function cancelSubscription(&$message = '', $params = array(
439 )) {
440 $orderNo = CRM_Utils_Array::value('subscriptionId', $params);
441
442 $merchant_id = $this->_paymentProcessor['user_name'];
443 $merchant_key = $this->_paymentProcessor['password'];
444 $server_type = ($this->_mode == 'test') ? 'sandbox' : '';
445
446 $googleRequest = new GoogleRequest($merchant_id, $merchant_key, $server_type);
447 $result = $googleRequest->SendCancelItems($orderNo, array(), 'Cancelled by admin', '');
448 $message = "{$result[0]}: {$result[1]}";
449
450 if ($result[0] != 200) {
451 return self::error($result[0], $result[1]);
452 }
453 return TRUE;
454 }
455}
456