| 微信公众号开发 基础支持 获取access_token下班闲来无事,写的微信基础授权接口,纯手打,并非网上复制,有兴趣的朋友可以参考一下 网页用户授权和拉取用户信息可查看博主其他文章有兴趣的朋友或者PHP新手可以关注我,不定时更新PHP代码代码基于 Apache2.4.39 + MySql5.7.26 + PHP7.4.3nts + 小皮面板 + Thinkphp 5.0.24
 	
	 
	
    public $Db = [
        'type' => 'mysql',
        'hostname' => '',
        'database' => '',
        'username' => '',
        'password' => '',
        'hostport' => '3306',
        'prefix' => 'w_',
    ];
	public $Appid = "";
    public $AppSecret = "";
	public $GetToken = "https://api.weixin.qq.com/cgi-bin/token?grant_type=";
    
	public function GetToken()
    {
        $Db = Db::connect($this->Db)->name("wechat_token");
        $grant_type = "client_credential";
        $token_url = $this->GetToken . "$grant_type&appid=" . $this->Appid . "&secret=" . $this->AppSecret;
        
        $AcctokenData = $Db->where(["name" => "access_token"])->find();
        if (empty($AcctokenData) or $AcctokenData['expiration'] < time()) {
            
            
            $TokenInfo = $this->PostCurl($token_url);
            
            $TokenInfo = !empty($TokenInfo) ? json_decode($TokenInfo, true) : NULL;
            
            if (!empty($TokenInfo['access_token'])) {
                
                $AcctokenCount = $Db->where(["name" => "access_token"])->count();
                if ($AcctokenCount == 0) {
                    $Db->insert([
                        'name' => "access_token", "token" => $TokenInfo['access_token'],
                        'obtain' => time(), 'expires_in' => $TokenInfo['expires_in'],
                        "expiration" => time() + $TokenInfo['expires_in']
                    ]);
                } else {
                    $Db->where(["name" => "access_token"])->update([
                        "token" => $TokenInfo['access_token'], 'obtain' => time(),
                        'expires_in' => $TokenInfo['expires_in'], "expiration" => time() + $TokenInfo['expires_in']
                    ]);
                }
                $access_token = $TokenInfo['token'];
            } else {
                return $this->msg(404, "获取Token失败,失败原因:" . $TokenInfo['errmsg'], $TokenInfo, 0);
            }
        } else {
            
            $access_token = $AcctokenData['token'];
        }
        return $this->msg(200, "调用成功", ['access_token' => $access_token,], 1);
    }
 |