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