<?php
namespace helper;
use think\facade\Cache;
use helper\URL;
use think\Exception;
class Wechat{
    /**
     * [GetWeiXinToken 获取微信公众号ACCESS_TOKEN]
     */
    public static function GetWeiXinToken()
    {
        if (!config('xy_wechat_mp.status'))
            throw new Exception('未开启公众号');
        $token=Cache::get('WechatToken');
        $param=[
            'grant_type'    =>  'client_credential',
            'appid'         =>  config('xy_wechat_mp.appid'),
            'secret'        =>  config('xy_wechat_mp.secret')
        ];
        $url = "https://api.weixin.qq.com/cgi-bin/token";
        if ($token)
        {
            if (!empty($token['access_token']) 
                && time() < $token['expires_time'])
                return ['status'=>1,'access_token'=>$token['access_token']];
        }
        $token = URL::get($url,$param);
        if (empty($token))
            throw new Exception('请将服务器IP地址添加到微信公众号IP白名单中，也可能是微信获取TOKEN的时候出现错误，可能是APPID或SERCRET出现错误');
        $token=json_decode($token, true);
        if (isset($token['errcode']) && $token['errcode'] != 0)
            throw new Exception("微信获取TOKEN的时候出现错误{$token['errcode']}");
        $arr = [
            'access_token'          => $token['access_token'],
            'expires_time'          => time() + $token['expires_in']
        ];
        Cache::set('WechatToken',$arr,intval($token['expires_in']));
        return ['status'=>1,'access_token'=>$token['access_token']];
    }
    /**
     * [GetWechatMiniprogramToken 获取微信小程序ACCESS_TOKEN]
     */
    public static function GetWechatMiniprogramToken()
    {
        if (!config('xy_wechatminiprogram.status'))
            throw new Exception('未开启小程序');
        $token=Cache::get('GetWechatMiniprogramToken');
        $param=[
            'grant_type'    =>  'client_credential',
            'appid'         =>  config('xy_wechatminiprogram.appid'),
            'secret'        =>  config('xy_wechatminiprogram.secret')
        ];
        $url = "https://api.weixin.qq.com/cgi-bin/token";
        if ($token)
        {
            if (!empty($token['access_token']) 
                && time() < $token['expires_time'])
                return ['status'=>1,'access_token'=>$token['access_token']];
        }
        $token = URL::get($url,$param);
        if (empty($token))
            throw new Exception('请将服务器IP地址添加到微信公众号IP白名单中，也可能是微信获取TOKEN的时候出现错误，可能是APPID或SERCRET出现错误');
        $token=json_decode($token, true);
        if (isset($token['errcode']) && $token['errcode'] != 0)
            throw new Exception("微信获取TOKEN的时候出现错误{$token['errcode']}");
        $arr = [
            'access_token'          => $token['access_token'],
            'expires_time'          => time() + $token['expires_in']
        ];
        Cache::set('GetWechatMiniprogramToken',$arr,intval($token['expires_in']));
        return ['status'=>1,'access_token'=>$token['access_token']];
    }
    public static function getUserInfo($openid)
    {
        try {
            $token = self::GetWeiXinToken();
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
        $param=[
            'access_token'  =>  $token['access_token'],
            'openid'        =>  $openid,
            'lang'          =>  'zh_CN'
        ];
        $url = "https://api.weixin.qq.com/cgi-bin/user/info";
        return json_decode(URL::get($url,$param), true);
    }
    public static function getUserInfoSns($openid,$token)
    {
        $param=[
            'access_token'  =>  $token,
            'openid'        =>  $openid,
            'lang'          =>  'zh_CN'
        ];
        $url = "https://api.weixin.qq.com/sns/userinfo";
        return json_decode(URL::get($url,$param), true);
    }
    /**
     * [createQrScene 创建临时二维码]
     * @param  [type] $Data [description]
     * @return [type]       [description]
     */
    public static function createQrScene($Data)
    {
    	$param=[
    		'expire_seconds'	=>	2592000,
    		'action_name'		=>	empty($Data['scene']['scene_str'])?'QR_SCENE':'QR_STR_SCENE',
    		'action_info'		=>	$Data
    	];
        try {
            $token = self::GetWeiXinToken();
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
    	$url="https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$token['access_token'];
        return json_decode(URL::post($url,json_encode($param)), true);
    }
    /**
     * [createQrLimit 创建永久二维码]
     * @param  [type] $Data [description]
     * @return [type]       [description]
     */
    public static function createQrLimit($Data)
    {
        try {
            $token = self::GetWeiXinToken();
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
        $param=[
            'action_name'       =>  empty($Data['scene']['scene_str'])?'QR_LIMIT_SCENE':'QR_LIMIT_STR_SCENE',
            'action_info'       =>  $Data
        ];
        $url="https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$token['access_token'];
        return json_decode(URL::post($url,json_encode($param)), true);
    }
    /**
     * [createWxaQrcode 创建小程序码]
     * @param  [type] $Data [description]
     * @return [type]       [description]
     */
    public static function createWxaQrcode($param)
    {
        try {
            $token = self::GetWechatMiniprogramToken();
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
    	$url="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$token['access_token'];
        return URL::post($url,json_encode($param));
    }
    public static function getTicket()
    {
        $ticket=Cache::get('WechatTicket');
        if($ticket)return $ticket;
        try {
            $token = self::GetWeiXinToken();
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
        $param=[
            'access_token'  =>  $token['access_token'],
            'type'          =>  'jsapi'
        ];
        $url='https://api.weixin.qq.com/cgi-bin/ticket/getticket';
        $ret=json_decode(URL::get($url,$param),true);
        if ($ret['errcode']===0) {
            $ticket=$ret['ticket'];
            Cache::set('WechatTicket',$ticket,intval($ret['expires_in']));
        }
        return $ticket;
    }
}