微信开发之access_token获取

时间:2022-04-07 04:49:12

概念理清:

*->appid、appsecret:注册微信时,微信提供的身份证
->access_token 由appid、appsecret生成,并且2小时一变
特性:唯一有效性、全局有效性*

准备工具:curl

简单的实例

function http_curl() {
        //初始化curl
        $ch = curl_init();
        //设置链接
        $url = 'http://www.baidu.com';
        //设置curl的参数
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //采集数据
        $output = curl_exec($ch);
        //关闭curl
        curl_close($ch);
        var_dump($output);
    }

获取access_token实例

/** * 根据appID、appsecret获取 * @author:chenwenzhen * @time:十2017-5-16 10:54:04 */
    public function getWxAccessToken() {
        $appid = 'wx2219ca587f02b0d8';//公众号后台获取
        $appsecret = '736668c99461c79bed75aa3eea360f6a';//公众号后台获取
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $appsecret;

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($ch);
        curl_close($ch);
        if (curl_error($ch)) {
            var_dump(curl_error($ch));
        }
        $arr = json_decode($res);
        echo '<pre>';
        print_r($arr);
    }

获取微信服务器IP实例

 /** * 获取微信的IP地址,根据Access_token * @author:chenwenzhen * @time:2017-5-12 14:57:02 */
    public function getWxServerIp() {
        $accesstoken = 'ES3SiMQeL5PQbHAnqQ3dJorfBtexgzYowkUc6wNammh7KlgW5x-lXv1KYu6lHhMusCQYTX7Ddrmglev03sMZWZizgdf44jOZSn1SEJzuLCN9NRfS_jHSrfzqorpQDwiwFDYfAAATRM';
        $url = 'https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=' . $accesstoken;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($ch);
        curl_close($ch);
        if(curl_error($ch)){
            var_dump(curl_error($ch));
        }
        $arr = json_decode($res);
        echo '<pre>';
        print_r($arr);
    }