<?php

/**
 * 金立 accesstoken换取用户信息
 * @version
 *          1.0.0 Created at 2018-3-9. by --gwang
 * @author gwang (mail@wanggangzero.cn)
 * @copyright ? 2018-3-9, SJZ LoyalSoft Corporation & gwang. All rights reserved.
 */
include_once __DIR__ . '/../../../main.php';             # 导入game utils
include_once __DIR__ . '/../Mo/payResp.php';                # 导入通用返回值结构
include_once __DIR__ . '/../Mo/payRequest.php';          # 导入通用订单请求结构
require_once __DIR__ . '/config_for_gionee.php';         # 配置文件

use loyalsoft\CLog;
use loyalsoft\JsonUtil;
use loyalsoft\HttpUtil;

HttpUtil::PostOnly();                                                           # 要求客户端必须以post方式提交数据
#

function jinli_verify($content) {
    $cfg = config_for_gionee::Inst();                                           # 配置
    $verify_url = $cfg->ApiURL_verifySession;
    $apiKey = $cfg->appkey;                                                     # 替换成商户申请获取的APIKey
    $secretKey = $cfg->app_secret;                                              # 替换成商户申请获取的SecretKey
    $host = "id.gionee.com";
    $port = "443";
    $uri = "/account/verify.do";
    $method = "POST";

    $ts = time();
    $nonce = strtoupper(substr(uniqid(), 0, 8));

    $signature_str = $ts . "\n" . $nonce . "\n" . $method . "\n" . $uri . "\n" . $host . "\n" . $port . "\n" . "\n";

    $signature = base64_encode(hash_hmac('sha1', $signature_str, $secretKey, true));

    $Authorization = "MAC id=\"{$apiKey}\",ts=\"{$ts}\",nonce=\"{$nonce}\",mac=\"{$signature}\"";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $verify_url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: ' . $Authorization));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

CLog::info(HttpUtil::getQueryString());                                         # 日志


$json['status'] = 1;

//参数: playId,isGuest,access_token
$playId = trim($_REQUEST['playId']);
$isGuest = trim($_REQUEST['isGuest']);
$amigoToken = trim($_REQUEST['token']);
if ($isGuest == 'false') {
    //正式账号需要验证
    $result_json = jinli_verify($amigoToken);
    $result_arr = json_decode($result_json, 1);
    if (isset($result_arr['r'])) {
        $json['status'] = 0;
        die(payResp::err($result_arr['r'], $result_arr['wid']));
    }
    die(payResp::ok($result_arr));
}

die(payResp::ok($json));
