微信公众号小程序access_token全局存储与更新

获取和更新类

<?php 
namespace app\service;

use app\model\WxTokenModel;

class Jssdk
{
    private $appId;
    private $appSecret;

    public function __construct($appId, $appSecret)
    {
        $this->appId = $appId;
        $this->appSecret = $appSecret;
    }

    public function getSignPackage($url)
    {
        $jsapiTicket = $this->getJsApiTicket();

        // 注意 URL 一定要动态获取,不能 hardcode.
        if($url==''){
        	$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        	$url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        }else{
        	//$string = str_replace("&amp;", "&", $string);
        	$url = str_replace("&amp;", "&", $url);
        }
        $timestamp = time();
        $nonceStr = $this->createNonceStr();

        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

        $signature = sha1($string);
        $signPackage = array(
            "appId" => $this->appId,
            "nonceStr" => $nonceStr,
            "timestamp" => $timestamp,
            "url" => $url,
            "signature" => $signature,
            "rawString" => $string
        );
        return $signPackage;
    }

    private function createNonceStr($length = 16)
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    
    //jsapi_ticket-jsapi_ticket是公众号用于调用微信JS接口的临时票据
    function get_jsapi_ticket(){
    	$WxTokenModel = new WxTokenModel();
    	$where['type'] = $add_data['type'] = 3;
    	$info = $WxTokenModel->where($where)->order("id desc")->find();
        $wx_access_token_url = config("weixin.wx_access_token_url");
    	if($info){
    		if ($info['expire_in'] < time()) {
    			$access_token = $this->http_request($wx_access_token_url['url']."/api/push/get_access_token",['type'=>1]);
    			$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$access_token";
    			$res = json_decode($this->httpGet($url),true);
    			if(!empty($res['errcode'])){
    				$ticket = '';
    			}else{
    				$ticket = $res['ticket'];
    			}
    			//修改$ticket信息
    			$update_data['access_token'] = $ticket;
    			$update_data['expire_in'] = time() + 7000;
    			$update_data['new_time'] = date("Y-m-d H:i:s",time());
    			$update_data['rerurn_info'] = json_encode($res);
    			$WxTokenModel->update_by($where, $update_data);
    		}else{
    			$ticket = $info['access_token'];
    		}
    	}else{
	    	$access_token = $this->http_request($wx_access_token_url['url']."/api/push/get_access_token",['type'=>1]);
	    	$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$access_token";
	    	$res = json_decode($this->httpGet($url),true);
	    	if(!empty($res['errcode'])){
	    		$ticket = '';
	    	}else{
	    		$ticket = $res['ticket'];
	    	}    			
    		//增加$ticket信息
    		$add_data['access_token'] = $ticket;
    		$add_data['expire_in'] = time() + 7000;
    		$add_data['new_time'] = date("Y-m-d H:i:s",time());
    		$add_data['rerurn_info'] = json_encode($res);
    		$WxTokenModel->insert_data($add_data);
    	}
    	return $ticket;
    }
    

    //公众号使用
     public function getAccessToken()
    {
        // access_token 应该全局存储与更新,以下代码以写入到文件中做示例
        $data = json_decode(file_get_contents("access_token.json"));
        if ($data->expire_time < time()) {
            // 如果是企业号用以下URL获取access_token
            // $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
            $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));
            if(!empty($res->errcode)){
            	$access_token = '';
            }else{
            	$access_token = $res->access_token;
            }
            if ($access_token) {
                $data->expire_time = time() + 7000;
                $data->access_token = $access_token;
                $fp = fopen("access_token.json", "w");
                fwrite($fp, json_encode($data));
                fclose($fp);
            }
        } else {
            $access_token = $data->access_token;
        }
        return $access_token;
    } 
    //小程序使用
    public function getAccessTokenSmall()
    {
    	// access_token 应该全局存储与更新,以下代码以写入到文件中做示例
    	$data = json_decode(file_get_contents("access_token_small.json"));
    	if ($data->expire_time < time()) {
    		// 如果是企业号用以下URL获取access_token
    		// $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
    		$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));
    		if(!empty($res->errcode)){
    			$access_token = '';
    		}else{
    			$access_token = $res->access_token;
    		}
    		if ($access_token) {
    			$data->expire_time = time() + 7000;
    			$data->access_token = $access_token;
    			$fp = fopen("access_token_small.json", "w");
    			fwrite($fp, json_encode($data));
    			fclose($fp);
    		}
    	} 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;
    }
    function http_request($url, $data = array()){
    	$ch = curl_init();
    	curl_setopt($ch, CURLOPT_URL, $url);
    	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    	// POST数据
    	curl_setopt($ch, CURLOPT_POST, 1);
    	// 把post的变量加上
    	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    	$output = curl_exec($ch);
    	curl_close($ch);
    	return $output;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值