Steam接口封装

本文档介绍了如何在PHP中封装和使用Steam平台的Web API,包括关键接口的调用和应用实例,适用于需要接入Steam平台的开发者。
摘要由CSDN通过智能技术生成

之前有项目接入steam平台,这儿整理了常用到的WebApi封装,可以参考

usage

     $steam = new SteamUtils([
     'appid' => $this->currentConfig['appid'],
     'appkey' => $this->currentConfig['appkey'],
     'steamid' => $this->steamid,
     'ticket' => $this->params['encrypted_loginkey'] ? :Cache::redis_get('_STEAM_LOGIN_'.$this->steamid),
     ]);
     $ret = $steam->ISteamUserAuth->AuthenticateUserTicket();
     if ( 0!==strcasecmp($ret['response']['params']['result'], 'OK') ){
   
         // TODO u business
     }
/**
 * SteamUtils
 * present by YCZ
 * Author: Nomandia
 * Date: 2020/6/19 13:53
 * @see https://partner.steamgames.com/doc/features/microtransactions/implementation#error_codes 错误代码
 *
 * @property SteamUtils_IBroadcastService IBroadcastService
 * @property SteamUtils_IGameInventory IGameInventory
 * @property SteamUtils_ISteam ISteam
 * @property SteamUtils_ISteamApps ISteamApps
 * @property SteamUtils_ISteamCommunity ISteamCommunity
 * @property SteamUtils_ISteamEconomy ISteamEconomy
 * @property SteamUtils_ISteamGameServerStats ISteamGameServerStats
 * @property SteamUtils_ISteamMicroTxn ISteamMicroTxn
 * @property SteamUtils_ISteamNews ISteamNews
 * @property SteamUtils_ISteamUser ISteamUser
 * @property SteamUtils_ISteamUserAuth ISteamUserAuth
 * @property SteamUtils_ISteamUserStats ISteamUserStats
 * @property SteamUtils_ISteamWebAPIUtil ISteamWebAPIUtil
 *
 * @usage
 *     $steam = new SteamUtils([
 *        'appid' => $this->currentConfig['appid'],
 *        'appkey' => $this->currentConfig['appkey'],
 *        'steamid' => $this->steamid,
 *        'ticket' => $this->params['encrypted_loginkey'] ? :Cache::redis_get('_STEAM_LOGIN_'.$this->steamid),
 *     ]);
 *     $ret = $steam->ISteamUserAuth->AuthenticateUserTicket();
 *     if ( 0!==strcasecmp($ret['response']['params']['result'], 'OK') ){
 *         // TODO u business
 *     }
 */
class SteamUtils
{
   
    /**
     * @var string appid
     */
    public $appid;

    /**
     * @var string appkey
     */
    public $appkey;

    /**
     * @var string ticket
     */
    public $ticket;

    /**
     * @var string gameid
     */
    public $gameid;

    /**
     * @var string steamid
     */
    public $steamid;

    /**
     * @var bool use_ssl 开启SSL(https)
     */
    public $use_ssl = false;

    /**
     * @var bool return_json 返回JSON数据,否则返回文本
     */
    public $return_json = true;

    /**
     * @var string language 语言代码
     * @see https://baike.baidu.com/item/ISO%20639-1/8292914?fr=aladdin
     */
    public $language = 'zh';

    /**
     * @var string currency Steam支持的币种(默认软妹币,单位分即100的整数倍)
     * @see https://partner.steamgames.com/doc/store/pricing/currencies
     */
    public $currency = 'CNY';

    /**
     * @var bool sandbox 是否开启沙箱(MicroTxn用到,仅改变URL)
     */
    public $sandbox = false;

    /**
     * Author: Great Nomandia
     * Created At 2020/6/19 14:36
     */
    function __construct()
    {
   
        if (is_array($func = func_get_arg(0))) {
   
            $this->appid = $func['appid'];
            $this->appkey = $func['appkey'];
            $this->steamid = $func['steamid'];
            $this->ticket = $func['ticket'];
        } else if (func_num_args() > 3) {
   
            $this->appid = func_get_arg(0);
            $this->appkey = func_get_arg(1);
            $this->steamid = func_get_arg(2);
            $this->ticket = func_get_arg(3);
        }
    }

