本以为啊,要想使用微信的接口就必须验证微信服务器,验证完微信服务器那么什么在微信公众号或者服务号后台创建的那些菜单啊,自动回复啊什么的都要再用代码写一遍,如果你的项目一开始就是你写的倒还好,如果是一个已经成型的项目,之前只是在服务号菜单放一链接这种的微信项目,老板突然要在会员注册成功的时候公众号推送一条消息告诉他的时候,会不会有那么一瞬间的懵逼....

    回归正题,现在来时说不验证服务器的情况下去微信取accress_token

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
class wx
{
    public $appid;
    public $secret;
    public $type;
 
    public function __construct()
    {
        parent::__construct();
        //appid和secret 需取服务号后台去查看
        $this->appid = 'AppId';
        $this->secret = 'Appsecret';
        $this->type = 'client_credential';
    }
 
    /**
     * 获取token值,
     * 获取cookie中的值若cookie失效重新请求微信获取cookie
     */
    public function get_token(){
        $access_token $_COOKIE['access_token'];
        if(!$access_token){
            $access_token $this->_addToken();
        }
        return $access_token;
    }
 
    /**
     * 请求微信获取access_token
     * @return mixed
     */
    private function _addToken () {
        $url 'https://api.weixin.qq.com/cgi-bin/token?grant_type='.$this->type.'&appid='.$this->appid.'&secret='.$this->secret;
        $data =  json_decode( $this->curl_get($url),true);
        if($data['errcode']){
            //提示报错信息
            showMessage($data['errmsg']);
        else {
            setcookie('access_token'$data['access_token'],  7200);
            return $data['access_token'];
        }
    }
 
     
    /**
     * get请求
     * @param $url
     * @return mixed
     */
    public function curl_get($url){
        $ch = curl_init();
        //设置选项,包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        //执行并获取HTML文档内容
        $output = curl_exec($ch);
        //释放curl句柄
        curl_close($ch);
        //打印获得的数据
        return $output;
    }
 
}

需要注意的是微信返回的数据格式是

{"access_token":"ACCESS_TOKEN","expires_in":7200}

 我们在php中处理一般多用数组,所以我们想到了json_decode函数可以将json 转成数组,现在就说一下json_decode这函数的用法

<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
 
var_dump(json_decode($json));
var_dump(json_decode($json, true));
 
?>
 输出结果是
 
object(stdClass)#1 (5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}
 
array(5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

 
相关评论(0)
您是不是忘了说点什么?

友情提示:垃圾评论一律封号...

还没有评论,快来抢沙发吧!