<?php
/*
 本代码由 焕岱科技 创建
 技术支持 WX：15285007200
 严禁反编译、逆向等任何形式的侵权行为，违者将追究法律责任
*/

namespace app\common\model\bbfxshop;

use think\Model;
use think\Cache;
use think\Db;

class Weixin extends Model
{
    protected static $config = [];
    
    
    public static function getSet(){
        
        if(empty(self::$config)){
            $config  = Db::name("platform")->where("id",UNIACID)->find();
            self::$config = $config;
        }
        else{
            $config = self::$config;
        }
        
        return $config;
    }
    
    public static function login($code){
        $config = self::getSet();
        
        if(empty($code)){
            return __json(0,'code错误');
        }
        
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $config['wxapp_AppId'] . '&secret=' . $config['wxapp_AppSecret'] . '&js_code=' . $code . '&grant_type=authorization_code';
        $result = ihttp_get($url);
        $result = json_decode($result['content'],true);
        if(empty($result['openid'])){
            return __json(0,'登录失败:'.$result['errmsg']);
        }
        
        return __json(1,"登录成功",$result);
    }
    
    public static function getPhoneNumber($code){
        
        $result = self::getAccessToken();
        if($result['code'] != 1){
            return $result;
        }
        $access_token = $result['data'];
        
        if(empty($code)){
            return __json(0,'code错误');
        }
        
        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=".$access_token;
        
        $data = array("code"=>$code);
        
        $data = urldecode(json_encode($data)); 
        
        $result = ihttp_post($url,$data);
        $result = json_decode($result['content'],true);
        if(empty($result)){
            return __json(0,'接口错误');
        }
        else{
            if($result['errmsg'] == 'ok'){
                return __json(1,"操作成功",$result['phone_info']['phoneNumber']);
            }
            else{
                return __json(0,$result['errmsg']);
            }
        }
    }
    
    // 小程序码永久有效，数量暂无限制
    public static function getUnlimitedQRCode($page,$name,$type=0,$n=0){
        
        
        $path = ROOT_PATH.'public/data/qr';
        if(!file_exists($path)){ //判断目录是否存在
            mkdir($path, 0777, true); 
        }
        
        $qr_path = "/data/qr/".$name.".png";
        $filename = ROOT_PATH."public".$qr_path;
        
        if($type == 1){
            if (file_exists($filename)) {
                 return __json(1,"操作成功",['url'=>$qr_path]); 
            }
        }
        
        
        $result = self::getAccessToken();
        if($result['code'] != 1){
            return $result;
        }
        $access_token = $result['data'];
        
        $params = explode("?",$page);
        
        $data = array(
            'scene' => (!empty($params[1])?$params[1]:''), 
            'page' => $params[0],
            'check_path'=>false,
            'env_version'=>'release' // 正式版为 "release"，体验版为 "trial"，开发版为 "develop"。默认是正式版。
        );
        if(empty($data['scene'])){
            $data['scene'] = "666";
        }
        // echo "<pre>";
        // print_r($data);die;
        $json = json_encode($data);
        $response = ihttp_request("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$access_token,$json);
             
        $result = $response["content"];
        // print_r($result);die;
        if(strstr($result, 'errcode')){
            $result = json_decode($result,true);
        }
        
        if(isset($result['errcode'])){ //查看文档错误代码
            if($result['errcode'] == 40001 && $n == 0){
                // access_token无效
                $n++;
                self::clearAccessToken();
                return self::getUnlimitedQRCode($page,$name,$type,$n);
            }
            return __json(0,$result['errcode']."：".$result['errmsg']);
        }
        
        //  创建将数据流文件写入我们创建的文件内容中
        $ifp = fopen( $filename, "w" );
        fwrite( $ifp, $result );
        fclose( $ifp );
        
        return __json(1,"操作成功",['url'=>$qr_path]); 
    }
    
    // 获取公众号jsapi_ticket
    public static function getTicket($appid='',$secret=''){
        $config = self::getSet();
        
        if($appid == "" && $secret == ""){
            $appid = $config['AppId'];
            $secret = $config['AppSecret'];
        }
        
        if(empty($appid) || empty($secret)){
            return __json(0,"缺少参数appid或秘钥");
        }
        
        $ticket_key = "ticket_".$appid;
        $ticket_expires_time_key = "ticket_expires_time_".$appid;
         
        $ticket = Cache::get("{$ticket_key}");
        
        if(!empty($ticket)){
            $ticket_expires_time = (int)Cache::get("{$ticket_expires_time_key}");
            if($ticket_expires_time > time()){
                return __json(1,"操作成功",$ticket);
            }
        }
        
        $result = self::getWxAccessToken();
        if($result['code'] != 1){
            return $result;
        }
        $access_token = $result['data'];
        
        $result = ihttp_get("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$access_token}&type=jsapi");
        $result = json_decode($result['content'],true);
        
        if(!empty($result['ticket'])){
            
            Cache::set("{$ticket_key}",$result['ticket']);
            Cache::set("{$ticket_expires_time_key}",$result['expires_in'] + time());
            
            return __json(1,"操作成功",$result['ticket']);
        }
        else{
            return __json(0,"获取ticket失败",$result);
        }
    }
    
    //获取小程序AccessToken
    public static function getAccessToken($appid = "",$secret = ""){
        
        $config = self::getSet();
        
        if($appid == "" && $secret == ""){
            $appid = $config['wxapp_AppId'];
            $secret = $config['wxapp_AppSecret'];
        }
        
        if(empty($appid) || empty($secret)){
            return __json(0,"缺少参数appid或秘钥");
        }
        
        $access_token_key = "access_token_".$appid;
        $access_token_expires_time_key = "access_token_expires_time_".$appid;
        
        $access_token = Cache::get("{$access_token_key}");
        
        if(!empty($access_token)){
            $access_token_expires_time = (int)Cache::get("{$access_token_expires_time_key}");
            if($access_token_expires_time > time()){
                return __json(1,"操作成功",$access_token);
            }
        }
        
        $result = ihttp_get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}");
        
        $result = json_decode($result['content'],true);
        
        if($result['access_token']){
            
            Cache::set("{$access_token_key}",$result['access_token']);
            Cache::set("{$access_token_expires_time_key}",$result['expires_in'] + time());
            
            return __json(1,"操作成功",$result['access_token']);
        }
        else{
            return __json(0,"获取AccessToken失败",$result);
        }
    }