    function __destruct()
    {
   
        static::$implements = null;
        $this->appid = $this->appkey = $this->steamid = $this->ticket = null;
    }

    /*********** ALIAS *************/

    protected static $implements = [];

    /**
     * @param string $name
     * @return mixed
     * @throws SteamException
     * Author: Great Nomandia
     * Created At 2020/6/19 15:16
     */
    function __get($name)
    {
   
        if (in_array($name, static::$implements)) {
   
            return static::$implements[$name];
        }
        $clazz = 'SteamUtils_' . $name; // 增加一个前缀
        if (class_exists($clazz) || !($clazz instanceof SteamUtils_ISteam)) {
   
            /** @var SteamUtils_ISteam $implements */
            static::$implements[$name] = new $clazz();
            return static::$implements[$name]->bind($this);
        }
        throw new SteamException('Interface[' . $name . '] not exists', 502);
    }

    /*********** CURL TOOLS *************/

    /**
     * @param string $url
     * @param mixed $params
     * @param bool $json
     * @param string $cookie
     * @param bool $use_ssl
     * @return string
     * Author: Great Nomandia
     * Created At 2020/6/19 14:06
     */
    static function get($url, $params = null, $json = true, $cookie = '', $use_ssl = false)
    {
   
        return $json ?
            static::requestJson($url, $params, 'GET', $cookie, $use_ssl) :
            static::request($url, $params, 'GET', $cookie, $use_ssl);
    }

    /**
     * @param string $url
     * @param mixed $params
     * @param bool $json
     * @param string $cookie
     * @param bool $use_ssl
     * @return string
     * Author: Great Nomandia
     * Created At 2020/6/19 14:06
     */
    static function post($url, $params = null, $json = true, $cookie = '', $use_ssl = false)
    {
   
        return $json ?
            static::requestJson($url, $params, 'POST', $cookie, $use_ssl) :
            static::request($url, $params, 'POST', $cookie, $use_ssl);
    }

    /**
     * @var int _curl_port 默认请求端口
     */
    static $_curl_port = 0;

    /**
     * @var array _curl_headers 附加的Header数据
     */
    static $_curl_headers = [];

    /**
     * @var int _curl_connect_timeout  连接超时时间
     */
    static $_curl_connect_timeout = 2;

    /**
     * @var int _curl_timeout 执行超时时间
     */
    static $_curl_timeout = 5;

    /**
     * @var mixed fetch_result
     */
    static $fetch_result;

    /**
     * @var mixed fetch_error
     */
    static $fetch_error;

    /**
     * @param string $url
     * @param mixed $params
     * @param string $method
     * @param string $cookie
     * @param bool $use_ssl
     * @return mixed
     * Author: Great Nomandia
     * Created At 2020/6/19 14:47
     */
    static function requestJson($url, $params = null, $method = 'GET', $cookie = '', $use_ssl = false)
    {
   
        $ret = static::request($url, $params, $method, $cookie, $use_ssl);
        return json_decode($ret, 1);
    }

    /**
     * @param string $url
     * @param mixed $params
     * @param string $method
     * @param string $cookie
     * @param bool $use_ssl
     * @return string
     * Author: Great Nomandia
     * Created At 2020/6/19 14:06
     */
    static function request($url, $params = null, $method = 'GET', $cookie = '', $use_ssl = false)
    {
   
        $ch = curl_init();
        if ('GET' == strtoupper($method)) {
   
            $param_str = '';
//            默认范文为ipv4
            curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);

            if (is_array($params)) {
   
                $param_str = http_build_query($params);
            } else if (is_string($params) && strlen($params) > 0) {
   
                $param_str = $params;
            }
            $url .= $param_str ? '?' . trim($param_str) : '';
            curl_setopt($ch, CURLOPT_URL, $url);
        } else {
   
            curl_setopt_array($ch, array(
                CURLOPT_URL => $url,
                CURLOPT_POST => 1,
                CURLOPT_POSTFIELDS => $params,
            ));
        }

        curl_setopt_array($ch, array(
            CURLOPT_HEADER => false,
            CURLOPT_RETURNTRANSFER => true, // 成功时返回取到的结果(如HTML或json)
            CURLOPT_CONNECTTIMEOUT => self::$_curl_connect_timeout,
            CURLOPT_TIMEOUT => self::$_curl_timeout,
            CURLOPT_HTTPHEADER => array(
                'Expect:',
            ),
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
        ));

