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