Merge pull request #5971 from PalanteJon/activityreportfix
[civicrm-core.git] / CRM / Core / Payment / Google.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
6a488035 5 +--------------------------------------------------------------------+
e7112fa7 6 | Copyright CiviCRM LLC (c) 2004-2015 |
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
e7112fa7 31 * @copyright CiviCRM LLC (c) 2004-2015
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
6a488035
TO
58 */
59 static private $_singleton = NULL;
60
61 /**
fe482240 62 * Constructor.
6a488035 63 *
6a0b768e
TO
64 * @param string $mode
65 * The mode of operation: live or test.
6a488035 66 *
77b97be7
EM
67 * @param $paymentProcessor
68 *
69 * @return \CRM_Core_Payment_Google
6a488035 70 */
00be9182 71 public function __construct($mode, &$paymentProcessor) {
6a488035
TO
72 $this->_mode = $mode;
73 $this->_paymentProcessor = $paymentProcessor;
74 $this->_processorName = ts('Google Checkout');
75 }
76
6a488035 77 /**
fe482240 78 * This function checks to see if we have the right config values.
6a488035 79 *
a6c01b45
CW
80 * @return string
81 * 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 110 *
bed98343 111 * @return void
a6c01b45 112 * the result in an nice formatted array (or an error object)
b5c2afd0
EM
113 * @abstract
114 */
00be9182 115 public function doDirectPayment(&$params) {
6a488035
TO
116 CRM_Core_Error::fatal(ts('This function is not implemented'));
117 }
118
119 /**
fe482240 120 * Sets appropriate parameters for checking out to google.
6a488035 121 *
6a0b768e
TO
122 * @param array $params
123 * Name value pair of contribution datat.
6c8f6e67
EM
124 *
125 * @param $component
6a488035
TO
126 *
127 * @return void
6a488035 128 */
00be9182 129 public function doTransferCheckout(&$params, $component) {
6a488035
TO
130 $component = strtolower($component);
131
a7488080 132 if (!empty($params['is_recur']) &&
6a488035
TO
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
6c786a9b 152 /**
c490a46a 153 * @param array $params
6c786a9b
EM
154 * @param $component
155 */
00be9182 156 public function doRecurCheckout(&$params, $component) {
6a488035
TO
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
353ffa53
TO
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);
6a488035
TO
180 $installments = CRM_Utils_Array::value('installments', $params);
181
353ffa53
TO
182 $cart = new GoogleCart($merchant_id, $merchant_key, $server_type, $params['currencyID']);
183 $item = new GoogleItem($itemName, $description, 1, $amount);
6a488035
TO
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 /**
fe482240 193 * Builds appropriate parameters for checking out to google and submits the post params.
6a488035 194 *
6a0b768e
TO
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.
6a488035
TO
201 *
202 * @return void
6a488035 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',
353ffa53
TO
279 array(1 => $request->getResponseCode())
280 ));
6a488035
TO
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
c2b5a0af 288 *
6a488035
TO
289 * @paymentProcessor is the array of payment processor settings value.
290 * @searchParamsnvpStr is the array of search params.
291 * returns an associtive array containing the response from the server.
c2b5a0af
EM
292 *
293 * @param $paymentProcessor
294 * @param $searchParams
295 *
296 * @return array|object
297 * @throws \Exception
6a488035 298 */
00be9182 299 public function invokeAPI($paymentProcessor, $searchParams) {
353ffa53 300 $merchantID = $paymentProcessor['user_name'];
6a488035 301 $merchantKey = $paymentProcessor['password'];
353ffa53 302 $siteURL = rtrim(str_replace('https://', '', $paymentProcessor['url_site']), '/');
6a488035
TO
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'));
17c04b52 317 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'verifySSL') ? 2 : 0);
6a488035
TO
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
6c786a9b 348 /**
100fef9d 349 * @param array $searchParams
6c786a9b
EM
350 *
351 * @return string
352 */
00be9182 353 public static function buildXMLQuery($searchParams) {
6a488035
TO
354 $xml = '<?xml version="1.0" encoding="UTF-8"?>
355<notification-history-request xmlns="http://checkout.google.com/schema/2">';
356
357 if (array_key_exists('next-page-token', $searchParams)) {
358 $xml .= '
359<next-page-token>' . $searchParams['next-page-token'] . '</next-page-token>';
360 }
361 if (array_key_exists('start', $searchParams)) {
362 $xml .= '
363<start-time>' . $searchParams['start'] . '</start-time>
364<end-time>' . $searchParams['end'] . '</end-time>';
365 }
366 if (array_key_exists('notification-types', $searchParams)) {
367 $xml .= '
368<notification-types>
369<notification-type>' . implode($searchParams['notification-types'], '</notification-type>
370<notification-type>') . '</notification-type>
371</notification-types>';
372 }
373 if (array_key_exists('order-numbers', $searchParams)) {
374 $xml .= '
375<order-numbers>
376<google-order-number>' . implode($searchParams['order-numbers'], '</google-order-number>
377<google-order-number>') . '</google-order-number>
378</order-numbers>';
379 }
380 $xml .= '
381</notification-history-request>';
382
383 return $xml;
384 }
385
6c786a9b
EM
386 /**
387 * @param $xmlData
388 *
389 * @return array
390 */
00be9182 391 public static function getArrayFromXML($xmlData) {
6a488035
TO
392 require_once 'Google/library/xml-processing/gc_xmlparser.php';
393 $xmlParser = new gc_XmlParser($xmlData);
353ffa53
TO
394 $root = $xmlParser->GetRoot();
395 $data = $xmlParser->GetData();
6a488035
TO
396
397 return array($root, $data);
398 }
399
6c786a9b
EM
400 /**
401 * @param null $errorCode
402 * @param null $errorMessage
403 *
404 * @return object
405 */
00be9182 406 public function &error($errorCode = NULL, $errorMessage = NULL) {
6a488035
TO
407 $e = &CRM_Core_Error::singleton();
408 if ($errorCode) {
409 $e->push($errorCode, 0, NULL, $errorMessage);
410 }
411 else {
412 $e->push(9001, 0, NULL, 'Unknown System Error.');
413 }
414 return $e;
415 }
416
6c786a9b
EM
417 /**
418 * @return string
419 */
00be9182 420 public function accountLoginURL() {
6a488035
TO
421 return ($this->_mode == 'test') ? 'https://sandbox.google.com/checkout/sell' : 'https://checkout.google.com/';
422 }
423
6c786a9b
EM
424 /**
425 * @param string $message
426 * @param array $params
427 *
428 * @return bool|object
429 */
00be9182 430 public function cancelSubscription(&$message = '', $params = array()) {
6a488035
TO
431 $orderNo = CRM_Utils_Array::value('subscriptionId', $params);
432
353ffa53 433 $merchant_id = $this->_paymentProcessor['user_name'];
6a488035 434 $merchant_key = $this->_paymentProcessor['password'];
353ffa53 435 $server_type = ($this->_mode == 'test') ? 'sandbox' : '';
6a488035
TO
436
437 $googleRequest = new GoogleRequest($merchant_id, $merchant_key, $server_type);
353ffa53
TO
438 $result = $googleRequest->SendCancelItems($orderNo, array(), 'Cancelled by admin', '');
439 $message = "{$result[0]}: {$result[1]}";
6a488035
TO
440
441 if ($result[0] != 200) {
442 return self::error($result[0], $result[1]);
443 }
444 return TRUE;
445 }
96025800 446
6a488035 447}