        if (!empty(self::$_curl_headers)) {
   
            curl_setopt_array($ch, array(
                CURLOPT_HTTPHEADER => self::$_curl_headers,
            ));
        }

        // disable 100-continue
        if (!empty($cookie)) {
   
            if (is_array($cookie)) {
   
                $cs = [];
                foreach ($cookie as $k => $v) {
   
                    $cs[] = $k . '=' . $v;
                }
                $cookie = join('; ', $cs);
            }
            curl_setopt($ch, CURLOPT_COOKIE, $cookie);
        }
        // 关闭SSL设置,通常这样就可以直接访问HTTPS地址了
        if (!$use_ssl) {
   
            curl_setopt_array($ch, array(
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_SSL_VERIFYHOST => false,
            ));
        }
        if (self::$_curl_port) {
   
            curl_setopt($ch, CURLOPT_PORT, intval(self::$_curl_port));
        }
        self::$fetch_result = curl_exec($ch);
        self::$fetch_error = curl_error($ch);
        curl_close($ch);

        // 需要恢复的配置
        self::$_curl_port = 0;

        return self::$fetch_result ?: self::$fetch_error;
    }
}

/*********** EXCEPTION *************/
class SteamException extends Exception
{
   
}

/*********** SUPPORT INTERFACE *************/
abstract class SteamUtils_ISteam
{
   
    /**
     * @var SteamUtils steam
     */
    protected static $steam;

    function bind(&$steam)
    {
   
        static::$steam = $steam;
        return $this;
    }

    /**
     * @param string $url
     * @param array $params
     * @param bool $no_merge 不增加默认参数表
     * @return string|array|mixed
     * Author: Great Nomandia
     * Created At 2020/6/19 15:42
     */
    function post($url, $params = [], $no_merge = false)
    {
   
        return (static::$steam)::post($url, $no_merge ? $params : array_merge([
            'key' => static::$steam->appkey,
            'appid' => static::$steam->appid,
            'steamid' => static::$steam->steamid,
        ], array_filter($params)), static::$steam->return_json);
    }

    /**
     * @param string $url
     * @param array $params
     * @param bool $no_merge
     * @return string|array|mixed
     * Author: Great Nomandia
     * Created At 2020/6/19 17:11
     */
    function get
Spring Boot是一个流行的Java框架,它简化了构建生产级应用程序的过程。如果你想利用Spring Boot实现Steam API接口的能力,你可以按照以下步骤操作: 1. 添加依赖:首先,你需要在你的`pom.xml`文件中添加对相关库的支持,比如`RestTemplate`用于HTTP请求,以及处理JSON数据的`Jackson`或`Gson`。 ```xml <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- 如果需要json解析 --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> </dependencies> ``` 2. 创建服务类:创建一个`@Service`或`@RestController`类,这里你会有一个方法用于处理Steam API的请求。例如,假设你想获取用户信息,可以这样设计: ```java import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; @Service public class SteamApiService { @Value("${STEAM_API_KEY}") private String apiKey; public User getUserInfo(String userId) { RestTemplate restTemplate = new RestTemplate(); String apiUrl = "https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=" + apiKey + "&steamids=" + userId; ResponseEntity<String> response = restTemplate.getForEntity(apiUrl, String.class); return parseResponse(response.getBody()); } // 对返回的JSON进行解析,这里省略解析部分 } ``` 注意替换`STEAM_API_KEY`为你从Steam获取的实际API密钥,并确保URL格式正确。 3. 注册配置:如果你的API密钥作为环境变量存储,可以在`application.properties`或`application.yml`中注册: ```properties STEAM_API_KEY=your_steam_api_key_here ``` 4. 调用服务:通过Controller或其他服务组件,你可以对外暴露这个接口供客户端调用。 ```java @RestController public class SteamApiController { @Autowired private SteamApiService steamApiService; @GetMapping("/users/{userId}") public ResponseEntity<User> getPlayerSummary(@PathVariable("userId") Long userId) { User user = steamApiService.getUserInfo(userId.toString()); return ResponseEntity.ok(user); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值