<?php

namespace App\Handlers;

use Illuminate\Support\Facades\Cache;

//小程序accesstoken
class MpAaccessToken
{

    private $appId;
    private $appSecret;

    public function __construct()
    {
        $this->appId = env('WX_XCX_APPID');
        $this->appSecret = env('WX_XCX_KEY');
    }

    public function getAccessToken()
    {
        // access_token 应该全局存储与更新,以下代码以写入到文件中做示例
        //$data = json_decode(file_get_contents("access_token.json"));

        $token = Cache::get('access_token_expire_time');
        $data = $token ? $token : ['expire_time' => 0];
        if ($data['expire_time'] < time()) {
            // 如果是企业号用以下URL获取access_token
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
            $res = json_decode($this->httpGet($url));
            $access_token = $res->access_token;
            if ($access_token) {
                $data['expire_time'] = time() + 7000;
                $data['access_token'] = $access_token;
                Cache::set('access_token_expire_time', $data);
            }
        } else {
            $access_token = $data['access_token'];
        }
        return $access_token;
    }

    private function httpGet($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);

        $res = curl_exec($curl);
        curl_close($curl);

        return $res;
    }
}