Merge pull request #4865 from eileenmcnaughton/my-first-factory
[civicrm-core.git] / CRM / Core / Payment / Google.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
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 /**
100fef9d 47 * Mode of operation: live or test
6a488035
TO
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 *
6a0b768e
TO
65 * @param string $mode
66 * The mode of operation: live or test.
6a488035 67 *
77b97be7
EM
68 * @param $paymentProcessor
69 *
70 * @return \CRM_Core_Payment_Google
6a488035 71 */
00be9182 72 public function __construct($mode, &$paymentProcessor) {
6a488035
TO
73 $this->_mode = $mode;
74 $this->_paymentProcessor = $paymentProcessor;
75 $this->_processorName = ts('Google Checkout');
76 }
77
6a488035
TO
78 /**
79 * This function checks to see if we have the right config values
80 *
81 * @return string the error message if any
6a488035 82 */
00be9182 83 public function checkConfig() {
6a488035
TO
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
b5c2afd0
EM
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 *
6a0b768e
TO
108 * @param array $params
109 * Assoc array of input parameters for this transaction.
b5c2afd0
EM
110 *
111 * @return array the result in an nice formatted array (or an error object)
112 * @abstract
113 */
00be9182 114 public function doDirectPayment(&$params) {
6a488035
TO
115 CRM_Core_Error::fatal(ts('This function is not implemented'));
116 }
117
118 /**
119 * Sets appropriate parameters for checking out to google
120 *
6a0b768e
TO
121 * @param array $params
122 * Name value pair of contribution datat.
6c8f6e67
EM
123 *
124 * @param $component
6a488035
TO
125 *
126 * @return void
6a488035 127 */
00be9182 128 public function doTransferCheckout(&$params, $component) {
6a488035
TO
129 $component = strtolower($component);
130
a7488080 131 if (!empty($params['is_recur']) &&
6a488035
TO
132 $params['contributionRecurID']
133 ) {
134 return $this->doRecurCheckout($params, $component);
135 }
136
137 //Create a new shopping cart object
138 // Merchant ID
139 $merchant_id = $this->_paymentProcessor['user_name'];
140 // Merchant Key
141 $merchant_key = $this->_paymentProcessor['password'];
142 $server_type = ($this->_mode == 'test') ? 'sandbox' : '';
143
144 $cart = new GoogleCart($merchant_id, $merchant_key, $server_type, $params['currencyID']);
145 $item1 = new GoogleItem($params['item_name'], '', 1, $params['amount']);
146 $cart->AddItem($item1);
147
148 $this->submitPostParams($params, $component, $cart);
149 }
150
6c786a9b 151 /**
c490a46a 152 * @param array $params
6c786a9b
EM
153 * @param $component
154 */
00be9182 155 public function doRecurCheckout(&$params, $component) {
6a488035
TO
156 $intervalUnit = CRM_Utils_Array::value('frequency_unit', $params);
157 if ($intervalUnit == 'week') {
158 $intervalUnit = 'WEEKLY';
159 }
160 elseif ($intervalUnit == 'year') {
161 $intervalUnit = 'YEARLY';
162 }
163 elseif ($intervalUnit == 'day') {
164 $intervalUnit = 'DAILY';
165 }
166 elseif ($intervalUnit == 'month') {
167 $intervalUnit = 'MONTHLY';
168 }
169
170 // Merchant ID
171 $merchant_id = $this->_paymentProcessor['user_name'];
172 // Merchant Key
173 $merchant_key = $this->_paymentProcessor['password'];
174 $server_type = ($this->_mode == 'test') ? 'sandbox' : '';
175
176 $itemName = CRM_Utils_Array::value('item_name', $params);
177 $description = CRM_Utils_Array::value('description', $params);
178 $amount = CRM_Utils_Array::value('amount', $params);
179 $installments = CRM_Utils_Array::value('installments', $params);
180
181 $cart = new GoogleCart($merchant_id, $merchant_key, $server_type, $params['currencyID']);
182 $item = new GoogleItem($itemName, $description, 1, $amount);
183 $subscription_item = new GoogleSubscription("merchant", $intervalUnit, $amount, $installments);
184
185 $item->SetSubscription($subscription_item);
186 $cart->AddItem($item);
187
188 $this->submitPostParams($params, $component, $cart);
189 }
190
191 /**
192 * Builds appropriate parameters for checking out to google and submits the post params
193 *
6a0b768e
TO
194 * @param array $params
195 * Name value pair of contribution data.
196 * @param string $component
197 * Event/contribution.
198 * @param object $cart
199 * Object of googel cart.
6a488035
TO
200 *
201 * @return void
6a488035
TO
202 *
203 */
00be9182 204 public function submitPostParams($params, $component, $cart) {
6a488035
TO
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 /**
100fef9d 287 * Hash_call: Function to perform the API call to PayPal using API signature
6a488035
TO
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 */
00be9182 292 public function invokeAPI($paymentProcessor, $searchParams) {
6a488035
TO
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'));
17c04b52 310 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'verifySSL') ? 2 : 0);
6a488035
TO
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
6c786a9b 341 /**
100fef9d 342 * @param array $searchParams
6c786a9b
EM
343 *
344 * @return string
345 */
00be9182 346 public static function buildXMLQuery($searchParams) {
6a488035
TO
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
6c786a9b
EM
379 /**
380 * @param $xmlData
381 *
382 * @return array
383 */
00be9182 384 public static function getArrayFromXML($xmlData) {
6a488035
TO
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
6c786a9b
EM
393 /**
394 * @param null $errorCode
395 * @param null $errorMessage
396 *
397 * @return object
398 */
00be9182 399 public function &error($errorCode = NULL, $errorMessage = NULL) {
6a488035
TO
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
6c786a9b
EM
410 /**
411 * @return string
412 */
00be9182 413 public function accountLoginURL() {
6a488035
TO
414 return ($this->_mode == 'test') ? 'https://sandbox.google.com/checkout/sell' : 'https://checkout.google.com/';
415 }
416
6c786a9b
EM
417 /**
418 * @param string $message
419 * @param array $params
420 *
421 * @return bool|object
422 */
00be9182 423 public function cancelSubscription(&$message = '', $params = array()) {
6a488035
TO
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}