Вход Регистрация
Файл: pay1/123hghgnjoifjofjg.php
Строк: 428
<?php
/**
 * Реализация протокола продажи игровой валюты. Пример.
 *
 * Virtual Currency Protocol Implementation. Sample.
 *
 * @version 1.0
 * @author Xsolla
 */

/*
 * Команда на создание таблицы с пользователями
CREATE TABLE  `dvapay`.`characters` (
 `id` int(10) NOT NULL AUTO_INCREMENT,
 `v1` varchar(255) NOT NULL,
 `v2` varchar(255) DEFAULT NULL,
 `v3` varchar(255) DEFAULT NULL,
 PRIMARY KEY (`id`),
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=cp1251;
*/

/*
 * Команда на создание биллинговой таблицы
CREATE TABLE  `dvapay`.`xsolla_billing` (
 `id` int(10) NOT NULL AUTO_INCREMENT,
 `invoice` bigint(20) NOT NULL COMMENT 'Xsolla invoice ID',
 `v1` varchar(255) NOT NULL,
 `v2` varchar(255) DEFAULT NULL,
 `v3` varchar(255) DEFAULT NULL,
 `amount` decimal(10,2) NOT NULL COMMENT 'Amount of payment',
 `currency` varchar(3) DEFAULT NULL COMMENT 'Payment currency',
 `date_add` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
 `canceled` enum('0','1') NOT NULL DEFAULT '0',
 `date_cancel` timestamp NULL DEFAULT NULL,
 PRIMARY KEY (`id`),
 UNIQUE KEY `invoice_UNIQUE` (`invoice`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=cp1251;
*/

/**
 * Config class
 */
Class Config {

    
/**
     * Параметры для подключения к базе
     *
     * @var String
     */
    
const dbHost 'localhost';
    const 
dbUser 'wistis';
    const 
dbPassword 'agres3105';
    const 
db 'a36667_element';

    
/**
     * Параметры для названий таблиц в базе
     *
     * @var String
     */
    
const dbPaymentsTable 'xsolla_billing';
    const 
dbCharactersTable 'table1';

    
/**
     * Секретный ключ проекта (секретный ключ вы можете уточнить у вашего менеджера)
     *
     * @var String
     */
    
const secretKey 'C,-PLRpB?-IiV>5Jw3PnlV)Zy,(.M;Cl';

    
/**
     * Список разрешенных IP-адресов
     *
     * @var Array
     */
    
public static $allowedIPs = array("94.103.26.178""94.103.26.181","94.103.26.180","94.103.26.179","94.103.26.182");

}

/**
 * Класс, реализующий протокол продажи игровой валюты.
 *
 * В классе реализована работа с основными методами по протоколу "Продажа игровой валюты".
 * Для того чтобы заставить его работать, нужно заменить параметры на свои.
 * Описание протокола доступно по адресу @see http://xsolla.ru/docs/virtual-currency-protocol
 *
 * Class that implements "Virtual Currency Protocol"
 *
 * In this sample class you can find implementation of main methods of "Virtual Currency Protocol".
 * To start script, replace parameters by your own parameters (based on your system).
 * Full description you can find here @see http://xsolla.com/docs/virtual-currency-protocol
 *
 * @version 1.0
 * @author Xsolla
 */
