@Mazafacer

Не работает авторизация через Steam что я делаю не так?

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

class Functions{

    public $db, $config;

    public function __construct($config){
        
        $this->config = $config;
        $this->db = new mysqli($config['db_host'], $config['db_user'], $config['db_pass'], $config['db_name']);
        if ($this->db->connect_error) {
            die("Couldn't connect to MySQL: ".$this->db->connect_error);
        }
        mysqli_query($this->db, "SET NAMES utf8");
    }
    public function getTemplate($name){
        $file = $_SERVER['DOCUMENT_ROOT']."/template/".$name.".tpl";
        if(!is_file($file)){
            return "Error! Template not found!";
        }else{
            $template = file_get_contents($file);
            preg_match_all('/{include file="(.*?)"}/is', $template, $matches);
            foreach($matches[1] as $value) {
                $template = str_replace('{include file="'.$value.'"}', $this->getTemplate(str_replace(".tpl", "", $value)), $template);
            }
            return $template;
        }
    }
public function getIndex($template, $replace = ['from' => [], 'to' => []]){
        $template = $this->getTemplate($template);
        $replace['from'][] = "{title}";
        $replace['to'][] = $this->config['site_title'];
        if($this->isLogged()){
            $user = $this->getUser();
            $replace['from'][] = "{authBlock}";
            $replace['to'][] = '<div class="userblock">
                <a href="/user" class="username">
                    <img src="'.$_SESSION['avatarfull'].'" alt="Аватар">
                    <span>'.$_SESSION['name'].'</span>
                </a>
                <div class="userblock-bottom">
                    <a href="#" class="purse">
                        Баланс:
                        <span>'.$user->money.' <small>p</small></span>
                    </a>
                    <span class="addmoney">
                    <form action="/pay" method="POST">
                        <input name="money" type="number" min="0" placeholder="Сумма" class="invoiceMoney">
                        <button class="button" type="submit">+</button>
                    </form>
                    </span>
                </div>
                <a href="/steam?logout" class="quit">x</a>
            </div>';
        }else{
            $replace['from'][] = "{authBlock}";
            $replace['to'][] = '<a href="/steam?login" class="authblock login hidden"></a>';
            $replace['from'][] = "{logoutBlock}";
            $replace['to'][] = "";
        }
        return str_replace($replace['from'], $replace['to'], $template);
    }




Файл steam.php


<?php
if(!isset($Functions)){
    die("Error! 404");
}

require $_SERVER['DOCUMENT_ROOT'].'/engine/openid.php';

if($Functions->isLogged()){
    if(isset($_GET['logout'])){
        session_destroy();
    }
    $Functions->redirect();
}else{
    try{
        $openid = new LightOpenID('http://'.$Functions->config['site_name']);
        if(!$openid->mode) {
            if(isset($_GET['login'])){
                $openid->identity = 'http://steamcommunity.com/openid';
                $Functions->redirect($openid->authUrl());
            }else{
                $Functions->redirect();
            }
        }elseif($openid->mode == 'cancel'){
            $Functions->redirect();
        }else{
            if($openid->validate()) {
                $id = $openid->identity;
                $ptn = "/^http:\/\/steamcommunity\.com\/openid\/id\/(7[0-9]{15,25}+)$/";
                preg_match($ptn, $id, $matches);

$json_object = file_get_contents("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=".$Functions->config['steamapi']."&steamids=".$matches[1]);
                if($json_object == false){
                    die($Functions->getIndex("steam_fail"));
                }else{
                    $json_decoded = json_decode($json_object);
                    $player = $json_decoded->response->players[0];
                    if(!empty($player)){
                        $getPlayer = $Functions->db->query("SELECT * FROM users WHERE steamid = '".$player->steamid."'");
                        if($getPlayer->num_rows == 0){
                            $Functions->db->query("INSERT INTO `users`(`steamid`, `name`, `avatar`, `money`, `created`, `status`) VALUES ('".$player->steamid."', '".$player->personaname."', '".$player->avatarfull."', '0', '".time()."', '1')");
                        }else{
                            $Functions->db->query("UPDATE users SET name = '".$Functions->getString($player->personaname)."', avatar = '".$player->avatarfull."' WHERE steamid = '".$player->steamid."'");
                            $_SESSION['name'] = $player->personaname;
                            $_SESSION['steamid'] = $player->steamid;
                            $_SESSION['avatarfull'] = $player->avatarfull;
                        }
                        $Functions->redirect();
                    }else{
                        die($Functions->getIndex("steam_fail"));
                    }
                }
            }else{
                $Functions->redirect();
            }
        }
    }catch(ErrorException $e){
        echo $e->getMessage();
    }
}

?>
  • Вопрос задан
  • 207 просмотров
Решения вопроса 1
EPIDEMIASH
@EPIDEMIASH
Человек швейцарский нож
Используйте библиотеку steam-auth

Ну и php будет таким примерно

require 'vendor/autoload.php';

$openid = new \EllisLab\OpenID\OpenID();
$openid->setReturnUrl('https://example.com/authenticate');
$openid->identity = 'https://steamcommunity.com/openid';
if ($openid->mode == 'cancel') {
    // Операция отменена пользователем
} elseif ($openid->mode) {
    if ($openid->validate()) {
        $id = str_replace('https://steamcommunity.com/openid/id/', '', $openid->identity);
        // Пользователь авторизован, можно использовать его id для дополнительной авторизации на Вашем сайте
    }
}
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 1
vabka
@vabka
Токсичный шарпист
нашел в интернете готовый код

Попробуй вместо готового кода почитать официальную документацию, тем более что код ужасно нечитабельный:
https://partner.steamgames.com/doc/webapi_overview...

И обрати внимание на один из первых пунктов:

Чтобы использовать OAuth, вам сначала нужно получить клиентский ID от Valve

Тоесть даже если код твой рабочий - он не будет работать, пока ты не получил client id от Valve

За дополнительной информацией обращайся ещё к стандарту:
RFC 6749 (oauth 2.0): https://www.ietf.org/rfc/rfc6749.txt
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы