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