<?php

namespace App\Services;

use Illuminate\Support\Facades\Log;

class RealnameAuthService {
    protected $url = 'https://api.srccwl.com/real_name/auth';
    
    const IDENTIFY_BIZ_SECRET = '0iBDmXSj8porIboyqISWAcRtS1GzD33GLX17abFdIO2fzjhxNRrSHWJtIVdC';
    

    public function check($gameId, $realName, $idCard, $uid, $eq = '')
    { 
        $data = array(
            'id_num' => $idCard,
            'real_name' => $realName,
            'api_token' => self::IDENTIFY_BIZ_SECRET,
            'device_id' => $eq,
            'game_id' => $gameId,
            'user_ip' => $eq,
            'account' => $uid
        );
        
        $ret = $this->http_requst($this->url, $data, 'post', array('Accept:application/json'));
//         Log::info("real name Auth:" . $ret, $data);
        $ret = json_decode($ret, true);
        
        if (isset($ret['error']) && $ret['error'] == 0) {
            if (!empty($ret['data']['is_valid']) && $ret['data']['is_valid'] > 0) {
                return array(true, "");
            } else {
                Log::info("real name Auth:" . $ret['message'], $data);
                return array(false, $ret['message']);
            }
        } else {
            $msg = isset($ret['message']) ? $ret['message'] : '网络繁忙，请重试';
            return array(false, $msg);
        }
    }
    
    private function http_requst($url, $params=array(), $method="GET", $header = array())
    {
        $ch = curl_init();
        if (!empty($params)) {
            if (strtoupper($method) == "GET") {
                $url = $url . "?" . http_build_query($params);
            }else {
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
            }
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if ($header) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        $response = curl_exec($ch);
        //                var_dump($response);
        if (curl_errno($ch)) {
            return false;
        }
        curl_close($ch);
        return $response;
    }
    
 
}