7c5ed1f6a493bc329c8fa486ec283294a4decc00
[civicrm-core.git] / tools / extensions / org.civicrm.payment.googlecheckout / GoogleCheckout.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
32 * $Id$
33 *
34 */
35
36 require_once 'CRM/Core/Payment.php';
37 require_once ('packages/Google/library/googlecart.php');
38 require_once ('packages/Google/library/googleitem.php');
39
40 /**
41 * Class org_civicrm_payment_googlecheckout
42 */
43 class org_civicrm_payment_googlecheckout extends CRM_Core_Payment {
44
45 /**
46 * We only need one instance of this object. So we use the singleton
47 * pattern and cache the instance in this variable
48 *
49 * @var object
50 */
51 static private $_singleton = NULL;
52
53 /**
54 * mode of operation: live or test
55 *
56 * @var object
57 */
58 static protected $_mode = NULL;
59
60 /**
61 * Constructor
62 *
63 * @param string $mode the mode of operation: live or test
64 *
65 * @param $paymentProcessor
66 *
67 * @return \org_civicrm_payment_googlecheckout
68 */
69 function __construct($mode, &$paymentProcessor) {
70 $this->_mode = $mode;
71 $this->_paymentProcessor = $paymentProcessor;
72 $this->_processorName = ts('Google Checkout');
73 }
74
75 /**
76 * singleton function used to manage this object
77 *
78 * @param string $mode the mode of operation: live or test
79 *
80 * @param object $paymentProcessor
81 * @return object
82 */
83 static
84 function &singleton($mode, &$paymentProcessor) {
85 $processorName = $paymentProcessor['name'];
86 if (self::$_singleton[$processorName] === NULL) {
87 self::$_singleton[$processorName] = new org_civicrm_payment_googlecheckout($mode, $paymentProcessor);
88 }
89 return self::$_singleton[$processorName];
90 }
91
92 /**
93 * This function checks to see if we have the right config values
94 *
95 * @return string the error message if any
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; Payment Processor.');
104 }
105
106 if (empty($this->_paymentProcessor['password'])) {
107 $error[] = ts('Password is not set in the Administer CiviCRM &raquo; Payment Processor.');
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 * @throws Exception
138 * @return void
139 */
140 function doTransferCheckout(&$params, $component) {
141 $component = strtolower($component);
142
143 $url = rtrim($this->_paymentProcessor['url_site'], '/') . '/cws/v2/Merchant/' . $this->_paymentProcessor['user_name'] . '/checkout';
144
145 //Create a new shopping cart object
146 // Merchant ID
147 $merchant_id = $this->_paymentProcessor['user_name'];
148 // Merchant Key
149 $merchant_key = $this->_paymentProcessor['password'];
150 $server_type = ($this->_mode == 'test') ? 'sandbox' : '';
151
152 $cart = new GoogleCart($merchant_id, $merchant_key, $server_type);
153 $item1 = new GoogleItem($params['item_name'], '', 1, $params['amount'], $params['currencyID']);
154 $cart->AddItem($item1);
155
156 if ($component == "event") {
157 $privateData = "contactID={$params['contactID']},contributionID={$params['contributionID']},contributionTypeID={$params['contributionTypeID']},eventID={$params['eventID']},participantID={$params['participantID']},invoiceID={$params['invoiceID']}";
158 }
159 elseif ($component == "contribute") {
160 $privateData = "contactID={$params['contactID']},contributionID={$params['contributionID']},contributionTypeID={$params['contributionTypeID']},invoiceID={$params['invoiceID']}";
161
162 $membershipID = CRM_Utils_Array::value('membershipID', $params);
163 if ($membershipID) {
164 $privateData .= ",membershipID=$membershipID";
165 }
166
167 $relatedContactID = CRM_Utils_Array::value('related_contact', $params);
168 if ($relatedContactID) {
169 $privateData .= ",relatedContactID=$relatedContactID";
170
171 $onBehalfDupeAlert = CRM_Utils_Array::value('onbehalf_dupe_alert', $params);
172 if ($onBehalfDupeAlert) {
173 $privateData .= ",onBehalfDupeAlert=$onBehalfDupeAlert";
174 }
175 }
176 }
177
178 // Allow further manipulation of the arguments via custom hooks ..
179 CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $privateData);
180
181 $cart->SetMerchantPrivateData($privateData);
182
183 if ($component == "event") {
184 $returnURL = CRM_Utils_System::url('civicrm/event/register',
185 "_qf_ThankYou_display=1&qfKey={$params['qfKey']}",
186 TRUE, NULL, FALSE
187 );
188 }
189 elseif ($component == "contribute") {
190 $returnURL = CRM_Utils_System::url('civicrm/contribute/transact',
191 "_qf_ThankYou_display=1&qfKey={$params['qfKey']}",
192 TRUE, NULL, FALSE
193 );
194 }
195
196 $cart->SetContinueShoppingUrl($returnURL);
197
198 $cartVal = base64_encode($cart->GetXML());
199 $signatureVal = base64_encode($cart->CalcHmacSha1($cart->GetXML()));
200
201 $googleParams = array('cart' => $cartVal,
202 'signature' => $signatureVal,
203 );
204
205 require_once 'HTTP/Request.php';
206 $params = array('method' => HTTP_REQUEST_METHOD_POST,
207 'allowRedirects' => FALSE,
208 );
209 $request = new HTTP_Request($url, $params);
210 foreach ($googleParams as $key => $value) {
211 $request->addPostData($key, $value);
212 }
213
214 $result = $request->sendRequest();
215
216 if (PEAR::isError($result)) {
217 CRM_Core_Error::fatal($result->getMessage());
218 }
219
220 if ($request->getResponseCode() != 302) {
221 CRM_Core_Error::fatal(ts('Invalid response code received from Google Checkout: %1',
222 array(1 => $request->getResponseCode())
223 ));
224 }
225 CRM_Utils_System::redirect($request->getResponseHeader('location'));
226
227 exit();
228 }
229
230 /**
231 * hash_call: Function to perform the API call to PayPal using API signature
232 * @paymentProcessor is the array of payment processor settings value.
233 * @searchParamsnvpStr is the array of search params.
234 * returns an associtive array containing the response from the server.
235 * @param $paymentProcessor
236 * @param $searchParams
237 * @return array|object
238 * @throws \Exception
239 */
240 function invokeAPI($paymentProcessor, $searchParams) {
241 $merchantID = $paymentProcessor['user_name'];
242 $merchantKey = $paymentProcessor['password'];
243 $siteURL = rtrim(str_replace('https://', '', $paymentProcessor['url_site']), '/');
244
245 $url = "https://{$merchantID}:{$merchantKey}@{$siteURL}/api/checkout/v2/reports/Merchant/{$merchantID}";
246 $xml = self::buildXMLQuery($searchParams);
247
248 if (!function_exists('curl_init')) {
249 CRM_Core_Error::fatal("curl functions NOT available.");
250 }
251
252 $ch = curl_init();
253 curl_setopt($ch, CURLOPT_URL, $url);
254 curl_setopt($ch, CURLOPT_VERBOSE, 1);
255
256 //turning off the server and peer verification(TrustManager Concept).
257 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
258 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
259
260 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
261 curl_setopt($ch, CURLOPT_POST, 1);
262
263 //setting the nvpreq as POST FIELD to curl
264 curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
265
266 //getting response from server
267 $xmlResponse = curl_exec($ch);
268
269 // strip slashes if needed
270 if (get_magic_quotes_gpc()) {
271 $xmlResponse = stripslashes($xmlResponse);
272 }
273
274 if (curl_errno($ch)) {
275 $e = &CRM_Core_Error::singleton();
276 $e->push(curl_errno($ch),
277 0, NULL,
278 curl_error($ch)
279 );
280 return $e;
281 }
282 else {
283 curl_close($ch);
284 }
285
286 return self::getArrayFromXML($xmlResponse);
287 }
288
289 /**
290 * @param $searchParams
291 *
292 * @return string
293 */
294 static
295 function buildXMLQuery($searchParams) {
296 $xml = '<?xml version="1.0" encoding="UTF-8"?>
297 <notification-history-request xmlns="http://checkout.google.com/schema/2">';
298
299 if (array_key_exists('next-page-token', $searchParams)) {
300 $xml .= '
301 <next-page-token>' . $searchParams['next-page-token'] . '</next-page-token>';
302 }
303 if (array_key_exists('start', $searchParams)) {
304 $xml .= '
305 <start-time>' . $searchParams['start'] . '</start-time>
306 <end-time>' . $searchParams['end'] . '</end-time>';
307 }
308 if (array_key_exists('notification-types', $searchParams)) {
309 $xml .= '
310 <notification-types>
311 <notification-type>' . implode($searchParams['notification-types'], '</notification-type>
312 <notification-type>') . '</notification-type>
313 </notification-types>';
314 }
315 if (array_key_exists('order-numbers', $searchParams)) {
316 $xml .= '
317 <order-numbers>
318 <google-order-number>' . implode($searchParams['order-numbers'], '</google-order-number>
319 <google-order-number>') . '</google-order-number>
320 </order-numbers>';
321 }
322 $xml .= '
323 </notification-history-request>';
324
325 return $xml;
326 }
327
328 /**
329 * @param $xmlData
330 *
331 * @return array
332 */
333 static
334 function getArrayFromXML($xmlData) {
335 require_once 'Google/library/xml-processing/xmlparser.php';
336 $xmlParser = new XmlParser($xmlData);
337 $root = $xmlParser->GetRoot();
338 $data = $xmlParser->GetData();
339
340 return array($root, $data);
341 }
342 }
343