Class PHP Steam

De Wiki levelKro

Steam offre un API mais peu de documentation, voici des codes pour vous aider à inclure Steam dans votre site.

Pré-requis

  • Clé d'accès à l'API de Steam.
  • PHP 5.4+ avec cURL

Commandes

  • userPublic(a)
    • a : Le SteamID ou le Username de l'utilisateur Steam
  • userDetails(a,b)
    • a : Le ApiKey d'accès à Steam
    • b : Le SteamID de l'utilisateur Steam
  • userGames(a,b)
    • a : Le ApiKey d'accès à Steam
    • b : Le SteamID de l'utilisateur Steam
  • userBans(a,b)
    • a : Le ApiKey d'accès à Steam
    • b : Le SteamID de l'utilisateur Steam
  • marketPages(a,b)
    • a : Valeur de départ de la liste, affiche les 100 éléments suivant
    • b : (true) Retourne le nombre de page à consulter, utiliser 0 comme valeur pour a (optionnel, false par défaut)
  • marketItem(a)
    • a : Url complet vers la page du produit dans le marché Steam
  • group(a) : Retourne les détails d'un groupe Steam
    • a : Le GroupID ou le Non court du groupe Steam
  • loginUrl(a,b) : Obtenir le lien de connexion avec Steam
    • a : URL complet de retourne une fois connecté. (optionnel, retourne la page courante)
    • b : Utiliser & (true) au lieu de & dans le lien (optionnel, true par défaut)
  • loginValidate() : Valider la session de l'utilisateur (à utiliser sur la page de retour)
  • storeList() : Retourne la liste des produits disponible dans la boutique Steam (non disponible)
  • storeItem(a,b) : Retourne les détails d'un produit
    • a : Le AppID du produit
    • b : 1 pour un produit seul (video,dlc,apps,games,demo,...) ou 2 pour un package (pas un bundle) (optionnel, 1 par défaut)

Codes de la Class PHP

Enregistrer ce code dans un document comme Steam.Class.php.

<?php
 /*
  * (c) Copyright Mathieu Légaré (levelkro@yahoo.ca)
  * 2013-2019
  */
class SteamLVK {
 /* Variables */
 const STEAM_LOGIN = 'https://steamcommunity.com/openid';
 const STEAM_OPENID = 'http://specs.openid.net/auth/2.0';
 const STEAM_COMMUNITY = 'https://steamcommunity.com';
 const STEAM_API = 'http://api.steampowered.com';
 const STEAM_STORE = 'https://store.steampowered.com';
 const STEAM_MARKET = 'https://steamcommunity.com/market';
 const STEAM_CDN = 'https://steamcdn-a.akamaihd.net';