    // 清除AccessToken
    public static function clearAccessToken($appid='',$secret=''){
        $config = self::getSet();
        
        if($appid == "" && $secret == ""){
            $appid = $config['wxapp_AppId'];
            $secret = $config['wxapp_AppSecret'];
        }

        if(empty($appid) || empty($secret)){
            return true;
        }
        
        $access_token_key = "access_token_".$appid;
        $access_token_expires_time_key = "access_token_expires_time_".$appid;

        Cache::rm("{$access_token_key}");
        Cache::rm("{$access_token_expires_time_key}");
    }
    
    //获取公众号AccessToken
    public static function getWxAccessToken($appid = "",$secret = "",$type=0){
        
        $config = self::getSet();
        if($appid == "" && $secret == ""){
            $appid = $config['AppId'];
            $secret = $config['AppSecret'];
        }
        
        if(empty($appid) || empty($secret)){
            return __json(0,"缺少参数appid或秘钥");
        }
        
        $access_token_key = "gzh_access_token_".$appid;
        $access_token_expires_time_key = "gzh_access_token_expires_time_".$appid;
        
        $access_token = Cache::get("{$access_token_key}");
        
        if(!empty($access_token) && $type == 0){
            $access_token_expires_time = (int)Cache::get("{$access_token_expires_time_key}");
            if($access_token_expires_time > time()){
                return __json(1,"操作成功",$access_token);
            }
        }
        
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
        
        $result = ihttp_get($url);
        
        $result = json_decode($result['content'],true);
        
        if($result['errcode'] == 45009 && strstr($result['errmsg'], 'getStableAccessToken')){
            
            $data = [
                'grant_type'=>'client_credential',
                'appid'=>$appid,
                'secret'=>$secret
            ];
            $url = "https://api.weixin.qq.com/cgi-bin/stable_token";
            $result = ihttp_post($url,json_encode($data));
            $result = json_decode($result['content'],true);
            
        }
        
        if($result['access_token']){
            
            Cache::set("{$access_token_key}",$result['access_token']);
            Cache::set("{$access_token_expires_time_key}",$result['expires_in'] + time());
            
            return __json(1,"操作成功",$result['access_token']);
        }
        else{
            return __json(0,"获取AccessToken失败",$result);
        }
    }
}