<?php

class XBill {

    const USER = 'silawar';
    const KEY = 'hmONCD8TEa6SUeRd';
    const SID = '22342';
    const API1 = 'http://api.x-bill.org/';
    const API2 = 'http://api.x-bill.ru/';

    # Инициализации платежа

    public static function mk_create_pay($phone, $cost, $desc, $answer = "", $arr = array()) {
        $phone = preg_replace('/[^0-9]/', '', $phone);
        $cost = (float) str_replace(",", ".", $cost);
        $desc = $desc;
        $answer = $answer;
        $var = "";
        if (isset($arr)) {
            $keys = array_keys($arr);
            for ($i = 0; $i < count($keys); $i++) {
                $var .= "&{$keys[$i]}=" . $arr[$keys[$i]];
            }
        }
        $post = "phone=".$phone."&cost=".$cost."&desc=".$desc."&answer=".$answer."&sign=" . self::mk_create_sign($phone) . "&login=mland&sid=199".$var;

        $result = self::mk_send_data($post, self::API1 . "payment.php");
        if ($result == 'error') {
            $result = self::mk_send_data($post, self::API2 . "payment.php");
        }
        if ($result == 'error') {
            return "0";
        } else {
            $result = self::mk_parse_result($result);
            return $result;
        }
    }

    # Узнаем статус платежа по ID

    public static function mk_get_status($id) {
        $post = "id={$id}&sign=" . self::mk_create_sign() . "&login={" . self::USER . "}&sid={" . self::SID . "}";
        $result = self::mk_send_data($post, self::API1 . "status.php");
        if ($result == 'error') {
            $result = self::mk_send_data($post, self::API2 . "status.php");
        }
        if ($result == 'error') {
            return "0";
        } else {
            $result = self::mk_parse_result($result);
            return $result;
        }
    }

    # Запрашиваем баланс

    public static function mk_get_balance($password = "", $sid = "", $dade_in = "", $date_to = "") {
        $post = "login={" . self::USER . "}&sid={$sid}&pass=" . md5($password) . "&date_in={$dade_in}&date_to={$date_to}";
        $result = self::mk_send_data($post, self::API1 . "balance.php");
        if ($result == 'error') {
            $result = self::mk_send_data($post, self::API2 . "balance.php");
        }
        if ($result == 'error') {
            return "0";
        } else {
            $result = self::mk_parse_result($result);
            return $result;
        }
    }

    # Формируем подпись

    public static function mk_create_sign($phone = "") {
        return md5(self::USER . self::KEY . self::SID . $phone);
    }

    # Разбираем ответ от скрипта

    public static function mk_parse_result($result) {
        $XML = trim($result);
        $returnVal = $XML;
        $emptyTag = '<(.*)/>';
        $fullTag = '<\\1></\\1>';
        $XML = preg_replace("|$emptyTag|", $fullTag, $XML);
        $matches = array();
        if (preg_match_all('|<(.*)>(.*)</\\1>|Ums', trim($XML), $matches)) {
            if (count($matches[1]) > 0)
                $returnVal = array();
            foreach ($matches[1] as $index => $outerXML) {
                $attribute = $outerXML;
                $value = self::mk_parse_result($matches[2][$index]);
                if (!isset($returnVal[$attribute]))
                    $returnVal[$attribute] = array();
                $returnVal[$attribute][] = $value;
            }
        }
        if (is_array($returnVal))
            foreach ($returnVal as $key => $value) {
                if (is_array($value) && count($value) == 1 && key($value) === 0) {
                    $returnVal[$key] = $returnVal[$key][0];
                }
            }
        return $returnVal;
    }

    # Отпраляем POST запрос

    public static function mk_send_data($post, $url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FAILONERROR, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); # Разрешить переадресацию
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 4); # Таймаут не менять! 
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

        $result = curl_exec($ch);
        $status = curl_errno($ch);

        curl_close($ch);
        if ($status == 0 && !empty($result)) {
            return $result;
        } else {
            return "error";
        }
    }

}

?>