 /*
	Tools Functions
 */
 function=nameVAC($id){
  switch($id){
   case '0':
    return "En règle";
    break;
   case '1':
    return "Suspendu";
    break;
   default:
    return "Non déterminé";
  }
 }
 function=nameTrade($id)
  switch($id){
   case 'None':
    return "En règle";
    break;
   case 'Probation':
    return "Limité";
    break;
   default:
    return "Non déterminé";
  }	
 }
 function=nameVisibility($id){
  switch($id){
   case '1':
    return "Privé";
    break;
   case '2':
   case '3':
    return "Public";
    break;
   default:
    return "Non déterminé";
  }			
 }
 function OpenUrl($url){
  $ch = curl_init();
  curl_setopt($ch,CURLOPT_URL,$url);
  curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch,CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.3) Gecko/20060426 Firefox/1.5.0.3");
  curl_setopt($ch,CURLOPT_TIMEOUT,1000);
  $result = curl_exec($ch);
  return $result; 
  curl_close($ch);
 }	

 /* Steam Community */
 function group($id){
  $values = self::OpenUrl(self::STEAM_COMMUNITY."/groups/".$id."/memberslistxml/?xml=1");
  try{
   $values = (array) simplexml_load_string($values);
   $values['groupDetails'] = (array) $values['groupDetails'];				
   $values['groupDetails']['groupName'] = (string) $values['groupDetails']['groupName'];
   $values['groupDetails']['groupURL'] = (string) $values['groupDetails']['groupURL'];
   $values['groupDetails']['headline'] = (string) $values['groupDetails']['headline'];
   $values['groupDetails']['summary'] = (string) $values['groupDetails']['summary'];
   $values['groupDetails']['avatarIcon'] = (string) $values['groupDetails']['avatarIcon'];
   $values['groupDetails']['avatarMedium'] = (string) $values['groupDetails']['avatarMedium'];
   $values['groupDetails']['avatarFull'] = (string) $values['groupDetails']['avatarFull'];
   $values['members'] = (array) $values['members'];
   return $values;
  } catch (Exception $e) {
   return false;
  } 		
 }	
 function userPublic($id){
  $values = self::OpenUrl(self::STEAM_COMMUNITY."/id/".$id."/?xml=1");
  try{
   $values = (array) simplexml_load_string($values);
   $values['steamID'] = (string) $values['steamID'];
   $values['stateMessage'] = (string) $values['stateMessage'];
   $values['avatarIcon'] = (string) $values['avatarIcon'];
   $values['avatarMedium'] = (string) $values['avatarMedium'];
   $values['avatarFull'] = (string) $values['avatarFull'];
   $values['customURL'] = (string) $values['customURL'];
   $values['steamRating'] = (string) $values['steamRating'];
   $values['headline'] = (string) $values['headline'];
   $values['location'] = (string) $values['location'];
   $values['realname'] = (string) $values['realname'];
   $values['summary'] = (string) $values['summary'];
   $values['mostPlayedGames'] = (array) $values['mostPlayedGames'];
   $values['mostPlayedGames'] = (array) $values['mostPlayedGames']['mostPlayedGame'];
   $values['groups'] = (array) $values['groups'];
   $values['groups'] = (array) $values['groups']['group'];
   return $values;
  } catch (Exception $e) {
   return false;
  } 		
 }	
 function=userDetails($apikey,$value){
  $result=self::OpenUrl(self::STEAM_API."/ISteamUser/GetPlayerSummaries/v2/?key=".$apikey."&steamids=".$value."&format=json");
  $pro=json_decode($result);
  return (array) $pro->response->players[0];
 }	  
 function=userGames($apikey,$steamID){
  $json = self::OpenUrl(self::STEAM_API."/IPlayerService/GetOwnedGames/v1/?key=".$apikey."&steamid=".$steamID."&format=json"); 
  $result = json_decode($json,true);	
  return $result['response']['games'];   
 }
 function=userBans($apikey,$steamID){
  $result = false;
  $json = self::OpenUrl(self::STEAM_API."/ISteamUser/GetPlayerBans/v1/?key=".$apikey."&steamids=".$steamID."&format=json");		
  $array = json_decode($json,true);
  return $array['players']['0'];
 }

 function marketPages($s=0,$l=false){
  $s=self::OpenUrl(self::STEAM_MARKET."/search/render/?query=&start=".$s."&count=100&norender=1");
  $n=(array) json_decode($s, true);
  if($l===true) $n['total_count'] 
  else return $n;
 }
 function marketItem($p){
  // Steam XML/JSon details not found, use the public page
  $source = self::OpenUrl($p);
  $htmlsrc=explode("<!-- main body -->",$source);	// The beginning
  $htmlsrc=explode("<div id=\"market_activity_section\">",$htmlsrc[1]); // The end of part of code
  $htmlsrc=$htmlsrc[0]; 
  $htmlsrc=str_replace("&"."#36;","",$htmlsrc);	   
  $htmlsrc=str_replace("\r","",$htmlsrc);
  $htmlsrc=str_replace("\t","",$htmlsrc);	
  $htmlsrc=str_replace("\n","",$htmlsrc);	
  $htmlsrc=str_replace(">","",$htmlsrc);
  $htmlsrc=str_replace("<div id=\"BG_bottom\"><div id=\"mainContents\"><div class=\"market_listing_nav_container\"><div class=\"market_listing_nav\">","<item>\r\n",$htmlsrc);	
  $htmlsrc=str_replace("<div style=\"clear: both;\"></div>","",$htmlsrc);
  $htmlsrc=preg_replace("/<\/a>/i","</a>\r\n", $htmlsrc);
  $htmlsrc=explode("<div id=\"largeiteminfo\">",$htmlsrc);
  $htmlsrc=$htmlsrc[0];
  $htmlsrc=str_replace("</div></div><div class=\"market_page_fullwidth market_listing_firstsection\"><div class=\"market_listing_iteminfo\"><div class=\"market_listing_largeimage\">","",$htmlsrc);
  $htmlsrc=preg_replace("/<a href=\"(.+)search(.+)=(.+)\">(.+)<\/a>/i","<catAppid>$3</catAppid>\r\n<catName>$4</catName>", $htmlsrc);
  $htmlsrc=preg_replace("/<a href=\"(.+)listing(.+)\">(.+)<\/a>/i","<itemUrl>$1listing$2</itemUrl>\r\n<itemName>$3</itemName>", $htmlsrc);
  $htmlsrc=preg_replace("/<img src=\"(.+)\" alt=\"\" \/><\/div>/i","<itemImage>$1</itemImage>", $htmlsrc);
  $htmlsrc=$htmlsrc."</item>";
  $htmlsrc="<?phpxml version=\"1.0\" encoding=\"UTF-8\"?>\r\n".$htmlsrc."";
  $htmlsrc=str_replace("&","&",$htmlsrc);
  try{
   $htmlsrc = simplexml_load_string($htmlsrc);
   $htmlsrc = (array) $htmlsrc;
  } catch (Exception $e) {
   $htmlsrc=array();
  } 
  $jsonAsrc=explode("var g_rgAppContextData = ",$source);
  $jsonAsrc=explode("var g_rgAssets",$jsonAsrc[1]);
  $jsonAsrc=explode("\"".$htmlsrc['catAppid']."\":",$jsonAsrc[0]);
  $jsonAsrc=explode("};",$jsonAsrc[1]);
  if(strpos($jsonAsrc[0],"},")){
   $jsonAsrc=explode("},",$jsonAsrc[0]);
   $jsonAsrc=explode(":{",$jsonAsrc[1]);
   $jsonAsrc=(array) json_decode("{".$jsonAsrc[1],true);
  }
  else{
   $jsonAsrc=(array) json_decode($jsonAsrc[0],true);
  }
  $jsonBsrc=explode("var g_rgAssets = ",$source);
  $jsonBsrc=explode("var g_rgListingInfo",$jsonBsrc[1]);
  $jsonBsrc=explode("\"".$htmlsrc['catAppid']."\":",$jsonBsrc[0]);
  $jsonBsrc=explode("};",$jsonBsrc[1]);
  $jsonBsrc=(array) json_decode($jsonBsrc[0],true);
  foreach($jsonBsrc as $jsonItemsrc){
   $jsonBsrc=$jsonItemsrc;
  }			
  $o=1;
  foreach($jsonBsrc as $jsonItemsrc){
   if($o==1){
    $jsonItem=$jsonItemsrc;
    $o++;
   }
  }
  $jsonItemDesc="";
  foreach($jsonItem['descriptions'] as $jsonDescsrc){
   $jsonItemDesc.=$jsonDescsrc['value']."<br/>";
  }			
  $jsonItem['descriptions']=$jsonItemDesc;
  $output=array();
  $output['base']=$htmlsrc;
  $output['parent']=$jsonAsrc;
  $output['item']=$jsonItem;
  return $output;
 }
 public static function loginUrl($returnTo=false, $useAmp=true) {
  $returnTo = (!$returnTo) ? (!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] : $returnTo;
  $params = array('openid.ns'=>self::STEAM_OPENID,'openid.mode'=>'checkid_setup','openid.return_to'=> $returnTo,'openid.realm'=>(!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'],'openid.identity'=>self::STEAM_OPENID.'/identifier_select','openid.claimed_id'=>self::STEAM_OPENID.'/identifier_select');
  $sep = ($useAmp) ? '&' : '&';
  return self::STEAM_LOGIN . '?' . http_build_query($params, '', $sep);
 }
 public static function loginValidate() {
  $params = array('openid.assoc_handle'=>$_GET['openid_assoc_handle'],'openid.signed'=>$_GET['openid_signed'],'openid.sig'=>$_GET['openid_sig'],'openid.ns'=>self::STEAM_OPENID);
  $signed = explode(',', $_GET['openid_signed']);
  foreach($signed as $item) {
   $val = $_GET['openid_' . str_replace('.', '_', $item)];
   $params['openid.' . $item] = get_magic_quotes_gpc() ? stripslashes($val) : $val; 
  }
  $params['openid.mode'] = 'check_authentication';
  $data =  http_build_query($params);
  $context = stream_context_create(array('http' => array('method'=>'POST','header'=>"Accept-language: en\r\nContent-type: application/x-www-form-urlencoded\r\nContent-Length: ".strlen($data)."\r\n",'content'=>$data)));
  $result = file_get_contents(self::STEAM_LOGIN."/login", false, $context);
  preg_match("#^".self::STEAM_LOGIN."/id/([0-9]{17,25})#", $_GET['openid_claimed_id'], $matches);
  $steamid64 = is_numeric($matches[1]) ? $matches[1] : 0;
  return preg_match("#is_valid\s*:\s*true#i", $result) == 1 ? $steamid64 : false;
 }
}