Paypal, обработчик для платежной системы
Предлагается для тестирования обработчик ПС "Paypal".
1. В код типовой дин. страницы корзины внести следующий код:
2. Создать платежную систему Paypal со следующим обработчиком (обратите внимание на выделенные фрагменты):
1. В код типовой дин. страницы корзины внести следующий код:
######################################################
### Обработка принятия заказа от платежной системы ###
######################################################
// ------------------------------------------------
// Подготовка редиректа для PayPal
// ------------------------------------------------
if (isset($_POST['paymentType']))
{
// Получаем ID заказа
$order_id = to_int($_POST['order_id']);
$order_row = $shop->GetOrder($order_id);
if ($order_row)
{
// Вызов обработчика платежной системы
$shop->ExecSystemsOfPayHandler($order_row['shop_system_of_pay_id']);
}
}
### Обработка принятия заказа от платежной системы ###
######################################################
// ------------------------------------------------
// Подготовка редиректа для PayPal
// ------------------------------------------------
if (isset($_POST['paymentType']))
{
// Получаем ID заказа
$order_id = to_int($_POST['order_id']);
$order_row = $shop->GetOrder($order_id);
if ($order_row)
{
// Вызов обработчика платежной системы
$shop->ExecSystemsOfPayHandler($order_row['shop_system_of_pay_id']);
}
}
2. Создать платежную систему Paypal со следующим обработчиком (обратите внимание на выделенные фрагменты):
<?php
/****************************************************
PayPal includes the following API Signature for making API
calls to the PayPal sandbox:
API Username sdk-three_api1.sdk.com
API Password QFZCWN5HZM8VBG7Q
API Signature A-IzJhZZjhg29XQ2qnhapuwxIDzyAZQ92FRP5dqBzVesOkzbdUONzmOU
****************************************************/
/*
# true - тестовый режим,
# false - рабочий режим,
*/
$SandboxFlag = true;
/**
# API user: The user that is identified as making the call. you can
# also use your own API username that you created on PayPal’s sandbox
# or the PayPal live site
*/
define('API_USERNAME', 'sdk-three_api1.sdk.com');
/**
# API_password: The password associated with the API user
# If you are using your own API username, enter the API password that
# was generated by PayPal below
# IMPORTANT - HAVING YOUR API PASSWORD INCLUDED IN THE MANNER IS NOT
# SECURE, AND ITS ONLY BEING SHOWN THIS WAY FOR TESTING PURPOSES
*/
define('API_PASSWORD', 'QFZCWN5HZM8VBG7Q');
/**
# API_Signature:The Signature associated with the API user. which is generated by paypal.
*/
define('API_SIGNATURE', 'A.d9eRKfd1yVkRrtmMfCFLTqa6M9AyodL0SJkhYztxUi8W9pCXF6.4NI');
// BN Code is only applicable for partners
define('sBNCode','PP-ECWizard');
/**
# Endpoint: this is the server URL which you have to connect for submitting your API request.
*/
/* Define the PayPal URL. This is the URL that the buyer is
first sent to to authorize payment with their paypal account
change the URL depending if you are testing on the sandbox
or going to the live PayPal site
For the sandbox, the URL is
For the live site, the URL is
*/
if ($SandboxFlag == true)
{
define('API_ENDPOINT', "https://api-3t.sandbox.paypal.com/nvp");
define('PAYPAL_URL', "https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token=");
}
else
{
define('API_ENDPOINT', "https://api-3t.paypal.com/nvp");
define('PAYPAL_URL', "https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=");
}
/*
# Third party Email address that you granted permission to make api call.
*/
define('SUBJECT','sdk-three@sdk.com');
/**
USE_PROXY: Set this variable to TRUE to route all the API requests through proxy.
like define('USE_PROXY',TRUE);
*/
define('USE_PROXY',FALSE);
/**
PROXY_HOST: Set the host name or the IP address of proxy server.
PROXY_PORT: Set proxy port.
PROXY_HOST and PROXY_PORT will be read only if USE_PROXY is set to TRUE
*/
define('PROXY_HOST', '127.0.0.1');
define('PROXY_PORT', '808');
/**
# Version: this is the API version in the request.
# It is a mandatory parameter for each API request.
# The only supported value at this time is 2.3
*/
define('VERSION', '60.0');
// Ack related constants
define('ACK_SUCCESS', 'SUCCESS');
define('ACK_SUCCESS_WITH_WARNING', 'SUCCESSWITHWARNING');
/* Оплата через PayPal */
class system_of_pay_handler
{
/* Определяем валюты для USD */
var $default_currency_id = 3;
/**
* Обработка статуса оплаты
*
*/
function ProcessResult()
{
/* Информация о заказе */
$order_id = to_int($_POST['order_id']);
if (!$order_id)
{
return false;
}
$shop = & singleton('shop');
$order_row = $shop->GetOrder($order_id);
if (!$order_row)
{
return false;
}
$shop_row = $shop->GetShop($order_row['shop_shops_id']);
ini_set('session.bug_compat_42',0);
ini_set('session.bug_compat_warn',0);
/* Gather the information to make the final call to
finalize the PayPal payment. The variable nvpstr
holds the name value pairs
*/
$_SESSION['token'] = $_REQUEST['token'];
$_SESSION['payer_id'] = $_REQUEST['PayerID'];
$_SESSION['paymentAmount']=$_REQUEST['paymentAmount'];
$_SESSION['currCodeType']=$_REQUEST['currencyCodeType'];
$_SESSION['paymentType']=$_REQUEST['paymentType'];
$resArray = $_SESSION['reshash'];
$_SESSION['TotalAmount']= $resArray['AMT'] + $resArray['SHIPDISCAMT'];
$token =urlencode($_SESSION['token']);
$paymentAmount =urlencode ($_SESSION['TotalAmount']);
$paymentType = urlencode($_SESSION['paymentType']);
$currCodeType = urlencode($_SESSION['currCodeType']);
$payerID = urlencode($_SESSION['payer_id']);
$serverName = urlencode($_SERVER['SERVER_NAME']);
$nvpstr='&TOKEN='.$token.'&PAYERID='.$payerID.'&PAYMENTACTION='.$paymentType.'&AMT='.$paymentAmount.'&CURRENCYCODE='.$currCodeType.'&IPADDRESS='.$serverName ;
/* Make the call to PayPal to finalize payment
If an error occured, show the resulting errors
*/
$resArray = hash_call("DoExpressCheckoutPayment", $nvpstr);
/* Display the API response back to the browser.
If the response from PayPal was a success, display the response parameters'
If the response was an error, display the errors received using APIError.php.
*/
$ack = strtoupper($resArray["ACK"]);
/* Устанавливаем параметры */
$param['id'] = $order_row['shop_order_id'];
$param['shop_shops_id'] = $order_row['shop_shops_id'];
$param['location_id'] = $order_row['shop_location_id'];
$param['country_id'] = $order_row['shop_country_id'];
$param['shop_city_id'] = $order_row['shop_city_id'];
$param['city_area_id'] = $order_row['shop_city_area_id'];
$param['shop_cond_of_delivery_id'] = $order_row['shop_cond_of_delivery_id'];
$param['delivery_price'] = $order_row['shop_order_delivery_price'];
$param['site_user_id'] = $order_row['site_users_id'];
$param['shop_order_status_id'] = $order_row['shop_order_status_id'];
$param['currency_id'] = $order_row['shop_currency_id'];
$param['shop_system_of_pay_id'] = $order_row['shop_system_of_pay_id'];
$param['order_date_time'] = $order_row['shop_order_date_time'];
$param['status_of_pay'] = $order_row['shop_order_status_of_pay'];
$param['date_of_pay'] = $order_row['shop_order_date_of_pay'];
$param['address'] = $order_row['shop_order_address'];
$param['index'] = $order_row['shop_order_index'];
$param['phone'] = $order_row['shop_order_phone'];
$param['description'] = $order_row['shop_order_description'];
if($ack == 'SUCCESS' || $ack == 'SUCCESSWITHWARNING')
{
/* Проверка прошла успешно!
Добавляем комментарий */
$param['system_information'] = "Товар оплачен через PayPal.\n".
"Атрибуты:\n".
"Transaction ID: {$resArray['TRANSACTIONID']}\n".
"Amount: {$resArray['AMT']} {$currCodeType}";
/* Устанавливаем признак оплаты */
//$param['date_of_pay'] = date("Y-m-d H:i:s");
//$param['status_of_pay'] = true;
// Обновляем информацию о заказе
$shop->InsertOrder($param);
// Изменяем статус оплаты ПОСЛЕ ОБНОВЛЕНИЯ ИНФОРМАЦИ, генерируем ссылки для эл.товаров, списываем товары
$shop->SetOrderPaymentStatus($order_id);
}
else
{
$param['system_information'] = 'PayPal не подтвердил платеж, ответ: {$ack}!';
// Обновляем информацию о заказе
$shop->InsertOrder($param);
}
// Отправку письма об оплате делаем только после вставки информации об оплате
if($ack == 'SUCCESS' || $ack == 'SUCCESSWITHWARNING')
{
$structure = & singleton('Structure');
$structure_row = $structure->GetStructureItem(to_int($shop_row['structure_id']));
$lib = new lib();
$LA = $lib->LoadLibPropertiesValue(to_int($structure_row['lib_id']), to_int($structure_row['structure_id']));
$order_row = $shop->GetOrder($order_id);
// Отправляем письмо администратору о подтверждении платежа
$shop->SendMailAboutOrder($order_row['shop_shops_id'], $order_id, $order_row['site_users_id'],
to_str($LA['xsl_letter_to_admin']),
to_str($LA['xsl_letter_to_user']),
$order_row['shop_order_users_email'],
array(
'admin-content-type' => 'html',
'user-content-type' => 'html',
'admin-subject' => sprintf($GLOBALS['MSG_shops']['shop_order_confirm_admin_subject'], $order_id, $shop_row['shop_shops_name'], $order_row['shop_order_date_of_pay']),
'user-subject' => sprintf($GLOBALS['MSG_shops']['shop_order_confirm_user_subject'], $order_id, $shop_row['shop_shops_name'], $order_row['shop_order_date_of_pay']),
'email_from_admin' => $order_row['shop_order_users_email']));
}
}
function GetHandlerUrl($shop_shops_id)
{
$shop = & singleton('shop');
$shop_row = $shop->GetShop($shop_shops_id);
if ($shop_row)
{
/* Информация об алиасе сайта */
$site = & singleton ('site');
$site_alias = $site->GetCurrentAlias($shop_row['site_id']);
/* Получаем путь к магазину */
$Structure = & singleton('Structure');
$shop_path = "/".$Structure->GetStructurePath($shop_row['structure_id'], 0);
$handler_url = 'http://'.$site_alias.$shop_path.'cart/';
}
else
{
$handler_url = '';
}
return $handler_url;
}
/**
* Отображает стартовую страницу для оплаты через Web Money.
*
*/
function ShowPurseRequest()
{
$shop_id = to_int($GLOBALS['shop_id']);
/* Получаем id текущего пользователя сайта */
if (class_exists('SiteUsers'))
{
/* Получаем id текущего пользователя сайта */
$SiteUsers = & singleton('SiteUsers');
$site_users_id = $SiteUsers->GetCurrentSiteUser();
}
else
{
$site_users_id = false;
}
$shop = & singleton('shop');
/* ID платежной системы берем из сессии */
$system_of_pay_id = to_int($_SESSION['system_of_pay_id']);
// статус платежа, по умолчанию 0
$order_row['status_of_pay'] = 0 ;
// дата платежа, по умолчанию пустая строка
$order_row['date_of_pay'] = '';
$order_row['description'] = to_str($_SESSION['description']);
// описание и системная информация, по умолчанию пустая строка
if (to_str($_SESSION['shop_coupon_text']) != '')
{
$order_row['description'] .= "Купон на скидку: ".to_str($_SESSION['shop_coupon_text'])."\n";
}
if (!isset($_SESSION['last_order_id']))
{
$_SESSION['last_order_id'] = 0;
}
// Если заказ еще не был оформлен
if ($_SESSION['last_order_id'] == 0)
{
/* Оформляем заказ */
$order_id = $shop->ProcessOrder($shop_id, $site_users_id, $system_of_pay_id, $order_row);
}
else
{
$order_id = $_SESSION['last_order_id'];
}
if ($order_id > 0)
{
if (!class_exists('SiteUsers'))
{
/* Класс пользователей сайта не существует, дописываем информацию о заказчике
в поле shop_order_description из текущей сессии */
if ($order_row)
{
/* Описание заказчика */
$order_row['description'] .= "Информация о заказчике:\n"
."Имя: ".to_str($_SESSION['site_users_name'])."\n"
."Фамилия: ".to_str($_SESSION['site_users_surname'])."\n"
."Отчество: ".to_str($_SESSION['site_users_patronymic'])."\n"
."E-Mail: ".to_str($_SESSION['site_users_email'])."\n"
."Телефон: ".to_str($_SESSION['site_users_phone'])."\n"
."Факс: ".to_str($_SESSION['site_users_fax'])."\n"
."Адрес: ".to_str($_SESSION['full_address'])."\n";
/* Дополнительная информация о заказе */
$order_row['system_information'] = to_str($_SESSION['system_information']);
/* Обязательно добавляем идентификатор! */
$order_row['id'] = $order_id;
$shop->InsertOrder($order_row);
}
}
$order_row = $shop->GetOrder($order_id);
if ($order_row)
{
$this->PrintOrder($order_id);
}
$shop_row = $shop->GetShop($shop_id);
if ($_SESSION['last_order_id'] == 0)
{
$structure = & singleton('Structure');
$structure_row = $structure->GetStructureItem(to_int($shop_row['structure_id']));
$lib = new lib();
$LA = $lib->LoadLibPropertiesValue(to_int($structure_row['lib_id']), to_int($structure_row['structure_id']));
$date_str = date("d.m.Y H:i:s");
if (trim(to_str($order_row['shop_order_account_number'])) != '')
{
$shop_order_account_number = trim(to_str($order_row['shop_order_account_number']));
}
else
{
$shop_order_account_number = $order_id;
}
/* Отправляем письмо заказчику */
$shop->SendMailAboutOrder($shop_id,
$order_id,
$site_users_id,
to_str($LA['xsl_letter_to_admin']),
to_str($LA['xsl_letter_to_user']),
$order_row['shop_order_users_email'],
array('admin-content-type' => 'html',
'user-content-type' => 'html',
'admin-subject' => sprintf($GLOBALS['MSG_shops']['shop_order_admin_subject'], $shop_order_account_number, $shop_row['shop_shops_name'], $date_str),
'user-subject' => sprintf($GLOBALS['MSG_shops']['shop_order_user_subject'], $shop_order_account_number, $shop_row['shop_shops_name'], $date_str),
'email_from_admin' => $order_row['shop_order_users_email']));
}
// Сохраняем ID последнего оформленного заказа ТОЛЬКО ПОСЛЕ ОТПРАВКИ ПИСЬМА
$_SESSION['last_order_id'] = $order_id;
}
else
{
switch ($order_id)
{
case -1:
{
echo "Ошибка вставки заказа в базу данных. Обратитесь к администратору.";
break;
}
case -2:
{
echo "Ошибка - не найден магазин. Обратитесь к администратору.";
break;
}
}
}
}
/**
* Метод, запускающий выполнение обработчика
*/
function Execute()
{
/* Пришло подтверждение оплаты, обработаем его */
if (isset($_POST['PayPalOrderConfirmation']))
{
$this->ProcessResult();
return true;
}
/* Пришел запрос на редирект, обработаем его */
if (isset($_POST['paymentType']))
{
$this->ReviewOrder();
return true;
}
/* Иначе оформляем заказ и отображаем стартовую страницу для оплаты через PayPal */
$this->ShowPurseRequest();
}
/**
* Обработка формы для получения ссылки и редирект
*
* @param int $order_id идентификатор заказа
*/
function ReviewOrder()
{
/* Информация о заказе */
$order_id = to_int($_POST['order_id']);
if (!$order_id)
{
return false;
}
$shop = & singleton('shop');
$order_row = $shop->GetOrder($order_id);
if (!$order_row)
{
return false;
}
$shop_row = $shop->GetShop($order_row['shop_shops_id']);
/****************************************************
CallerService.php
This file uses the constants.php to get parameters needed
to make an API call and calls the server.if you want use your
own credentials, you have to change the constants.php
Called by TransactionDetails.php, ReviewOrder.php,
DoDirectPaymentReceipt.php and DoExpressCheckoutPayment.php.
****************************************************/
/* An express checkout transaction starts with a token, that
identifies to PayPal your transaction
In this example, when the script sees a token, the script
knows that the buyer has already authorized payment through
paypal. If no token was found, the action is to send the buyer
to PayPal to first authorize payment
*/
if(!isset($_REQUEST['token']))
{
/* The servername and serverport tells PayPal where the buyer
should be directed back to after authorizing payment.
In this case, its the local webserver that is running this script
Using the servername and serverport, the return URL is the first
portion of the URL that buyers will return to after authorizing payment
*/
$serverName = $_SERVER['SERVER_NAME'];
$serverPort = $_SERVER['SERVER_PORT'];
$url = dirname('http://'.$serverName.':'.$serverPort.$_SERVER['REQUEST_URI']);
$currencyCodeType = $_REQUEST['currencyCodeType'];
$paymentType = $_REQUEST['paymentType'];
$personName = $_REQUEST['PERSONNAME'];
$SHIPTOSTREET = $_REQUEST['SHIPTOSTREET'];
$SHIPTOCITY = $_REQUEST['SHIPTOCITY'];
$SHIPTOSTATE = $_REQUEST['SHIPTOSTATE'];
$SHIPTOCOUNTRYCODE = $_REQUEST['SHIPTOCOUNTRYCODE'];
$SHIPTOZIP = $_REQUEST['SHIPTOZIP'];
$L_NAME0 = $_REQUEST['L_NAME0'];
$L_AMT0 = $_REQUEST['L_AMT0'];
$L_QTY0 = $_REQUEST['L_QTY0'];
/* The returnURL is the location where buyers return when a
payment has been succesfully authorized.
The cancelURL is the location buyers are sent to when they hit the
cancel button during authorization of payment during the PayPal flow
*/
$handler_url = $this->GetHandlerUrl($order_row['shop_shops_id']);
/*$returnURL =urlencode($url.'/ReviewOrder.php?currencyCodeType='.$currencyCodeType.'&paymentType='.$paymentType);
$cancelURL =urlencode("$url/SetExpressCheckout.php?paymentType=$paymentType" );*/
$returnURL = urlencode($handler_url."?currencyCodeType={$currencyCodeType}&paymentType={$paymentType}&order_id={$order_id}&payment=success&PayPalOrderConfirmation=1");
$cancelURL = urlencode($handler_url."?paymentType={$paymentType}&order_id={$order_id}&payment=failed");
/* Construct the parameter string that describes the PayPal payment
the varialbes were set in the web form, and the resulting string
is stored in $nvpstr
*/
/*$itemamt = 0.00;
$itemamt = $L_QTY0*$L_AMT0+$L_AMT1*$L_QTY1;
$amt = 5.00+2.59+1.00+$itemamt;
$maxamt= $amt+25.00;
$nvpstr="";*/
/*
* Setting up the Shipping address details
*/
$shiptoAddress = "&SHIPTONAME=$personName&SHIPTOSTREET=$SHIPTOSTREET&SHIPTOCITY=$SHIPTOCITY&SHIPTOSTATE=$SHIPTOSTATE&SHIPTOCOUNTRYCODE=$SHIPTOCOUNTRYCODE&SHIPTOZIP=$SHIPTOZIP";
$default_sum = $this->GetOrderSum($order_id);
$nvpstr = "&AMT=" . $default_sum . "&PAYMENTACTION=" . $paymentType . "&ReturnUrl=" . $returnURL . "&CANCELURL=" . $cancelURL . "&CURRENCYCODE=" . $currencyCodeType;
//$nvpstr="&ADDRESSOVERRIDE=1$shiptoAddress&L_NAME0=".$L_NAME0."&L_AMT0=".$L_AMT0."&L_QTY0=".$L_QTY0./*"&MAXAMT=".(string)$maxamt."&AMT=".(string)$amt."&ITEMAMT=".(string)$itemamt.*/"&CALLBACKTIMEOUT=4&L_SHIPPINGOPTIONAMOUNT1=8.00&L_SHIPPINGOPTIONlABEL1=UPS Next Day Air&L_SHIPPINGOPTIONNAME1=UPS Air&L_SHIPPINGOPTIONISDEFAULT1=true&L_SHIPPINGOPTIONAMOUNT0=3.50&L_SHIPPINGOPTIONLABEL0=UPS Ground 7 Days&L_SHIPPINGOPTIONNAME0=Ground&L_SHIPPINGOPTIONISDEFAULT0=false&INSURANCEAMT=1.00&INSURANCEOPTIONOFFERED=true&CALLBACK=https://d-sjn-00513807/callback.pl&SHIPPINGAMT=8.00&SHIPDISCAMT=-3.00&TAXAMT=2.59&L_NUMBER0=1000&L_DESC0=Size: 8.8-oz&L_NUMBER1=10001&L_DESC1=Size: Two 24-piece boxes&L_ITEMWEIGHTVALUE1=0.5&L_ITEMWEIGHTUNIT1=lbs&ReturnUrl=".$returnURL."&CANCELURL=".$cancelURL ."&CURRENCYCODE=".$currencyCodeType."&PAYMENTACTION=".$paymentType;
/* Make the call to PayPal to set the Express Checkout token
If the API call succeded, then redirect the buyer to PayPal
to begin to authorize payment. If an error occured, show the
resulting errors
*/
$resArray = $this->hash_call("SetExpressCheckout", $nvpstr);
$_SESSION['reshash'] = $resArray;
/////
/*$_SESSION['token'] = $resArray["TOKEN"];
$_SESSION['payer_id'] = $_REQUEST['PayerID'];
$_SESSION['paymentAmount'] = $_REQUEST['paymentAmount'];
$_SESSION['currCodeType'] = $_REQUEST['currencyCodeType'];
$_SESSION['paymentType'] = $paymentType;
$_SESSION['TotalAmount']= $default_sum;*/
/////
$ack = strtoupper($resArray["ACK"]);
if ($ack == "SUCCESS")
{
// Redirect to paypal.com here
$token = urldecode($resArray["TOKEN"]);
$payPalURL = PAYPAL_URL.$token;
header("Location: ".$payPalURL);
} else {
//Redirecting to APIError.php to display errors.
//$location = "APIError.php";
//header("Location: $location");
//Display a user friendly Error on the page using any of the following error information returned by PayPal
$ErrorCode = urldecode(to_str($resArray["L_ERRORCODE0"]));
$ErrorShortMsg = urldecode(to_str($resArray["L_SHORTMESSAGE0"]));
$ErrorLongMsg = urldecode(to_str($resArray["L_LONGMESSAGE0"]));
$ErrorSeverityCode = urldecode(to_str($resArray["L_SEVERITYCODE0"]));
echo "<p><b>SetExpressCheckout API call failed.</b></p>";
echo "Detailed Error Message: " . $ErrorLongMsg;
echo "<br />Short Error Message: " . $ErrorShortMsg;
echo "<br />Error Code: " . $ErrorCode;
echo "<br />Error Severity Code: " . $ErrorSeverityCode;
}
} else {
/* At this point, the buyer has completed in authorizing payment
at PayPal. The script will now call PayPal with the details
of the authorization, incuding any shipping information of the
buyer. Remember, the authorization is not a completed transaction
at this state - the buyer still needs an additional step to finalize
the transaction
*/
$token = urlencode($_REQUEST['token']);
/* Build a second API request to PayPal, using the token as the
ID to get the details on the payment authorization
*/
$nvpstr="&TOKEN=".$token;
/* Make the API call and store the results in an array. If the
call was a success, show the authorization details, and provide
an action to complete the payment. If failed, show the error
*/
$resArray = $this->hash_call("GetExpressCheckoutDetails", $nvpstr);
$_SESSION['reshash']=$resArray;
$ack = strtoupper($resArray["ACK"]);
if($ack == 'SUCCESS' || $ack == 'SUCCESSWITHWARNING')
{
$_SESSION['token'] = $_REQUEST['token'];
$_SESSION['payer_id'] = $_REQUEST['PayerID'];
$_SESSION['paymentAmount'] = $_REQUEST['paymentAmount'];
$_SESSION['currCodeType'] = $_REQUEST['currencyCodeType'];
$_SESSION['paymentType'] = $_REQUEST['paymentType'];
$resArray = $_SESSION['reshash'];
$_SESSION['TotalAmount'] = $resArray['AMT'] + $resArray['SHIPDISCAMT'];
}
else
{
//Redirecting to APIError.php to display errors.
//$location = "APIError.php";
//header("Location: $location");
//var_dump($ack);
}
}
}
function GetOrderSum($order_id)
{
$shop = & singleton('shop');
$order_row = $shop->GetOrder($order_id);
if ($order_row)
{
$order_sum = $shop->GetOrderSum($order_id);
$shop_row = $shop->GetShop($order_row['shop_shops_id']);
/* Делаем перерасчет суммы в валюты, выбранные для PayPal */
$shop_currency_id = $shop_row['shop_currency_id'];
/* Для валюты, в которой осуществляется платеж */
$coefficient = $shop->GetCurrencyCoefficientToShopCurrency($shop_currency_id, $this->default_currency_id);
$default_sum = round($order_sum * $coefficient, 2);
}
else
{
$default_sum = false;
}
return $default_sum;
}
/**
* Метод для отображения формы заказа для печати.
*
* @param int $order_id идентификатор заказа
*/
function PrintOrder($order_id)
{
$shop = & singleton('shop');
$order_row = $shop->GetOrder($order_id);
if (!$order_row)
{
return false;
}
if ($order_row)
{
$default_sum = $this->GetOrderSum($order_id);
$handler_url = $this->GetHandlerUrl($order_row['shop_shops_id']);
?>
<h1>Оплата через систему PayPal</h1>
<!-- Форма для оплаты через WMR -->
<form
id="pay" name="pay" method="post" action="<?php echo $handler_url?>"><input
type="hidden" name="paymentType" value="Sale"> <input type="hidden"
name="L_NAME0"
value="Order N <?php echo $order_row['shop_order_account_number']?>"> <input
type="hidden" name="L_AMT0" value="<?php echo $default_sum?>" /> <input
type="hidden" name="L_QTY0" value="1" />
<table>
<tr>
<td class="field">Currency:</td>
<td><strong><?php echo $default_sum?></strong> <select
name="currencyCodeType">
<option value="USD">USD</option>
<!-- <option value="GBP">GBP</option>
<option value="EUR">EUR</option>
<option value="JPY">JPY</option>
<option value="CAD">CAD</option>
<option value="AUD">AUD</option> -->
</select></td>
</tr>
<tr>
<td class="field">Ship To:</td>
<td> </td>
</tr>
<tr>
<td class="field">Name:</td>
<td><input type="text" size="30" maxlength="32" name="PERSONNAME"
value="True Seeker" /></td>
</tr>
<tr>
<td class="field">Street:</td>
<td><input type="text" size="30" maxlength="32" name="SHIPTOSTREET"
value="111, Bliss Ave" /></td>
</tr>
<tr>
<td class="field">City:</td>
<td><input type="text" size="30" maxlength="32" name="SHIPTOCITY"
value="San Jose" /></td>
</tr>
<tr>
<td class="field">State:</td>
<td><input type="text" size="30" maxlength="32" name="SHIPTOSTATE"
value="CA" /></td>
</tr>
<tr>
<td class="field">Country:</td>
<td><input type="text" size="30" maxlength="32"
name="SHIPTOCOUNTRYCODE" value="US" /></td>
</tr>
<tr>
<td class="field">Zip Code:</td>
<td><input type="text" size="30" maxlength="32" name="SHIPTOZIP"
value="95128" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="image" name="submit"
src="https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif" /></td>
</tr>
<tr>
<td colspan="2" align="center"><small>Save time. Pay securely without
sharing your financial information.</small></td>
</tr>
</table>
<!-- Для определения платежной системы на странице корзины --> <input
type="hidden" name="order_id" value="<?php echo $order_id?>">
<div style="clear: both;"></div>
</form>
<?php
}
}
/**
* Изменение статуса заказа. Позволяет пользователю внедрять собственные
* обработчики при изменении статуса.
*
* @param array $param массив атрибутов
* - $param['shop_order_id'] идентификатор заказа
* - $param['action'] выполняемое действие над заказом, может принимать
* значения: edit (редактирование заказа), cancel (отмена заказ),
* status (изменение статуса заказа), delete (удаление заказа)
*/
function ChangeStatus($param = array())
{
// Если произошло изменение статуса
if (isset($param['action']) && in_array($param['action'], array('status', 'edit')))
{
$shop_order_id = to_int($param['shop_order_id']);
$shop = & singleton('shop');
$order_row = $shop->GetOrder($shop_order_id);
// Получаем информацию о магазине
$shop_id = to_int($order_row['shop_shops_id']);
$shop_row = $shop->GetShop($shop_id);
$structure = & singleton('Structure');
$structure_row = $structure->GetStructureItem(to_int($shop_row['structure_id']));
$lib = new lib();
$LA = $lib->LoadLibPropertiesValue(to_int($structure_row['lib_id']), to_int($structure_row['structure_id']));
if ($order_row)
{
$DateClass = new DateClass();
$date_str = $DateClass->datetime_format($order_row['shop_order_date_time']);
}
else
{
$date_str = '';
}
// Если предыдущий статус заказа был 1, то меняем тему на подтверждение
if (to_int($order_row['shop_order_status_of_pay']) == 1)
{
$admin_subject = $GLOBALS['MSG_shops']['shop_order_confirm_admin_subject'];
$user_subject = $GLOBALS['MSG_shops']['shop_order_confirm_user_subject'];
}
else
{
$admin_subject = $GLOBALS['MSG_shops']['shop_order_admin_subject'];
$user_subject = $GLOBALS['MSG_shops']['shop_order_user_subject'];
}
// Письмо отправляем только при установке статуса активности для заказа
if (to_int($order_row['shop_order_status_of_pay']) == 1)
{
if (trim(to_str($order_row['shop_order_account_number'])) != '')
{
$shop_order_account_number = trim(to_str($order_row['shop_order_account_number']));
}
else
{
$shop_order_account_number = $shop_order_id;
}
/* Отправляем письмо заказчику */
$shop->SendMailAboutOrder($shop_id,
$shop_order_id,
$order_row['site_users_id'],
to_str($LA['xsl_letter_to_admin']),
to_str($LA['xsl_letter_to_user']),
$order_row['shop_order_users_email'],
array('admin-content-type' => 'html',
'user-content-type' => 'html',
'admin-subject' => sprintf($admin_subject, $shop_order_account_number, $shop_row['shop_shops_name'], $date_str),
'user-subject' => sprintf($user_subject, $shop_order_account_number, $shop_row['shop_shops_name'], $date_str),
'email_from_admin' => $order_row['shop_order_users_email']));
}
}
}
/**
* hash_call: Function to perform the API call to PayPal using API signature
* @methodName is name of API method.
* @nvpStr is nvp string.
* returns an associtive array containing the response from the server.
*/
function hash_call($methodName,$nvpStr)
{
//declaring of global variables
//setting the curl parameters.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, API_ENDPOINT);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
//turning off the server and peer verification(TrustManager Concept).
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POST, 1);
//if USE_PROXY constant set to TRUE in Constants.php, then only proxy will be enabled.
//Set proxy name to PROXY_HOST and port number to PROXY_PORT in constants.php
if(USE_PROXY)
curl_setopt ($ch, CURLOPT_PROXY, PROXY_HOST.":".PROXY_PORT);
//NVPRequest for submitting to server
/*if(API_AUTHENTICATION_MODE == '3TOKEN')
{
$nvpreq="METHOD=".urlencode($methodName)."&VERSION=".urlencode(VERSION)."&PWD=".urlencode(API_PASSWORD)."&USER=".urlencode(API_USERNAME)."&SIGNATURE=".urlencode(API_SIGNATURE).$nvpStr;
}
else if(API_AUTHENTICATION_MODE == 'UNIPAY')
{
$nvpreq="METHOD=".urlencode($methodName)."&VERSION=".urlencode(VERSION)."&SUBJECT=".urlencode(SUBJECT).$nvpStr;
}*/
//NVPRequest for submitting to server
$nvpreq="METHOD=" . urlencode($methodName) . "&VERSION=" . urlencode(VERSION) . "&PWD=" . urlencode(API_PASSWORD) . "&USER=" . urlencode(API_USERNAME) . "&SIGNATURE=" . urlencode(API_SIGNATURE) . $nvpStr . "&BUTTONSOURCE=" . urlencode(sBNCode);
//setting the nvpreq as POST FIELD to curl
curl_setopt($ch,CURLOPT_POSTFIELDS,$nvpreq);
//getting response from server
$response = curl_exec($ch);
//convrting NVPResponse to an Associative Array
$nvpResArray = $this->deformatNVP($response);
$nvpReqArray = $this->deformatNVP($nvpreq);
$_SESSION['nvpReqArray']=$nvpReqArray;
if (curl_errno($ch)) {
// moving to display page to display curl errors
$_SESSION['curl_error_no']=curl_errno($ch) ;
$_SESSION['curl_error_msg']=curl_error($ch);
//$location = "APIError.php";
//header("Location: $location");
echo curl_errno($ch) . ' ' . curl_error($ch);
} else {
//closing the curl
curl_close($ch);
}
return $nvpResArray;
}
/** This function will take NVPString and convert it to an Associative Array and it will decode the response.
* It is usefull to search for a particular key and displaying arrays.
* @nvpstr is NVPString.
* @nvpArray is Associative Array.
*/
function deformatNVP($nvpstr)
{
$intial = 0;
$nvpArray = array();
while(strlen($nvpstr))
{
//postion of Key
$keypos= strpos($nvpstr,'=');
//position of value
$valuepos = strpos($nvpstr,'&') ? strpos($nvpstr,'&'): strlen($nvpstr);
/*getting the Key and Value values and storing in a Associative Array*/
$keyval=substr($nvpstr,$intial,$keypos);
$valval=substr($nvpstr,$keypos+1,$valuepos-$keypos-1);
//decoding the respose
$nvpArray[urldecode($keyval)] =urldecode( $valval);
$nvpstr=substr($nvpstr,$valuepos+1,strlen($nvpstr));
}
return $nvpArray;
}
}
?>
/****************************************************
PayPal includes the following API Signature for making API
calls to the PayPal sandbox:
API Username sdk-three_api1.sdk.com
API Password QFZCWN5HZM8VBG7Q
API Signature A-IzJhZZjhg29XQ2qnhapuwxIDzyAZQ92FRP5dqBzVesOkzbdUONzmOU
****************************************************/
/*
# true - тестовый режим,
# false - рабочий режим,
*/
$SandboxFlag = true;
/**
# API user: The user that is identified as making the call. you can
# also use your own API username that you created on PayPal’s sandbox
# or the PayPal live site
*/
define('API_USERNAME', 'sdk-three_api1.sdk.com');
/**
# API_password: The password associated with the API user
# If you are using your own API username, enter the API password that
# was generated by PayPal below
# IMPORTANT - HAVING YOUR API PASSWORD INCLUDED IN THE MANNER IS NOT
# SECURE, AND ITS ONLY BEING SHOWN THIS WAY FOR TESTING PURPOSES
*/
define('API_PASSWORD', 'QFZCWN5HZM8VBG7Q');
/**
# API_Signature:The Signature associated with the API user. which is generated by paypal.
*/
define('API_SIGNATURE', 'A.d9eRKfd1yVkRrtmMfCFLTqa6M9AyodL0SJkhYztxUi8W9pCXF6.4NI');
// BN Code is only applicable for partners
define('sBNCode','PP-ECWizard');
/**
# Endpoint: this is the server URL which you have to connect for submitting your API request.
*/
/* Define the PayPal URL. This is the URL that the buyer is
first sent to to authorize payment with their paypal account
change the URL depending if you are testing on the sandbox
or going to the live PayPal site
For the sandbox, the URL is
For the live site, the URL is
*/
if ($SandboxFlag == true)
{
define('API_ENDPOINT', "https://api-3t.sandbox.paypal.com/nvp");
define('PAYPAL_URL', "https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token=");
}
else
{
define('API_ENDPOINT', "https://api-3t.paypal.com/nvp");
define('PAYPAL_URL', "https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=");
}
/*
# Third party Email address that you granted permission to make api call.
*/
define('SUBJECT','sdk-three@sdk.com');
/**
USE_PROXY: Set this variable to TRUE to route all the API requests through proxy.
like define('USE_PROXY',TRUE);
*/
define('USE_PROXY',FALSE);
/**
PROXY_HOST: Set the host name or the IP address of proxy server.
PROXY_PORT: Set proxy port.
PROXY_HOST and PROXY_PORT will be read only if USE_PROXY is set to TRUE
*/
define('PROXY_HOST', '127.0.0.1');
define('PROXY_PORT', '808');
/**
# Version: this is the API version in the request.
# It is a mandatory parameter for each API request.
# The only supported value at this time is 2.3
*/
define('VERSION', '60.0');
// Ack related constants
define('ACK_SUCCESS', 'SUCCESS');
define('ACK_SUCCESS_WITH_WARNING', 'SUCCESSWITHWARNING');
/* Оплата через PayPal */
class system_of_pay_handler
{
/* Определяем валюты для USD */
var $default_currency_id = 3;
/**
* Обработка статуса оплаты
*
*/
function ProcessResult()
{
/* Информация о заказе */
$order_id = to_int($_POST['order_id']);
if (!$order_id)
{
return false;
}
$shop = & singleton('shop');
$order_row = $shop->GetOrder($order_id);
if (!$order_row)
{
return false;
}
$shop_row = $shop->GetShop($order_row['shop_shops_id']);
ini_set('session.bug_compat_42',0);
ini_set('session.bug_compat_warn',0);
/* Gather the information to make the final call to
finalize the PayPal payment. The variable nvpstr
holds the name value pairs
*/
$_SESSION['token'] = $_REQUEST['token'];
$_SESSION['payer_id'] = $_REQUEST['PayerID'];
$_SESSION['paymentAmount']=$_REQUEST['paymentAmount'];
$_SESSION['currCodeType']=$_REQUEST['currencyCodeType'];
$_SESSION['paymentType']=$_REQUEST['paymentType'];
$resArray = $_SESSION['reshash'];
$_SESSION['TotalAmount']= $resArray['AMT'] + $resArray['SHIPDISCAMT'];
$token =urlencode($_SESSION['token']);
$paymentAmount =urlencode ($_SESSION['TotalAmount']);
$paymentType = urlencode($_SESSION['paymentType']);
$currCodeType = urlencode($_SESSION['currCodeType']);
$payerID = urlencode($_SESSION['payer_id']);
$serverName = urlencode($_SERVER['SERVER_NAME']);
$nvpstr='&TOKEN='.$token.'&PAYERID='.$payerID.'&PAYMENTACTION='.$paymentType.'&AMT='.$paymentAmount.'&CURRENCYCODE='.$currCodeType.'&IPADDRESS='.$serverName ;
/* Make the call to PayPal to finalize payment
If an error occured, show the resulting errors
*/
$resArray = hash_call("DoExpressCheckoutPayment", $nvpstr);
/* Display the API response back to the browser.
If the response from PayPal was a success, display the response parameters'
If the response was an error, display the errors received using APIError.php.
*/
$ack = strtoupper($resArray["ACK"]);
/* Устанавливаем параметры */
$param['id'] = $order_row['shop_order_id'];
$param['shop_shops_id'] = $order_row['shop_shops_id'];
$param['location_id'] = $order_row['shop_location_id'];
$param['country_id'] = $order_row['shop_country_id'];
$param['shop_city_id'] = $order_row['shop_city_id'];
$param['city_area_id'] = $order_row['shop_city_area_id'];
$param['shop_cond_of_delivery_id'] = $order_row['shop_cond_of_delivery_id'];
$param['delivery_price'] = $order_row['shop_order_delivery_price'];
$param['site_user_id'] = $order_row['site_users_id'];
$param['shop_order_status_id'] = $order_row['shop_order_status_id'];
$param['currency_id'] = $order_row['shop_currency_id'];
$param['shop_system_of_pay_id'] = $order_row['shop_system_of_pay_id'];
$param['order_date_time'] = $order_row['shop_order_date_time'];
$param['status_of_pay'] = $order_row['shop_order_status_of_pay'];
$param['date_of_pay'] = $order_row['shop_order_date_of_pay'];
$param['address'] = $order_row['shop_order_address'];
$param['index'] = $order_row['shop_order_index'];
$param['phone'] = $order_row['shop_order_phone'];
$param['description'] = $order_row['shop_order_description'];
if($ack == 'SUCCESS' || $ack == 'SUCCESSWITHWARNING')
{
/* Проверка прошла успешно!
Добавляем комментарий */
$param['system_information'] = "Товар оплачен через PayPal.\n".
"Атрибуты:\n".
"Transaction ID: {$resArray['TRANSACTIONID']}\n".
"Amount: {$resArray['AMT']} {$currCodeType}";
/* Устанавливаем признак оплаты */
//$param['date_of_pay'] = date("Y-m-d H:i:s");
//$param['status_of_pay'] = true;
// Обновляем информацию о заказе
$shop->InsertOrder($param);
// Изменяем статус оплаты ПОСЛЕ ОБНОВЛЕНИЯ ИНФОРМАЦИ, генерируем ссылки для эл.товаров, списываем товары
$shop->SetOrderPaymentStatus($order_id);
}
else
{
$param['system_information'] = 'PayPal не подтвердил платеж, ответ: {$ack}!';
// Обновляем информацию о заказе
$shop->InsertOrder($param);
}
// Отправку письма об оплате делаем только после вставки информации об оплате
if($ack == 'SUCCESS' || $ack == 'SUCCESSWITHWARNING')
{
$structure = & singleton('Structure');
$structure_row = $structure->GetStructureItem(to_int($shop_row['structure_id']));
$lib = new lib();
$LA = $lib->LoadLibPropertiesValue(to_int($structure_row['lib_id']), to_int($structure_row['structure_id']));
$order_row = $shop->GetOrder($order_id);
// Отправляем письмо администратору о подтверждении платежа
$shop->SendMailAboutOrder($order_row['shop_shops_id'], $order_id, $order_row['site_users_id'],
to_str($LA['xsl_letter_to_admin']),
to_str($LA['xsl_letter_to_user']),
$order_row['shop_order_users_email'],
array(
'admin-content-type' => 'html',
'user-content-type' => 'html',
'admin-subject' => sprintf($GLOBALS['MSG_shops']['shop_order_confirm_admin_subject'], $order_id, $shop_row['shop_shops_name'], $order_row['shop_order_date_of_pay']),
'user-subject' => sprintf($GLOBALS['MSG_shops']['shop_order_confirm_user_subject'], $order_id, $shop_row['shop_shops_name'], $order_row['shop_order_date_of_pay']),
'email_from_admin' => $order_row['shop_order_users_email']));
}
}
function GetHandlerUrl($shop_shops_id)
{
$shop = & singleton('shop');
$shop_row = $shop->GetShop($shop_shops_id);
if ($shop_row)
{
/* Информация об алиасе сайта */
$site = & singleton ('site');
$site_alias = $site->GetCurrentAlias($shop_row['site_id']);
/* Получаем путь к магазину */
$Structure = & singleton('Structure');
$shop_path = "/".$Structure->GetStructurePath($shop_row['structure_id'], 0);
$handler_url = 'http://'.$site_alias.$shop_path.'cart/';
}
else
{
$handler_url = '';
}
return $handler_url;
}
/**
* Отображает стартовую страницу для оплаты через Web Money.
*
*/
function ShowPurseRequest()
{
$shop_id = to_int($GLOBALS['shop_id']);
/* Получаем id текущего пользователя сайта */
if (class_exists('SiteUsers'))
{
/* Получаем id текущего пользователя сайта */
$SiteUsers = & singleton('SiteUsers');
$site_users_id = $SiteUsers->GetCurrentSiteUser();
}
else
{
$site_users_id = false;
}
$shop = & singleton('shop');
/* ID платежной системы берем из сессии */
$system_of_pay_id = to_int($_SESSION['system_of_pay_id']);
// статус платежа, по умолчанию 0
$order_row['status_of_pay'] = 0 ;
// дата платежа, по умолчанию пустая строка
$order_row['date_of_pay'] = '';
$order_row['description'] = to_str($_SESSION['description']);
// описание и системная информация, по умолчанию пустая строка
if (to_str($_SESSION['shop_coupon_text']) != '')
{
$order_row['description'] .= "Купон на скидку: ".to_str($_SESSION['shop_coupon_text'])."\n";
}
if (!isset($_SESSION['last_order_id']))
{
$_SESSION['last_order_id'] = 0;
}
// Если заказ еще не был оформлен
if ($_SESSION['last_order_id'] == 0)
{
/* Оформляем заказ */
$order_id = $shop->ProcessOrder($shop_id, $site_users_id, $system_of_pay_id, $order_row);
}
else
{
$order_id = $_SESSION['last_order_id'];
}
if ($order_id > 0)
{
if (!class_exists('SiteUsers'))
{
/* Класс пользователей сайта не существует, дописываем информацию о заказчике
в поле shop_order_description из текущей сессии */
if ($order_row)
{
/* Описание заказчика */
$order_row['description'] .= "Информация о заказчике:\n"
."Имя: ".to_str($_SESSION['site_users_name'])."\n"
."Фамилия: ".to_str($_SESSION['site_users_surname'])."\n"
."Отчество: ".to_str($_SESSION['site_users_patronymic'])."\n"
."E-Mail: ".to_str($_SESSION['site_users_email'])."\n"
."Телефон: ".to_str($_SESSION['site_users_phone'])."\n"
."Факс: ".to_str($_SESSION['site_users_fax'])."\n"
."Адрес: ".to_str($_SESSION['full_address'])."\n";
/* Дополнительная информация о заказе */
$order_row['system_information'] = to_str($_SESSION['system_information']);
/* Обязательно добавляем идентификатор! */
$order_row['id'] = $order_id;
$shop->InsertOrder($order_row);
}
}
$order_row = $shop->GetOrder($order_id);
if ($order_row)
{
$this->PrintOrder($order_id);
}
$shop_row = $shop->GetShop($shop_id);
if ($_SESSION['last_order_id'] == 0)
{
$structure = & singleton('Structure');
$structure_row = $structure->GetStructureItem(to_int($shop_row['structure_id']));
$lib = new lib();
$LA = $lib->LoadLibPropertiesValue(to_int($structure_row['lib_id']), to_int($structure_row['structure_id']));
$date_str = date("d.m.Y H:i:s");
if (trim(to_str($order_row['shop_order_account_number'])) != '')
{
$shop_order_account_number = trim(to_str($order_row['shop_order_account_number']));
}
else
{
$shop_order_account_number = $order_id;
}
/* Отправляем письмо заказчику */
$shop->SendMailAboutOrder($shop_id,
$order_id,
$site_users_id,
to_str($LA['xsl_letter_to_admin']),
to_str($LA['xsl_letter_to_user']),
$order_row['shop_order_users_email'],
array('admin-content-type' => 'html',
'user-content-type' => 'html',
'admin-subject' => sprintf($GLOBALS['MSG_shops']['shop_order_admin_subject'], $shop_order_account_number, $shop_row['shop_shops_name'], $date_str),
'user-subject' => sprintf($GLOBALS['MSG_shops']['shop_order_user_subject'], $shop_order_account_number, $shop_row['shop_shops_name'], $date_str),
'email_from_admin' => $order_row['shop_order_users_email']));
}
// Сохраняем ID последнего оформленного заказа ТОЛЬКО ПОСЛЕ ОТПРАВКИ ПИСЬМА
$_SESSION['last_order_id'] = $order_id;
}
else
{
switch ($order_id)
{
case -1:
{
echo "Ошибка вставки заказа в базу данных. Обратитесь к администратору.";
break;
}
case -2:
{
echo "Ошибка - не найден магазин. Обратитесь к администратору.";
break;
}
}
}
}
/**
* Метод, запускающий выполнение обработчика
*/
function Execute()
{
/* Пришло подтверждение оплаты, обработаем его */
if (isset($_POST['PayPalOrderConfirmation']))
{
$this->ProcessResult();
return true;
}
/* Пришел запрос на редирект, обработаем его */
if (isset($_POST['paymentType']))
{
$this->ReviewOrder();
return true;
}
/* Иначе оформляем заказ и отображаем стартовую страницу для оплаты через PayPal */
$this->ShowPurseRequest();
}
/**
* Обработка формы для получения ссылки и редирект
*
* @param int $order_id идентификатор заказа
*/
function ReviewOrder()
{
/* Информация о заказе */
$order_id = to_int($_POST['order_id']);
if (!$order_id)
{
return false;
}
$shop = & singleton('shop');
$order_row = $shop->GetOrder($order_id);
if (!$order_row)
{
return false;
}
$shop_row = $shop->GetShop($order_row['shop_shops_id']);
/****************************************************
CallerService.php
This file uses the constants.php to get parameters needed
to make an API call and calls the server.if you want use your
own credentials, you have to change the constants.php
Called by TransactionDetails.php, ReviewOrder.php,
DoDirectPaymentReceipt.php and DoExpressCheckoutPayment.php.
****************************************************/
/* An express checkout transaction starts with a token, that
identifies to PayPal your transaction
In this example, when the script sees a token, the script
knows that the buyer has already authorized payment through
paypal. If no token was found, the action is to send the buyer
to PayPal to first authorize payment
*/
if(!isset($_REQUEST['token']))
{
/* The servername and serverport tells PayPal where the buyer
should be directed back to after authorizing payment.
In this case, its the local webserver that is running this script
Using the servername and serverport, the return URL is the first
portion of the URL that buyers will return to after authorizing payment
*/
$serverName = $_SERVER['SERVER_NAME'];
$serverPort = $_SERVER['SERVER_PORT'];
$url = dirname('http://'.$serverName.':'.$serverPort.$_SERVER['REQUEST_URI']);
$currencyCodeType = $_REQUEST['currencyCodeType'];
$paymentType = $_REQUEST['paymentType'];
$personName = $_REQUEST['PERSONNAME'];
$SHIPTOSTREET = $_REQUEST['SHIPTOSTREET'];
$SHIPTOCITY = $_REQUEST['SHIPTOCITY'];
$SHIPTOSTATE = $_REQUEST['SHIPTOSTATE'];
$SHIPTOCOUNTRYCODE = $_REQUEST['SHIPTOCOUNTRYCODE'];
$SHIPTOZIP = $_REQUEST['SHIPTOZIP'];
$L_NAME0 = $_REQUEST['L_NAME0'];
$L_AMT0 = $_REQUEST['L_AMT0'];
$L_QTY0 = $_REQUEST['L_QTY0'];
/* The returnURL is the location where buyers return when a
payment has been succesfully authorized.
The cancelURL is the location buyers are sent to when they hit the
cancel button during authorization of payment during the PayPal flow
*/
$handler_url = $this->GetHandlerUrl($order_row['shop_shops_id']);
/*$returnURL =urlencode($url.'/ReviewOrder.php?currencyCodeType='.$currencyCodeType.'&paymentType='.$paymentType);
$cancelURL =urlencode("$url/SetExpressCheckout.php?paymentType=$paymentType" );*/
$returnURL = urlencode($handler_url."?currencyCodeType={$currencyCodeType}&paymentType={$paymentType}&order_id={$order_id}&payment=success&PayPalOrderConfirmation=1");
$cancelURL = urlencode($handler_url."?paymentType={$paymentType}&order_id={$order_id}&payment=failed");
/* Construct the parameter string that describes the PayPal payment
the varialbes were set in the web form, and the resulting string
is stored in $nvpstr
*/
/*$itemamt = 0.00;
$itemamt = $L_QTY0*$L_AMT0+$L_AMT1*$L_QTY1;
$amt = 5.00+2.59+1.00+$itemamt;
$maxamt= $amt+25.00;
$nvpstr="";*/
/*
* Setting up the Shipping address details
*/
$shiptoAddress = "&SHIPTONAME=$personName&SHIPTOSTREET=$SHIPTOSTREET&SHIPTOCITY=$SHIPTOCITY&SHIPTOSTATE=$SHIPTOSTATE&SHIPTOCOUNTRYCODE=$SHIPTOCOUNTRYCODE&SHIPTOZIP=$SHIPTOZIP";
$default_sum = $this->GetOrderSum($order_id);
$nvpstr = "&AMT=" . $default_sum . "&PAYMENTACTION=" . $paymentType . "&ReturnUrl=" . $returnURL . "&CANCELURL=" . $cancelURL . "&CURRENCYCODE=" . $currencyCodeType;
//$nvpstr="&ADDRESSOVERRIDE=1$shiptoAddress&L_NAME0=".$L_NAME0."&L_AMT0=".$L_AMT0."&L_QTY0=".$L_QTY0./*"&MAXAMT=".(string)$maxamt."&AMT=".(string)$amt."&ITEMAMT=".(string)$itemamt.*/"&CALLBACKTIMEOUT=4&L_SHIPPINGOPTIONAMOUNT1=8.00&L_SHIPPINGOPTIONlABEL1=UPS Next Day Air&L_SHIPPINGOPTIONNAME1=UPS Air&L_SHIPPINGOPTIONISDEFAULT1=true&L_SHIPPINGOPTIONAMOUNT0=3.50&L_SHIPPINGOPTIONLABEL0=UPS Ground 7 Days&L_SHIPPINGOPTIONNAME0=Ground&L_SHIPPINGOPTIONISDEFAULT0=false&INSURANCEAMT=1.00&INSURANCEOPTIONOFFERED=true&CALLBACK=https://d-sjn-00513807/callback.pl&SHIPPINGAMT=8.00&SHIPDISCAMT=-3.00&TAXAMT=2.59&L_NUMBER0=1000&L_DESC0=Size: 8.8-oz&L_NUMBER1=10001&L_DESC1=Size: Two 24-piece boxes&L_ITEMWEIGHTVALUE1=0.5&L_ITEMWEIGHTUNIT1=lbs&ReturnUrl=".$returnURL."&CANCELURL=".$cancelURL ."&CURRENCYCODE=".$currencyCodeType."&PAYMENTACTION=".$paymentType;
/* Make the call to PayPal to set the Express Checkout token
If the API call succeded, then redirect the buyer to PayPal
to begin to authorize payment. If an error occured, show the
resulting errors
*/
$resArray = $this->hash_call("SetExpressCheckout", $nvpstr);
$_SESSION['reshash'] = $resArray;
/////
/*$_SESSION['token'] = $resArray["TOKEN"];
$_SESSION['payer_id'] = $_REQUEST['PayerID'];
$_SESSION['paymentAmount'] = $_REQUEST['paymentAmount'];
$_SESSION['currCodeType'] = $_REQUEST['currencyCodeType'];
$_SESSION['paymentType'] = $paymentType;
$_SESSION['TotalAmount']= $default_sum;*/
/////
$ack = strtoupper($resArray["ACK"]);
if ($ack == "SUCCESS")
{
// Redirect to paypal.com here
$token = urldecode($resArray["TOKEN"]);
$payPalURL = PAYPAL_URL.$token;
header("Location: ".$payPalURL);
} else {
//Redirecting to APIError.php to display errors.
//$location = "APIError.php";
//header("Location: $location");
//Display a user friendly Error on the page using any of the following error information returned by PayPal
$ErrorCode = urldecode(to_str($resArray["L_ERRORCODE0"]));
$ErrorShortMsg = urldecode(to_str($resArray["L_SHORTMESSAGE0"]));
$ErrorLongMsg = urldecode(to_str($resArray["L_LONGMESSAGE0"]));
$ErrorSeverityCode = urldecode(to_str($resArray["L_SEVERITYCODE0"]));
echo "<p><b>SetExpressCheckout API call failed.</b></p>";
echo "Detailed Error Message: " . $ErrorLongMsg;
echo "<br />Short Error Message: " . $ErrorShortMsg;
echo "<br />Error Code: " . $ErrorCode;
echo "<br />Error Severity Code: " . $ErrorSeverityCode;
}
} else {
/* At this point, the buyer has completed in authorizing payment
at PayPal. The script will now call PayPal with the details
of the authorization, incuding any shipping information of the
buyer. Remember, the authorization is not a completed transaction
at this state - the buyer still needs an additional step to finalize
the transaction
*/
$token = urlencode($_REQUEST['token']);
/* Build a second API request to PayPal, using the token as the
ID to get the details on the payment authorization
*/
$nvpstr="&TOKEN=".$token;
/* Make the API call and store the results in an array. If the
call was a success, show the authorization details, and provide
an action to complete the payment. If failed, show the error
*/
$resArray = $this->hash_call("GetExpressCheckoutDetails", $nvpstr);
$_SESSION['reshash']=$resArray;
$ack = strtoupper($resArray["ACK"]);
if($ack == 'SUCCESS' || $ack == 'SUCCESSWITHWARNING')
{
$_SESSION['token'] = $_REQUEST['token'];
$_SESSION['payer_id'] = $_REQUEST['PayerID'];
$_SESSION['paymentAmount'] = $_REQUEST['paymentAmount'];
$_SESSION['currCodeType'] = $_REQUEST['currencyCodeType'];
$_SESSION['paymentType'] = $_REQUEST['paymentType'];
$resArray = $_SESSION['reshash'];
$_SESSION['TotalAmount'] = $resArray['AMT'] + $resArray['SHIPDISCAMT'];
}
else
{
//Redirecting to APIError.php to display errors.
//$location = "APIError.php";
//header("Location: $location");
//var_dump($ack);
}
}
}
function GetOrderSum($order_id)
{
$shop = & singleton('shop');
$order_row = $shop->GetOrder($order_id);
if ($order_row)
{
$order_sum = $shop->GetOrderSum($order_id);
$shop_row = $shop->GetShop($order_row['shop_shops_id']);
/* Делаем перерасчет суммы в валюты, выбранные для PayPal */
$shop_currency_id = $shop_row['shop_currency_id'];
/* Для валюты, в которой осуществляется платеж */
$coefficient = $shop->GetCurrencyCoefficientToShopCurrency($shop_currency_id, $this->default_currency_id);
$default_sum = round($order_sum * $coefficient, 2);
}
else
{
$default_sum = false;
}
return $default_sum;
}
/**
* Метод для отображения формы заказа для печати.
*
* @param int $order_id идентификатор заказа
*/
function PrintOrder($order_id)
{
$shop = & singleton('shop');
$order_row = $shop->GetOrder($order_id);
if (!$order_row)
{
return false;
}
if ($order_row)
{
$default_sum = $this->GetOrderSum($order_id);
$handler_url = $this->GetHandlerUrl($order_row['shop_shops_id']);
?>
<h1>Оплата через систему PayPal</h1>
<!-- Форма для оплаты через WMR -->
<form
id="pay" name="pay" method="post" action="<?php echo $handler_url?>"><input
type="hidden" name="paymentType" value="Sale"> <input type="hidden"
name="L_NAME0"
value="Order N <?php echo $order_row['shop_order_account_number']?>"> <input
type="hidden" name="L_AMT0" value="<?php echo $default_sum?>" /> <input
type="hidden" name="L_QTY0" value="1" />
<table>
<tr>
<td class="field">Currency:</td>
<td><strong><?php echo $default_sum?></strong> <select
name="currencyCodeType">
<option value="USD">USD</option>
<!-- <option value="GBP">GBP</option>
<option value="EUR">EUR</option>
<option value="JPY">JPY</option>
<option value="CAD">CAD</option>
<option value="AUD">AUD</option> -->
</select></td>
</tr>
<tr>
<td class="field">Ship To:</td>
<td> </td>
</tr>
<tr>
<td class="field">Name:</td>
<td><input type="text" size="30" maxlength="32" name="PERSONNAME"
value="True Seeker" /></td>
</tr>
<tr>
<td class="field">Street:</td>
<td><input type="text" size="30" maxlength="32" name="SHIPTOSTREET"
value="111, Bliss Ave" /></td>
</tr>
<tr>
<td class="field">City:</td>
<td><input type="text" size="30" maxlength="32" name="SHIPTOCITY"
value="San Jose" /></td>
</tr>
<tr>
<td class="field">State:</td>
<td><input type="text" size="30" maxlength="32" name="SHIPTOSTATE"
value="CA" /></td>
</tr>
<tr>
<td class="field">Country:</td>
<td><input type="text" size="30" maxlength="32"
name="SHIPTOCOUNTRYCODE" value="US" /></td>
</tr>
<tr>
<td class="field">Zip Code:</td>
<td><input type="text" size="30" maxlength="32" name="SHIPTOZIP"
value="95128" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="image" name="submit"
src="https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif" /></td>
</tr>
<tr>
<td colspan="2" align="center"><small>Save time. Pay securely without
sharing your financial information.</small></td>
</tr>
</table>
<!-- Для определения платежной системы на странице корзины --> <input
type="hidden" name="order_id" value="<?php echo $order_id?>">
<div style="clear: both;"></div>
</form>
<?php
}
}
/**
* Изменение статуса заказа. Позволяет пользователю внедрять собственные
* обработчики при изменении статуса.
*
* @param array $param массив атрибутов
* - $param['shop_order_id'] идентификатор заказа
* - $param['action'] выполняемое действие над заказом, может принимать
* значения: edit (редактирование заказа), cancel (отмена заказ),
* status (изменение статуса заказа), delete (удаление заказа)
*/
function ChangeStatus($param = array())
{
// Если произошло изменение статуса
if (isset($param['action']) && in_array($param['action'], array('status', 'edit')))
{
$shop_order_id = to_int($param['shop_order_id']);
$shop = & singleton('shop');
$order_row = $shop->GetOrder($shop_order_id);
// Получаем информацию о магазине
$shop_id = to_int($order_row['shop_shops_id']);
$shop_row = $shop->GetShop($shop_id);
$structure = & singleton('Structure');
$structure_row = $structure->GetStructureItem(to_int($shop_row['structure_id']));
$lib = new lib();
$LA = $lib->LoadLibPropertiesValue(to_int($structure_row['lib_id']), to_int($structure_row['structure_id']));
if ($order_row)
{
$DateClass = new DateClass();
$date_str = $DateClass->datetime_format($order_row['shop_order_date_time']);
}
else
{
$date_str = '';
}
// Если предыдущий статус заказа был 1, то меняем тему на подтверждение
if (to_int($order_row['shop_order_status_of_pay']) == 1)
{
$admin_subject = $GLOBALS['MSG_shops']['shop_order_confirm_admin_subject'];
$user_subject = $GLOBALS['MSG_shops']['shop_order_confirm_user_subject'];
}
else
{
$admin_subject = $GLOBALS['MSG_shops']['shop_order_admin_subject'];
$user_subject = $GLOBALS['MSG_shops']['shop_order_user_subject'];
}
// Письмо отправляем только при установке статуса активности для заказа
if (to_int($order_row['shop_order_status_of_pay']) == 1)
{
if (trim(to_str($order_row['shop_order_account_number'])) != '')
{
$shop_order_account_number = trim(to_str($order_row['shop_order_account_number']));
}
else
{
$shop_order_account_number = $shop_order_id;
}
/* Отправляем письмо заказчику */
$shop->SendMailAboutOrder($shop_id,
$shop_order_id,
$order_row['site_users_id'],
to_str($LA['xsl_letter_to_admin']),
to_str($LA['xsl_letter_to_user']),
$order_row['shop_order_users_email'],
array('admin-content-type' => 'html',
'user-content-type' => 'html',
'admin-subject' => sprintf($admin_subject, $shop_order_account_number, $shop_row['shop_shops_name'], $date_str),
'user-subject' => sprintf($user_subject, $shop_order_account_number, $shop_row['shop_shops_name'], $date_str),
'email_from_admin' => $order_row['shop_order_users_email']));
}
}
}
/**
* hash_call: Function to perform the API call to PayPal using API signature
* @methodName is name of API method.
* @nvpStr is nvp string.
* returns an associtive array containing the response from the server.
*/
function hash_call($methodName,$nvpStr)
{
//declaring of global variables
//setting the curl parameters.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, API_ENDPOINT);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
//turning off the server and peer verification(TrustManager Concept).
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POST, 1);
//if USE_PROXY constant set to TRUE in Constants.php, then only proxy will be enabled.
//Set proxy name to PROXY_HOST and port number to PROXY_PORT in constants.php
if(USE_PROXY)
curl_setopt ($ch, CURLOPT_PROXY, PROXY_HOST.":".PROXY_PORT);
//NVPRequest for submitting to server
/*if(API_AUTHENTICATION_MODE == '3TOKEN')
{
$nvpreq="METHOD=".urlencode($methodName)."&VERSION=".urlencode(VERSION)."&PWD=".urlencode(API_PASSWORD)."&USER=".urlencode(API_USERNAME)."&SIGNATURE=".urlencode(API_SIGNATURE).$nvpStr;
}
else if(API_AUTHENTICATION_MODE == 'UNIPAY')
{
$nvpreq="METHOD=".urlencode($methodName)."&VERSION=".urlencode(VERSION)."&SUBJECT=".urlencode(SUBJECT).$nvpStr;
}*/
//NVPRequest for submitting to server
$nvpreq="METHOD=" . urlencode($methodName) . "&VERSION=" . urlencode(VERSION) . "&PWD=" . urlencode(API_PASSWORD) . "&USER=" . urlencode(API_USERNAME) . "&SIGNATURE=" . urlencode(API_SIGNATURE) . $nvpStr . "&BUTTONSOURCE=" . urlencode(sBNCode);
//setting the nvpreq as POST FIELD to curl
curl_setopt($ch,CURLOPT_POSTFIELDS,$nvpreq);
//getting response from server
$response = curl_exec($ch);
//convrting NVPResponse to an Associative Array
$nvpResArray = $this->deformatNVP($response);
$nvpReqArray = $this->deformatNVP($nvpreq);
$_SESSION['nvpReqArray']=$nvpReqArray;
if (curl_errno($ch)) {
// moving to display page to display curl errors
$_SESSION['curl_error_no']=curl_errno($ch) ;
$_SESSION['curl_error_msg']=curl_error($ch);
//$location = "APIError.php";
//header("Location: $location");
echo curl_errno($ch) . ' ' . curl_error($ch);
} else {
//closing the curl
curl_close($ch);
}
return $nvpResArray;
}
/** This function will take NVPString and convert it to an Associative Array and it will decode the response.
* It is usefull to search for a particular key and displaying arrays.
* @nvpstr is NVPString.
* @nvpArray is Associative Array.
*/
function deformatNVP($nvpstr)
{
$intial = 0;
$nvpArray = array();
while(strlen($nvpstr))
{
//postion of Key
$keypos= strpos($nvpstr,'=');
//position of value
$valuepos = strpos($nvpstr,'&') ? strpos($nvpstr,'&'): strlen($nvpstr);
/*getting the Key and Value values and storing in a Associative Array*/
$keyval=substr($nvpstr,$intial,$keypos);
$valval=substr($nvpstr,$keypos+1,$valuepos-$keypos-1);
//decoding the respose
$nvpArray[urldecode($keyval)] =urldecode( $valval);
$nvpstr=substr($nvpstr,$valuepos+1,strlen($nvpstr));
}
return $nvpArray;
}
}
?>
здравствуйте. был такой опыт - принимали пейпал к оплате, но сам пейпал через пару дней проверяет транзакции и если что то не нравиться ему то пейпал блокирует и отзывает платеж! получается - к продавцу пришли оплатили товар получили а на след. день полученный платеж заблокировали и отозвали! т. е. продавец лишился данной оплаты а товар то отдан!
Вопрос - будет ли какая то возможность настроить так чтобы платежи принимались только от верифицированных аккаунтов? иначе теряется всякий смысл в этом методе оплаты, ворованный пейпал система ловит в течении суток , за сут ки можно оплатить и получить товар, а через сутки у добросовестного продавца этот платеж заблокируют и товар вернуть тоже не возможно т.к. его уже используют!
Вопрос - будет ли какая то возможность настроить так чтобы платежи принимались только от верифицированных аккаунтов? иначе теряется всякий смысл в этом методе оплаты, ворованный пейпал система ловит в течении суток , за сут ки можно оплатить и получить товар, а через сутки у добросовестного продавца этот платеж заблокируют и товар вернуть тоже не возможно т.к. его уже используют!
деньги сразу тогда продавцу надо тратить....
пока не заблокоровали платёж...
пока не заблокоровали платёж...Lika, это обычная практика - есть такое понятие чардж бэк, т.е чел заплатил за товар и имеет право в течении трех дней его отозвать, и это согласно законодательной базе, мне как то раз знакомец эту тему объяснял, сами думаем как на hostcms реализовать разбиение пользователей на новичков и проверенных