Class VirtualCurrencyProtocolImplementation
{
    
/**
     * Коды завершения
     *
     * End codes
     */
    
const _codeSuccess 0;
    const 
_codeTemporaryError 1;
    const 
_codeCancelNotFound 2;
    const 
_codeIncorrectSignature 3;
    const 
_codeIncorrectRequestFormat 4;
    const 
_codeOtherError 5;
    const 
_codePaymentCannotBeProcessed 7;

    private 
$_connect;

    public function 
__construct()
    {
        
$this->_connect mysql_connect(Config::dbHostConfig::dbUserConfig::dbPassword);
        
mysql_select_db(Config::db$this->_connect);
    }

    
/**
     * Проверяет подпись при проверке ника
     *
     * Checks signature when using check method
     *
     * @return Boolean
     */
    
private function _checkStatusSignature()
    {
        return 
md5($_GET["command"].urldecode($_GET["v1"]).Config::secretKey) === $_GET["md5"];
    }

    
/**
     * Проверяет подпись при платеже
     *
     * Checks signature when using pay method
     *
     * @return Boolean
     */
    
private function _checkPaySignature()
    {
        return 
md5($_GET["command"].urldecode($_GET["v1"]).$_GET["id"].Config::secretKey) === $_GET["md5"];
    }

    
/**
     * Проверяет подпись при проверке ника
     *
     * Checks signature when using check method
     *
     * @return Boolean
     */
    
private function _checkCancelSignature()
    {
        return 
md5($_GET["command"].urldecode($_GET["id"]).Config::secretKey) === $_GET["md5"];
    }

    
/**
     * Метод проверки ника
     *
     * Method for nickname check
     *
     * @throws Exception
     */
    
public function processCheckRequest()
    {
        try
        {
            
/**
             * Проверяем наличие параметра v1 - никнейм, аккаунт и тд
             *
             * Checking existance of v1 - nickname, account and so on
             */
            
if (!isset($_GET["v1"]))
                throw new 
Exception("User ID is undefined");
            
/**
             * Проверяем наличие дополнительных параметров v2, v3. Если вы не поддерживаете эти параметры, закомментируете эти строки
             *
             * Checking existance of v2, v3. If you don't support these parametres, please comment out these lines
             */

            
if (!isset($_GET["v2"]))
                throw new 
Exception("User ID is undefined");

            if (!isset(
$_GET["v3"]))
                throw new 
Exception("User ID is undefined");

            
/*
             * Проверяем наличие параметра подписи md5
             */
            
if (!isset($_GET["md5"]))
                throw new 
Exception("Signature is undefined");

            
/**
             * Проверяем подпись
             *
             * Checking signature
             */
            
if (!$this->_checkStatusSignature())
                throw new 
Exception("Incorrect signature");

            
/* YOUR CHECK CODE HERE */
            /* Пример кода. Code example */
            /* Если вы не используете параметры v2, v3, используйте указанную ниже строку*/
            //$sql = 'SELECT count(1) as cnt FROM '.Config::dbCharactersTable.' WHERE v1 = ' . addslashes($_GET['v1']);
            
$sql 'SELECT count(1) as cnt FROM '.Config::dbCharactersTable.' WHERE ID = ' addslashes($_GET['v1']) ;
            
$result mysql_query($sql$this->_connect);
            
$checked mysql_fetch_assoc ($result);
            if (
$checked['cnt'] != 0)
            {
                
$responseCode self::_codeSuccess;
                
$responseDesc 'OK';
            }
            else
            {
                
$responseCode self::_codePaymentCannotBeProcessed;
                
$responseDesc 'Character doesn't exist.';
            }
            /* */

            /* Генерируем ответ */
            $this->_generateCheckResponse($responseCode, $responseDesc);
        }
        catch (Exception $e)
        {
            $this->_errorCheckResponse($e);
        }
    }

    /**
     * Метод для поведения платежа
     *
     * Pay method
     *
     * @throws Exception
     */
    public function processPayRequest()
    {
        try
        {
            /* Выполняем необходимые проверки */
            if (!isset($_GET["id"]))
                throw new Exception("Invoice is undefined");

            if (!isset($_GET["v1"]))
                throw new Exception("User ID is undefined");

            /*Если вы не используете параметры v2, v3, закомментируйте эти строки*/

            if (!isset($_GET["v2"]))
                throw new Exception("User ID is undefined");

            if (!isset($_GET["v3"]))
                throw new Exception("User ID is undefined");

            if (!isset($_GET["sum"]))
                throw new Exception("Amount is undefined");

            if (!isset($_GET["md5"]))
                throw new Exception("Signature is undefined");

            if (!$this->_checkPaySignature())
                throw new Exception("Incorrect signature");

            

            /* Смотрим, есть ли в системе платеж с таким xsolla-id */
            $sql = '
SELECT `idFROM '.Config::dbPaymentsTable.' WHERE `invoice` = ' . $_GET['id'];
            $result = mysql_query ($sql, $this->_connect);
            $exist = mysql_fetch_assoc ($result);
            /* Если в системе еще нет такого платежа, проводим */
            if (!$exist['
id'])
            {
                /*Если вы не используете параметры v2, v3, используйте указанную ниже строку*/
                $sql = '
INSERT INTO `'.Config::dbPaymentsTable.'` (`v1`, `amount`, `invoice`, `date_add`, `canceled`) VALUES ('. $_GET['v1'] . '' . $_GET['sum'] . '' . $_GET['id'] . 'NOW(), "0")';
                
                mysql_query ($sql, $this->_connect);
                $id_shop = mysql_insert_id ();
                
                /* YOUR PAY CODE HERE */
 $query = "SELECT * FROM `table1` WHERE `ID`='".
$_GET['v1']."'" ;


 $sql1 = mysql_query($query) or die(mysql_error()) ;
 $row = mysql_fetch_assoc($sql1) ;

$f=$_GET["sum"]*250;


$cent=$row['
cent']+$f;
mysql_query("UPDATE `table1` set `cent`='
$cent' where `ID`='".$_GET['v1']."'  limit  1");
$da=date('
n');
if($row['
partner']>0){
mysql_query("INSERT INTO `a36667_element`.`partner_cent` (
`id` ,
`cent` ,
`mons` 
)
VALUES (
'".
$row['partner']."', '$f', '$da'
);");
}




                //////////////////////////////////////////////////////////////////
                $this->_generatePayResponse(0, '
OK', $_GET['id'], $id_shop, $_GET['sum']);
            }
            else
            {
                /* Если в системе уже есть такой платеж, то отвечаем "успех" */
                $this->_generatePayResponse(0, '
OK', $_GET['id'], $exist['id'], $_GET['sum']);
            }
            /* END YOUR CODE */
        }
        catch (Exception $e)
        {
            $this->_errorPayResponse($e);
        }
    }

    /**
     * Метод для отката платежа
     *
     * Payment cancel method
     *
     * @throws Exception
     */
    public function processCancelRequest()
    {
        try
        {
            if (!isset($_GET["id"]))
                throw new Exception("Invoice is undefined");

            if (!isset($_GET["md5"]))
                throw new Exception("Signature is undefined");

            if (!$this->_checkCancelSignature())
                throw new Exception("Incorrect signature");

            /* Отменяем платеж */
            $sql = '
UPDATE `'.Config::dbPaymentsTable.'SET `canceled` = "1", `date_cancel` = NOW() WHERE `invoice` = '. $_GET['id'];
            mysql_query($sql, $this->_connect);

            /* Ответ */
            $this->_generateCancelResponse(0, '
OK');
        }
        catch (Exception $e)
        {
            $this->_errorCancelResponse($e);
        }
    }

    /**
     * Главный метод, который определяет что делать в зависимости от параметров
     *
     * Main method
     *
     * @throws Exception
     */
    public function processRequest()
    {
        try
        {
            /* Ограничение по IP-адресу */

            if (!in_array($_SERVER["REMOTE_ADDR"], Config::$allowedIPs))
                throw new Exception ("IP address is not allowed");

            if (!isset($_GET["command"]))
                throw new Exception("Command is undefined");

            $command = $_GET["command"];

            if ($command == "check")
            {
                $this->processCheckRequest();
            }
            elseif ($command == "pay")
            {
                $this->processPayRequest();
            }
            elseif ($command == "cancel")
            {
                $this->processCancelRequest();
            }
            else
            {
                throw new Exception("Incorrect command");
            }
        }
        catch (Exception $e)
        {
            $this->_errorCheckResponse($e);
        }
    }

    /**
     * Генерирует ответ на запрос проверки ника
     *
     * Generates answer when using nickname check method
     *
     * @param Int $code
     * @param String $description
     */
    private function _generateCheckResponse($code, $description)
    {
        $xml = new SimpleXMLElement("<response></response>");

        $xml->addChild("result", $code);
        $xml->addChild("comment", $description);

        header("Content-Type: text/xml; charset=cp1251");
        echo html_entity_decode($xml->asXML(), ENT_COMPAT, '
windows-1251');
    }

    /**
     * Генерирует ответ на проведение платежа
     *
     * Generates answer when using pay method
     *
     * @param Int $code
     * @param String $description
     * @param Int $invoice
     * @param Int $order
     * @param Float $sum
     */
    private function _generatePayResponse($code, $description, $invoice = 0, $order = 0, $sum = 0)
    {
        $xml = new SimpleXMLElement("<response></response>");

        $xml->addChild("id", $invoice);
        $xml->addChild("id_shop", $order);
        $xml->addChild("sum", $sum);
        $xml->addChild("result", $code);
        $xml->addChild("comment", $description);

        header("Content-Type: text/xml; charset=cp1251");
        echo html_entity_decode($xml->asXML(), ENT_COMPAT, '
windows-1251');
    }

    /**
     * Генерирует ответ на откат платежа
     *
     * Generates answer when using payment cancel method
     *
     * @param Int $code
     * @param String $description
     */
    private function _generateCancelResponse($code, $description)
    {
        $xml = new SimpleXMLElement("<response></response>");

        $xml->addChild("result", $code);
        $xml->addChild("comment", $description);

        header("Content-Type: text/xml; charset=cp1251");
        echo html_entity_decode($xml->asXML(), ENT_COMPAT, '
windows-1251');
    }


    private function _errorCheckResponse($e)
    {
        $this->_generateCheckResponse(self::_codePaymentCannotBeProcessed, $e->getMessage());
    }

    private function _errorPayResponse($e)
    {
        $this->_generatePayResponse(self::_codePaymentCannotBeProcessed, $e->getMessage());
    }

    private function _errorCancelResponse($e)
    {
        $this->_generateCancelResponse(self::_codePaymentCannotBeProcessed, $e->getMessage());
    }
}

$handler = new VirtualCurrencyProtocolImplementation();
$handler->processRequest();
Онлайн: 1
Реклама