Wechat.class.php
3.13 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
<?php
/**
* @ignore
*/
class OAuthException extends Exception
{
// pass
}
class WechatAuth
{
/**
* @ignore
*/
public $appId;
/**
* @ignore
*/
public $appKey;
/**
* @ignore
*/
public $accessToken;
/**
* @ignore
*/
public $refreshToken;
/**
* Set API URLS
*/
/**
* @ignore
*/
function userInfoURL()
{
return 'https://api.weixin.qq.com/sns/userinfo';
}
/**
* @ignore
*/
function authorizeURL()
{
return 'https://open.weixin.qq.com/connect/qrconnect';
}
/**
* @ignore
*/
function accessTokenURL()
{
return 'https://api.weixin.qq.com/sns/oauth2/access_token';
}
/**
* construct WeichatOAuth object
*/
function __construct($appId, $appKey, $accessToken = NULL)
{
$this->appId = $appId;
$this->appKey = $appKey;
$this->accessToken = $accessToken;
}
/**
* authorize接口
* $callBackurl 回调地址
*/
function getAuthorizeURL($callBackurl, $scope, $responseType = 'code', $state = 'STATE#wechat_redirect')
{
$params = array();
$params['appid'] = $this->appId;
$params['redirect_uri'] = $callBackurl;
$params['response_type'] = $responseType;
$params['scope'] = $scope;
$params['state'] = $state;
return $this->authorizeURL() . "?" . http_build_query($params);
}
/*
* 获取accesstoken
* code:授权链接返回的code
*/
function getAccessToken($code, $grant_type = 'authorization_code')
{
if (empty($code)) {
return '';
}
$params = array();
$params['appid'] = $this->appId;
$params['secret'] = $this->appKey;
$params['code'] = $code;
$params['grant_type'] = $grant_type;
$url = $this->accessTokenURL() . "?" . http_build_query($params);
$result = self::getCurl($url);
return json_decode($result, true);
}
// 获取用户信息
function getUserInfo($access_token, $openid)
{
if (empty($access_token) || empty($openid)) {
return array();
}
$params = array();
$params['access_token'] = $access_token;
$params['openid'] = $openid;
$url = $this->userInfoURL() . "?" . http_build_query($params);
$result = self::getCurl($url);
return json_decode($result, true);
}
/**
* Send a GET requst using cURL
* @param string $url to request
* @param array $get values to send
* @param array $options for cURL
* @return string
*/
public static function getCurl($url,$method="GET")
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_TIMEOUT, 20);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
}