3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
36 require_once 'Google/library/googlecart.php';
37 require_once 'Google/library/googleitem.php';
38 require_once 'Google/library/googlesubscription.php';
39 require_once 'Google/library/googlerequest.php';
40 class CRM_Core_Payment_Google
extends CRM_Core_Payment
{
43 * mode of operation: live or test
47 protected $_mode = NULL;
50 * We only need one instance of this object. So we use the singleton
51 * pattern and cache the instance in this variable
56 static private $_singleton = NULL;
61 * @param string $mode the mode of operation: live or test
63 * @param $paymentProcessor
65 * @return \CRM_Core_Payment_Google
67 function __construct($mode, &$paymentProcessor) {
69 $this->_paymentProcessor
= $paymentProcessor;
70 $this->_processorName
= ts('Google Checkout');
74 * singleton function used to manage this object
76 * @param string $mode the mode of operation: live or test
78 * @param object $paymentProcessor
83 static function &singleton($mode, &$paymentProcessor) {
84 $processorName = $paymentProcessor['name'];
85 if (!isset(self
::$_singleton[$processorName]) || self
::$_singleton[$processorName] === NULL) {
86 self
::$_singleton[$processorName] = new CRM_Core_Payment_Google($mode, $paymentProcessor);
88 return self
::$_singleton[$processorName];
92 * This function checks to see if we have the right config values
94 * @return string the error message if any
97 function checkConfig() {
98 $config = CRM_Core_Config
::singleton();
102 if (empty($this->_paymentProcessor
['user_name'])) {
103 $error[] = ts('User Name is not set in the Administer CiviCRM » System Settings » Payment Processors.');
106 if (empty($this->_paymentProcessor
['password'])) {
107 $error[] = ts('Password is not set in the Administer CiviCRM » System Settings » Payment Processors.');
110 if (!empty($error)) {
111 return implode('<p>', $error);
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
122 * @param array $params assoc array of input parameters for this transaction
124 * @return array the result in an nice formatted array (or an error object)
127 function doDirectPayment(&$params) {
128 CRM_Core_Error
::fatal(ts('This function is not implemented'));
132 * Sets appropriate parameters for checking out to google
134 * @param array $params name value pair of contribution datat
141 function doTransferCheckout(&$params, $component) {
142 $component = strtolower($component);
144 if (!empty($params['is_recur']) &&
145 $params['contributionRecurID']
147 return $this->doRecurCheckout($params, $component);
150 //Create a new shopping cart object
152 $merchant_id = $this->_paymentProcessor
['user_name'];
154 $merchant_key = $this->_paymentProcessor
['password'];
155 $server_type = ($this->_mode
== 'test') ?
'sandbox' : '';
157 $cart = new GoogleCart($merchant_id, $merchant_key, $server_type, $params['currencyID']);
158 $item1 = new GoogleItem($params['item_name'], '', 1, $params['amount']);
159 $cart->AddItem($item1);
161 $this->submitPostParams($params, $component, $cart);
164 function doRecurCheckout(&$params, $component) {
165 $intervalUnit = CRM_Utils_Array
::value('frequency_unit', $params);
166 if ($intervalUnit == 'week') {
167 $intervalUnit = 'WEEKLY';
169 elseif ($intervalUnit == 'year') {
170 $intervalUnit = 'YEARLY';
172 elseif ($intervalUnit == 'day') {
173 $intervalUnit = 'DAILY';
175 elseif ($intervalUnit == 'month') {
176 $intervalUnit = 'MONTHLY';
180 $merchant_id = $this->_paymentProcessor
['user_name'];
182 $merchant_key = $this->_paymentProcessor
['password'];
183 $server_type = ($this->_mode
== 'test') ?
'sandbox' : '';
185 $itemName = CRM_Utils_Array
::value('item_name', $params);
186 $description = CRM_Utils_Array
::value('description', $params);
187 $amount = CRM_Utils_Array
::value('amount', $params);
188 $installments = CRM_Utils_Array
::value('installments', $params);
190 $cart = new GoogleCart($merchant_id, $merchant_key, $server_type, $params['currencyID']);
191 $item = new GoogleItem($itemName, $description, 1, $amount);
192 $subscription_item = new GoogleSubscription("merchant", $intervalUnit, $amount, $installments);
194 $item->SetSubscription($subscription_item);
195 $cart->AddItem($item);
197 $this->submitPostParams($params, $component, $cart);
201 * Builds appropriate parameters for checking out to google and submits the post params
203 * @param array $params name value pair of contribution data
204 * @param string $component event/contribution
205 * @param object $cart object of googel cart
211 function submitPostParams($params, $component, $cart) {
212 $url = rtrim($this->_paymentProcessor
['url_site'], '/') . '/cws/v2/Merchant/' . $this->_paymentProcessor
['user_name'] . '/checkout';
214 if ($component == "event") {
215 $privateData = "contactID={$params['contactID']},contributionID={$params['contributionID']},contributionTypeID={$params['contributionTypeID']},eventID={$params['eventID']},participantID={$params['participantID']},invoiceID={$params['invoiceID']}";
217 elseif ($component == "contribute") {
218 $privateData = "contactID={$params['contactID']},contributionID={$params['contributionID']},contributionTypeID={$params['contributionTypeID']},invoiceID={$params['invoiceID']}";
220 $contributionRecurID = CRM_Utils_Array
::value('contributionRecurID', $params);
221 if ($contributionRecurID) {
222 $privateData .= ",contributionRecurID=$contributionRecurID";
225 $membershipID = CRM_Utils_Array
::value('membershipID', $params);
227 $privateData .= ",membershipID=$membershipID";
230 $relatedContactID = CRM_Utils_Array
::value('related_contact', $params);
231 if ($relatedContactID) {
232 $privateData .= ",relatedContactID=$relatedContactID";
234 $onBehalfDupeAlert = CRM_Utils_Array
::value('onbehalf_dupe_alert', $params);
235 if ($onBehalfDupeAlert) {
236 $privateData .= ",onBehalfDupeAlert=$onBehalfDupeAlert";
241 // Allow further manipulation of the arguments via custom hooks ..
242 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $privateData);
244 $cart->SetMerchantPrivateData($privateData);
246 if ($component == "event") {
247 $returnURL = CRM_Utils_System
::url('civicrm/event/register',
248 "_qf_ThankYou_display=1&qfKey={$params['qfKey']}",
252 elseif ($component == "contribute") {
253 $returnURL = CRM_Utils_System
::url('civicrm/contribute/transact',
254 "_qf_ThankYou_display=1&qfKey={$params['qfKey']}",
258 $cart->SetContinueShoppingUrl($returnURL);
260 $cartVal = base64_encode($cart->GetXML());
261 $signatureVal = base64_encode($cart->CalcHmacSha1($cart->GetXML()));
263 $googleParams = array(
265 'signature' => $signatureVal,
268 require_once 'HTTP/Request.php';
270 'method' => HTTP_REQUEST_METHOD_POST
,
271 'allowRedirects' => FALSE,
273 $request = new HTTP_Request($url, $params);
274 foreach ($googleParams as $key => $value) {
275 $request->addPostData($key, $value);
278 $result = $request->sendRequest();
280 if (PEAR
::isError($result)) {
281 CRM_Core_Error
::fatal($result->getMessage());
284 if ($request->getResponseCode() != 302) {
285 CRM_Core_Error
::fatal(ts('Invalid response code received from Google Checkout: %1',
286 array(1 => $request->getResponseCode())
289 CRM_Utils_System
::redirect($request->getResponseHeader('location'));
290 CRM_Utils_System
::civiExit();
294 * hash_call: Function to perform the API call to PayPal using API signature
295 * @paymentProcessor is the array of payment processor settings value.
296 * @searchParamsnvpStr is the array of search params.
297 * returns an associtive array containing the response from the server.
299 function invokeAPI($paymentProcessor, $searchParams) {
300 $merchantID = $paymentProcessor['user_name'];
301 $merchantKey = $paymentProcessor['password'];
302 $siteURL = rtrim(str_replace('https://', '', $paymentProcessor['url_site']), '/');
304 $url = "https://{$merchantID}:{$merchantKey}@{$siteURL}/api/checkout/v2/reports/Merchant/{$merchantID}";
305 $xml = self
::buildXMLQuery($searchParams);
307 if (!function_exists('curl_init')) {
308 CRM_Core_Error
::fatal("curl functions NOT available.");
312 curl_setopt($ch, CURLOPT_URL
, $url);
313 curl_setopt($ch, CURLOPT_VERBOSE
, 1);
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'));
317 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST
, CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'verifySSL') ?
2 : 0);
319 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, 1);
320 curl_setopt($ch, CURLOPT_POST
, 1);
322 //setting the nvpreq as POST FIELD to curl
323 curl_setopt($ch, CURLOPT_POSTFIELDS
, $xml);
325 //getting response from server
326 $xmlResponse = curl_exec($ch);
328 // strip slashes if needed
329 if (get_magic_quotes_gpc()) {
330 $xmlResponse = stripslashes($xmlResponse);
333 if (curl_errno($ch)) {
334 $e = CRM_Core_Error
::singleton();
335 $e->push(curl_errno($ch),
345 return self
::getArrayFromXML($xmlResponse);
348 static function buildXMLQuery($searchParams) {
349 $xml = '<?xml version="1.0" encoding="UTF-8"?>
350 <notification-history-request xmlns="http://checkout.google.com/schema/2">';
352 if (array_key_exists('next-page-token', $searchParams)) {
354 <next-page-token>' . $searchParams['next-page-token'] . '</next-page-token>';
356 if (array_key_exists('start', $searchParams)) {
358 <start-time>' . $searchParams['start'] . '</start-time>
359 <end-time>' . $searchParams['end'] . '</end-time>';
361 if (array_key_exists('notification-types', $searchParams)) {
364 <notification-type>' . implode($searchParams['notification-types'], '</notification-type>
365 <notification-type>') . '</notification-type>
366 </notification-types>';
368 if (array_key_exists('order-numbers', $searchParams)) {
371 <google-order-number>' . implode($searchParams['order-numbers'], '</google-order-number>
372 <google-order-number>') . '</google-order-number>
376 </notification-history-request>';
381 static function getArrayFromXML($xmlData) {
382 require_once 'Google/library/xml-processing/gc_xmlparser.php';
383 $xmlParser = new gc_XmlParser($xmlData);
384 $root = $xmlParser->GetRoot();
385 $data = $xmlParser->GetData();
387 return array($root, $data);
390 function &error($errorCode = NULL, $errorMessage = NULL) {
391 $e = &CRM_Core_Error
::singleton();
393 $e->push($errorCode, 0, NULL, $errorMessage);
396 $e->push(9001, 0, NULL, 'Unknown System Error.');
401 function accountLoginURL() {
402 return ($this->_mode
== 'test') ?
'https://sandbox.google.com/checkout/sell' : 'https://checkout.google.com/';
405 function cancelSubscription(&$message = '', $params = array(
407 $orderNo = CRM_Utils_Array
::value('subscriptionId', $params);
409 $merchant_id = $this->_paymentProcessor
['user_name'];
410 $merchant_key = $this->_paymentProcessor
['password'];
411 $server_type = ($this->_mode
== 'test') ?
'sandbox' : '';
413 $googleRequest = new GoogleRequest($merchant_id, $merchant_key, $server_type);
414 $result = $googleRequest->SendCancelItems($orderNo, array(), 'Cancelled by admin', '');
415 $message = "{$result[0]}: {$result[1]}";
417 if ($result[0] != 200) {
418 return self
::error($result[0], $result[1]);