<?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 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 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);
    }


    /**
     * 获取access_token
     */
    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) {
        $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);
        curl_close($curl);
        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);
    }
}