Вообщем пытаюсьподключить пейпал к сайту, забил все как нужно и описано но при отправке данных заказа на пейпал, выдает следующие
ПРЕДУПРЕЖДЕНИЕ: Cannot modify header information - headers already sent by (output started at /home/users2/d/divo/domains/sta2.belgar.ru/modules/shop/shop.class.php:19251) в файле /home/users2/d/divo/domains/sta2.belgar.ru/hostcmsfiles/shop/pay/handler10.php (строка 564)
где копать?
ПРЕДУПРЕЖДЕНИЕ: Cannot modify header information - headers already sent by (output started at /home/users2/d/divo/domains/sta2.belgar.ru/modules/shop/shop.class.php:19251) в файле /home/users2/d/divo/domains/sta2.belgar.ru/hostcmsfiles/shop/pay/handler10.php (строка 564)
где копать?
Делаю то благодаря чему, несмотря ни на что
suba писал(а):
в 564й строке файла /home/users2/d/divo/domains/sta2.belgar.ru/hostcmsfiles/shop/pay/handler10.php
В этом файле обработчик платежной системы с id=10,
а в строке 564 написано
Мне что-то подсказывает, что после этой строки не хватает команды
правда с пайпалом я в своей практике не сталкивался и может быть я ошибаюсь, но вы попробуйте
где копать?
в 564й строке файла /home/users2/d/divo/domains/sta2.belgar.ru/hostcmsfiles/shop/pay/handler10.php

В этом файле обработчик платежной системы с id=10,
а в строке 564 написано
header("Location: ".$payPalURL);
Мне что-то подсказывает, что после этой строки не хватает команды
exit();
правда с пайпалом я в своей практике не сталкивался и может быть я ошибаюсь, но вы попробуйте

Заказов не беру. Консультирую редко.
Благодарю, попробовал только что но каких то сдвигов не дало, это обработчик системы пейпала полностью такой же как и на демо сайте...
Делаю то благодаря чему, несмотря ни на что
Авторизация