<?php

declare (strict_types=1);
namespace library\lib;
// +----------------------------------------------------------------------
// | [ WE CAN DO IT MORE SIMPLE  ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2020 rights reserved.
// +----------------------------------------------------------------------
// | Author: TABLE ME
// +----------------------------------------------------------------------
// | Date: 2020-11-10 13:21
// +----------------------------------------------------------------------

class weixina {

    //AppID(应用ID)
    private $appid = '';

    //AppSecret(应用密钥)
    private $secret = "";

    //授权回调URL
    private $redirect_uri = '';

    //返回类型,请填写code
    private  $response_type = 'code';

    /**
     * 应用授权作用域,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且,即使在未关注的情况下,只要用户授权,也能获取其信息
     */
    private  $scope ='snsapi_userinfo';

    private  $state = 'STATE';
    
    public $error="";


    /**
     * 构造函数
     */
    public function __construct($info = null) {
        if(empty($info)) $info = config('weixin');
        $this->appid = $info['APPID'];
        $this->secret = $info['APPSECRET'];
        $this->redirect_uri = $info['REDIRECT'] ;// config() .'api/weixin/result';
    }
    
    /**
     * 新版授权登录
     * @param type $jsCode
     */
    public function auth_code2Session($jsCode){
        $oauth_url = "https://api.weixin.qq.com/sns/jscode2session?"
            ."appid=".$this->appid
            ."&secret=".$this->secret
            ."&js_code=".$jsCode
            ."&grant_type=authorization_code";
        $data = $this->Get($oauth_url);
        if(empty($data)){
            return false;
        }
        return json_decode($data,true);
    }
    /**
     * 新版获取微信手机号
     * @param type $jsCode
     */
    public function getPhoneNumber($jsCode){
        $accessData = $this->getAccessToken();
        if(empty($accessData) || empty($accessData["access_token"])){
            return false;
        }
        $access_token = $accessData["access_token"];
        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?"
            ."access_token=".$access_token;
        $postData = json_encode(array(
            "code"=>$jsCode
        ));
        $data = $this->Post($postData,$url);
        $res = $data;
        if(empty($data)){
            return false;
        }
        $data = json_decode($data,true);
        if(empty($data) || empty($data["phone_info"]) || empty($data["phone_info"]["purePhoneNumber"])){
            $this->error="返回参数名称错误".$res;
            return false;
        }
        return $data["phone_info"];
    }
    
    
    /**
     * 获取小程序码
     * @param type $path
     * @param type $width
     */
    public function getQRCode($path,$width){
        
    }
    
    /**
     * 获取不限制的小程序码
     * @param type $page 页面
     * @param type $scene 携带参数
     * @param type $width 宽度
     * @return bool
     */
    public function getUnlimitedQRCode($page,$scene,$width=430){
        $accessData = $this->getAccessToken();
        if(empty($accessData) || empty($accessData["access_token"])){
            return false;
        }
        $access_token = $accessData["access_token"];
        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?"
            ."access_token=".$access_token;
        $postData = json_encode(array(
            "page"=>$page,
            "scene"=>$scene,
            "width"=>$width,//默认430
//            "auto_color"=>true,//自动配置线条颜色
            "is_hyaline" => false,//是否透明底色
        ));
        $data = $this->Post($postData,$url,1);
        $res = $data;
        if(empty($data)){
            return false;
        }
        if(empty($data) || empty($data["contentType"]) || empty($data["buffer"])){
            $this->error="返回参数错误".$res;
            return false;
        }
        return $data;
        
        
        
//        return $data["phone_info"];
        
        
        
        
        
        
        
        
//        $key = md5($this->appid.$parms['path'].$parms['params']);
//        $imgsrc = Factory::cache('default')->hget($this->pathAndWxacodeunlimitKey, $key);
//        if(!empty($imgsrc)){
//            return ResultWrapper::success($imgsrc);
//        }
//
//        $apiUrl = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access_token;
//
//        $postData = [
//            'scene'      => $parms['params'],
//            'page'       => $parms['path'],
//            'width'      => 430,
//            'auto_color' => true,
//        ];
//
//        $reponse =  request($apiUrl, json_encode($postData));
//        if($reponse['httpcode'] != 200){
//            return ResultWrapper::fail('请求外部系统接口报错', ErrorCode::$apiNotResult);
//        }else{
//            if(!is_object($reponse['content'])){
//                $base64   = 'data:'.$reponse['content_type'].';base64,'.base64_encode($reponse['content']);
//                $upload = Factory::baseImg();
//                $upload->move($base64);
//                $imgsrc = $upload->getSaveName();
//                Factory::cache('default')->hset($this->pathAndWxacodeunlimitKey, $key, $imgsrc);
//                return ResultWrapper::success($imgsrc);
//            }
//            $reponseData = json_decode($reponse['content'], true);
//            if( isset($reponseData['errcode']) ){
//                return ResultWrapper::fail($reponseData['errmsg'], $reponseData['errcode']);
//            }
//        }
    }
    
