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';
42 * Class CRM_Core_Payment_Google
44 class CRM_Core_Payment_Google
extends CRM_Core_Payment
{
47 * mode of operation: live or test
51 protected $_mode = NULL;
54 * We only need one instance of this object. So we use the singleton
55 * pattern and cache the instance in this variable
60 static private $_singleton = NULL;
65 * @param string $mode the mode of operation: live or test
67 * @param $paymentProcessor
69 * @return \CRM_Core_Payment_Google
71 function __construct($mode, &$paymentProcessor) {
73 $this->_paymentProcessor
= $paymentProcessor;
74 $this->_processorName
= ts('Google Checkout');
78 * singleton function used to manage this object
80 * @param string $mode the mode of operation: live or test
82 * @param object $paymentProcessor
87 static function &singleton($mode, &$paymentProcessor) {
88 $processorName = $paymentProcessor['name'];
89 if (!isset(self
::$_singleton[$processorName]) || self
::$_singleton[$processorName] === NULL) {
90 self
::$_singleton[$processorName] = new CRM_Core_Payment_Google($mode, $paymentProcessor);
92 return self
::$_singleton[$processorName];
96 * This function checks to see if we have the right config values
98 * @return string the error message if any
101 function checkConfig() {
102 $config = CRM_Core_Config
::singleton();
106 if (empty($this->_paymentProcessor
['user_name'])) {
107 $error[] = ts('User Name is not set in the Administer CiviCRM » System Settings » Payment Processors.');
110 if (empty($this->_paymentProcessor
['password'])) {
111 $error[] = ts('Password is not set in the Administer CiviCRM » System Settings » Payment Processors.');
114 if (!empty($error)) {
115 return implode('<p>', $error);
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
126 * @param array $params assoc array of input parameters for this transaction
128 * @return array the result in an nice formatted array (or an error object)
131 function doDirectPayment(&$params) {
132 CRM_Core_Error
::fatal(ts('This function is not implemented'));
136 * Sets appropriate parameters for checking out to google
138 * @param array $params name value pair of contribution datat
145 function doTransferCheckout(&$params, $component) {
146 $component = strtolower($component);
148 if (!empty($params['is_recur']) &&
149 $params['contributionRecurID']
151 return $this->doRecurCheckout($params, $component);
154 //Create a new shopping cart object
156 $merchant_id = $this->_paymentProcessor
['user_name'];
158 $merchant_key = $this->_paymentProcessor
['password'];
159 $server_type = ($this->_mode
== 'test') ?
'sandbox' : '';
161 $cart = new GoogleCart($merchant_id, $merchant_key, $server_type, $params['currencyID']);
162 $item1 = new GoogleItem($params['item_name'], '', 1, $params['amount']);
163 $cart->AddItem($item1);
165 $this->submitPostParams($params, $component, $cart);
172 function doRecurCheckout(&$params, $component) {
173 $intervalUnit = CRM_Utils_Array
::value('frequency_unit', $params);
174 if ($intervalUnit == 'week') {
175 $intervalUnit = 'WEEKLY';
177 elseif ($intervalUnit == 'year') {
178 $intervalUnit = 'YEARLY';
180 elseif ($intervalUnit == 'day') {
181 $intervalUnit = 'DAILY';
183 elseif ($intervalUnit == 'month') {
184 $intervalUnit = 'MONTHLY';
188 $merchant_id = $this->_paymentProcessor
['user_name'];
190 $merchant_key = $this->_paymentProcessor
['password'];
191 $server_type = ($this->_mode
== 'test') ?
'sandbox' : '';
193 $itemName = CRM_Utils_Array
::value('item_name', $params);
194 $description = CRM_Utils_Array
::value('description', $params);
195 $amount = CRM_Utils_Array
::value('amount', $params);
196 $installments = CRM_Utils_Array
::value('installments', $params);
198 $cart = new GoogleCart($merchant_id, $merchant_key, $server_type, $params['currencyID']);
199 $item = new GoogleItem($itemName, $description, 1, $amount);
200 $subscription_item = new GoogleSubscription("merchant", $intervalUnit, $amount, $installments);
202 $item->SetSubscription($subscription_item);
203 $cart->AddItem($item);
205 $this->submitPostParams($params, $component, $cart);
209 * Builds appropriate parameters for checking out to google and submits the post params
211 * @param array $params name value pair of contribution data
212 * @param string $component event/contribution
213 * @param object $cart object of googel cart
219 function submitPostParams($params, $component, $cart) {
220 $url = rtrim($this->_paymentProcessor
['url_site'], '/') . '/cws/v2/Merchant/' . $this->_paymentProcessor
['user_name'] . '/checkout';
222 if ($component == "event") {
223 $privateData = "contactID={$params['contactID']},contributionID={$params['contributionID']},contributionTypeID={$params['contributionTypeID']},eventID={$params['eventID']},participantID={$params['participantID']},invoiceID={$params['invoiceID']}";
225 elseif ($component == "contribute") {
226 $privateData = "contactID={$params['contactID']},contributionID={$params['contributionID']},contributionTypeID={$params['contributionTypeID']},invoiceID={$params['invoiceID']}";
228 $contributionRecurID = CRM_Utils_Array
::value('contributionRecurID', $params);
229 if ($contributionRecurID) {
230 $privateData .= ",contributionRecurID=$contributionRecurID";
233 $membershipID = CRM_Utils_Array
::value('membershipID', $params);
235 $privateData .= ",membershipID=$membershipID";
238 $relatedContactID = CRM_Utils_Array
::value('related_contact', $params);
239 if ($relatedContactID) {
240 $privateData .= ",relatedContactID=$relatedContactID";
242 $onBehalfDupeAlert = CRM_Utils_Array
::value('onbehalf_dupe_alert', $params);
243 if ($onBehalfDupeAlert) {
244 $privateData .= ",onBehalfDupeAlert=$onBehalfDupeAlert";
249 // Allow further manipulation of the arguments via custom hooks ..
250 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $privateData);
252 $cart->SetMerchantPrivateData($privateData);
254 if ($component == "event") {
255 $returnURL = CRM_Utils_System
::url('civicrm/event/register',
256 "_qf_ThankYou_display=1&qfKey={$params['qfKey']}",
260 elseif ($component == "contribute") {
261 $returnURL = CRM_Utils_System
::url('civicrm/contribute/transact',
262 "_qf_ThankYou_display=1&qfKey={$params['qfKey']}",
266 $cart->SetContinueShoppingUrl($returnURL);
268 $cartVal = base64_encode($cart->GetXML());
269 $signatureVal = base64_encode($cart->CalcHmacSha1($cart->GetXML()));
271 $googleParams = array(
273 'signature' => $signatureVal,
276 require_once 'HTTP/Request.php';
278 'method' => HTTP_REQUEST_METHOD_POST
,
279 'allowRedirects' => FALSE,
281 $request = new HTTP_Request($url, $params);
282 foreach ($googleParams as $key => $value) {
283 $request->addPostData($key, $value);
286 $result = $request->sendRequest();
288 if (PEAR
::isError($result)) {
289 CRM_Core_Error
::fatal($result->getMessage());
292 if ($request->getResponseCode() != 302) {
293 CRM_Core_Error
::fatal(ts('Invalid response code received from Google Checkout: %1',
294 array(1 => $request->getResponseCode())
297 CRM_Utils_System
::redirect($request->getResponseHeader('location'));
298 CRM_Utils_System
::civiExit();
302 * hash_call: Function to perform the API call to PayPal using API signature
303 * @paymentProcessor is the array of payment processor settings value.
304 * @searchParamsnvpStr is the array of search params.
305 * returns an associtive array containing the response from the server.
307 function invokeAPI($paymentProcessor, $searchParams) {
308 $merchantID = $paymentProcessor['user_name'];
309 $merchantKey = $paymentProcessor['password'];
310 $siteURL = rtrim(str_replace('https://', '', $paymentProcessor['url_site']), '/');
312 $url = "https://{$merchantID}:{$merchantKey}@{$siteURL}/api/checkout/v2/reports/Merchant/{$merchantID}";
313 $xml = self
::buildXMLQuery($searchParams);
315 if (!function_exists('curl_init')) {
316 CRM_Core_Error
::fatal("curl functions NOT available.");
320 curl_setopt($ch, CURLOPT_URL
, $url);
321 curl_setopt($ch, CURLOPT_VERBOSE
, 1);
323 //turning off the server and peer verification(TrustManager Concept).
324 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'verifySSL'));
325 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST
, CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'verifySSL') ?
2 : 0);
327 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, 1);
328 curl_setopt($ch, CURLOPT_POST
, 1);
330 //setting the nvpreq as POST FIELD to curl
331 curl_setopt($ch, CURLOPT_POSTFIELDS
, $xml);
333 //getting response from server
334 $xmlResponse = curl_exec($ch);
336 // strip slashes if needed
337 if (get_magic_quotes_gpc()) {
338 $xmlResponse = stripslashes($xmlResponse);
341 if (curl_errno($ch)) {
342 $e = CRM_Core_Error
::singleton();
343 $e->push(curl_errno($ch),
353 return self
::getArrayFromXML($xmlResponse);
357 * @param $searchParams
361 static function buildXMLQuery($searchParams) {
362 $xml = '<?xml version="1.0" encoding="UTF-8"?>
363 <notification-history-request xmlns="http://checkout.google.com/schema/2">';
365 if (array_key_exists('next-page-token', $searchParams)) {
367 <next-page-token>' . $searchParams['next-page-token'] . '</next-page-token>';
369 if (array_key_exists('start', $searchParams)) {
371 <start-time>' . $searchParams['start'] . '</start-time>
372 <end-time>' . $searchParams['end'] . '</end-time>';
374 if (array_key_exists('notification-types', $searchParams)) {
377 <notification-type>' . implode($searchParams['notification-types'], '</notification-type>
378 <notification-type>') . '</notification-type>
379 </notification-types>';
381 if (array_key_exists('order-numbers', $searchParams)) {
384 <google-order-number>' . implode($searchParams['order-numbers'], '</google-order-number>
385 <google-order-number>') . '</google-order-number>
389 </notification-history-request>';
399 static function getArrayFromXML($xmlData) {
400 require_once 'Google/library/xml-processing/gc_xmlparser.php';
401 $xmlParser = new gc_XmlParser($xmlData);
402 $root = $xmlParser->GetRoot();
403 $data = $xmlParser->GetData();
405 return array($root, $data);
409 * @param null $errorCode
410 * @param null $errorMessage
414 function &error($errorCode = NULL, $errorMessage = NULL) {
415 $e = &CRM_Core_Error
::singleton();
417 $e->push($errorCode, 0, NULL, $errorMessage);
420 $e->push(9001, 0, NULL, 'Unknown System Error.');
428 function accountLoginURL() {
429 return ($this->_mode
== 'test') ?
'https://sandbox.google.com/checkout/sell' : 'https://checkout.google.com/';
433 * @param string $message
434 * @param array $params
436 * @return bool|object
438 function cancelSubscription(&$message = '', $params = array(
440 $orderNo = CRM_Utils_Array
::value('subscriptionId', $params);
442 $merchant_id = $this->_paymentProcessor
['user_name'];
443 $merchant_key = $this->_paymentProcessor
['password'];
444 $server_type = ($this->_mode
== 'test') ?
'sandbox' : '';
446 $googleRequest = new GoogleRequest($merchant_id, $merchant_key, $server_type);
447 $result = $googleRequest->SendCancelItems($orderNo, array(), 'Cancelled by admin', '');
448 $message = "{$result[0]}: {$result[1]}";
450 if ($result[0] != 200) {
451 return self
::error($result[0], $result[1]);