<?php
namespace App\Services\user\Weixin\Weixin;
use App\Libraries\Http;

/**
 * Created by PhpStorm.
 * User: shixing
 * Date: 2018/9/12
 * Time: 10:48
 */
class Weixin
{
    private $appId;
    private $appSecret;
    public function __construct()
    {
        $config = config('weixin');
        $this->appId = $config['appid'];
        $this->appSecret = $config['secret'];
    }

    /**
     * 获取accessToken
     * @return mixed
     */
    public function getAccessToken()
    {
        $appid          = $this->appId;
        $appsecret      = $this->appSecret;
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";

        $output = $this->curl($url);
        $jsoninfo = json_decode($output, true);
        $accessToken = $jsoninfo["access_token"];
        return $accessToken;
    }

    /**
     * 发送请求
     * @param $url
     * @param null $data
     * @return mixed
     */
    public function curl($url,$data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
//        $error = curl_error($curl);
        return $output;

    }

 


    public function getCode()
    {
        header("content-type:text/html;charset=utf-8");
        $code = $_GET["code"];//预定义的 $_GET 变量用于收集来自 method="get" 的表单中的值。
        if (isset($_GET['code'])){//判断code是否存在
            $userinfo = getUserInfo($code);
            $xinxi = $userinfo['nickname'];//获取nickname对应的值,即用户名
        }else{
            echo "NO CODE";
        }
    }
   
    
    public function getUserInfo($code)
    {
        $appid = "wxa6d4e8d3f4468cfc";
        $appsecret = "61d7c6f5cd3c81da729f8e10b57845f7";


        // $appid          = $this->appId;
        // $appsecret      = $this->appSecret;

        //Get access_token
        $access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code";
        $access_token_json = https_request($access_token_url);//自定义函数
        $access_token_array = json_decode($access_token_json,true);//对 JSON 格式的字符串进行解码，转换为 PHP 变量，自带函数
        //获取access_token
        $access_token = $access_token_array['access_token'];//获取access_token对应的值
        //获取openid
        $openid = $access_token_array['openid'];//获取openid对应的值

        //Get user info
        $userinfo_url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid";
        $userinfo_json = https_request($userinfo_url);
        $userinfo_array = json_decode($userinfo_json,ture);
        return $userinfo_array;
    }

}