    /**
     * 获取小程序二维码
     * @param type $path
     * @param type $width
     */
    public function createQRCode($path,$width){
        
    }
    
    /**
     * 新版获取接口调用凭证
     * @return type
     */
    public function getAccessToken(){
        $url = "https://api.weixin.qq.com/cgi-bin/token?"
            ."appid=".$this->appid
            ."&secret=".$this->secret
            ."&grant_type=client_credential";
        $data = $this->Get($url);
        if(empty($data)){
            return false;
        }
        return json_decode($data,true);
    }
    
    
   
    
    
    
    
    
    
    
    
    
    

    /**
     * 手机授权登录
     * @param string $state 状态值
     * @param string $scope 作用域
     */
    public function oauth($state = '', $scope = ''){
        if($state == '') $state = $this->state;
        if($scope == '') $scope = $this->scope;
        $oauth_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->appid
            ."&redirect_uri=".$this->redirect_uri
            ."&response_type=".$this->response_type
            ."&scope=".$scope.
            "&state=".$state."#wechat_redirect";
       return redirect($oauth_url);
    }


    /**
     * 处理事情
     */
    public function oauth_reuslt($code){
        $oauth_reuslt_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->appid
            ."&secret=".$this->secret
            ."&code=".$code
            ."&grant_type=authorization_code";
        $data = $this->Post("",$oauth_reuslt_url);
        return json_decode($data,true);
    }

    /**
     * 拉取用户信息(需scope为 snsapi_userinfo)
     *
     * openid	用户的唯一标识
    nickname	用户昵称
    sex	用户的性别,值为1时是男性,值为2时是女性,值为0时是未知
    province	用户个人资料填写的省份
    city	普通用户个人资料填写的城市
    country	国家,如中国为CN
    headimgurl	用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空。若用户更换头像,原有头像URL将失效。
    privilege	用户特权信息,json 数组,如微信沃卡用户为(chinaunicom)
    unionid	只有在用户将公众号绑定到微信开放平台帐号后,才会出现该字段。详见:获取用户个人信息(UnionID机制)
     */
    public function userinfo($access_token){
        $userinfo_url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$this->appid."&lang=zh_CN";
        $data = $this->Post("",$userinfo_url);
        return json_decode($data,true);
    }

    /**
     * 检验授权凭证(access_token)是否有效
     * @param $access_token
     */
    public function auth($access_token,$openid){
        $r = false;
        $auth_url = "https://api.weixin.qq.com/sns/auth?access_token=&openid=".$openid;
        $data = $this->Post("",$auth_url);
        $d = json_decode($data,true);
        if($d['errcode'] == 0){
            $r = true;
        }
        return $r;
    }
    /**
     * 写入值
     * @param $curlPost
     * @param $url
     * @return mixed
     */
    function Post($curlPost, $url, $isres=0) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
//        curl_setopt($curl, CURLOPT_NOBODY, true);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        $return_str = curl_exec($curl);
        $err = "";
        if(empty($return_str)){
            $err =  "系统错误:".curl_error($curl);
        }
        
        $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        $content_type = curl_getinfo($curl, CURLINFO_CONTENT_TYPE);

        curl_close($curl);
        if(!empty($err)){
            $this->error = $err;
            return false;
        }
        if($isres==1){
            if($httpcode!=200){
                return false;
            }
            return [
                "contentType"=>$content_type,
                "buffer"=>$return_str
            ];
        }
        return $return_str;
    }
    
    /**
     * 写入值
     * @param $url
     * @return mixed
     */
    function Get($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $return_str = curl_exec($curl);
        $err = "";
        if(empty($return_str)){
            $err =  "系统错误:".curl_error($curl);
        }
        curl_close($curl);
        if(!empty($err)){
            $this->error = $err;
            return false;
        }
        return $return_str;
    }



    /**
     * 写入日志
     * @param type $word
     * @param type $name
     */
    function log_result($word, $name) {
        $fp = fopen($name . "_log.txt", "a");
        flock($fp, LOCK_EX);
        fwrite($fp, $word . "\n");
        flock($fp, LOCK_UN);
        fclose($fp);
    }
}