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