<?php
/**
 * 第三方接口
 * User: solu
 * Date: 2018/12/10
 * Time: 4:40 PM
 */

class ThirdApi {

    /**
     * 检测token有效性
     * @author solu
     * @param $userId
     * @param $accessToken
     * @return bool
     */
    public static function checkToken($userId, $accessToken) {
        $data = [
            'user_id' => $userId,
            'app_id' => MEE_APP_ID,
            'access_token' => $accessToken
        ];
        $api = URL_MEECHAT . 'auth/checkAccessToken';

        $resp = (new dwHttp())->post2($api, $data);
        $json = json_decode($resp, true);

        return $json['data']['valid'];
    }

    /**
     * 获取用户信息
     * @author solu
     * @param $userId
     * @param $accessToken
     * @return null|array
     */
    public static function getMeeUserInfo($userId, $accessToken) {
        $data = [
            'user_id' => $userId,
            'app_id' => MEE_APP_ID,
            'access_token' => $accessToken
        ];
        $api = URL_MEECHAT . 'auth/getUserInfo';

        $resp = (new dwHttp())->post2($api, $data);
        $json = json_decode($resp, true);
        if (!$json['result']) {
            return null;
        }

        return $json['data'];
    }

    /**
     * 获取授权页面地址
     * @author solu
     * @param $callbackURL
     * @return string
     */
    public static function getAuthUrl($callbackURL) {
        $ts = time();
        $params = [
            'callback' => $callbackURL,
            'app_id' => MEE_APP_ID,
            'ts' => $ts,
            'sign' => self::meeSign(MEE_APP_ID, MEE_APP_SECRET, $ts),
        ];

        return URL_MEECHAT . 'auth/login?' . http_build_query($params);
    }

    private static function meeSign($appId, $appSecret, $ts) {
        return md5(sprintf('%s_%s_%s', $appId, $appSecret, $ts));
    }
}