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