Yii2微信开发系列二:获取用户信息

用户表设计

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
CREATE TABLE `wechat_user` (
`id` int(11) NOT NULL,
`openid` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`nickname` varchar(50) COLLATE utf8_unicode_ci NOT NULL COMMENT '微信昵称',
`sex` tinyint(4) NOT NULL COMMENT '性别',
`headimgurl` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT '头像',
`country` varchar(50) COLLATE utf8_unicode_ci NOT NULL COMMENT '国家',
`province` varchar(50) COLLATE utf8_unicode_ci NOT NULL COMMENT '省份',
`city` varchar(50) COLLATE utf8_unicode_ci NOT NULL COMMENT '城市',
`access_token` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`refresh_token` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

ALTER TABLE `wechat_user`
ADD PRIMARY KEY (`id`);

获取用户信息的相关接口

1.用户授权接口:获取access_token、openId等;获取并保存用户资料到数据库

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
public function actionAccesstoken()
{

$code = $_GET["code"];
$state = $_GET["state"];
$appid = Yii::$app->params['wechat']['appid'];
$appsecret = Yii::$app->params['wechat']['appsecret'];
$request_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';

//初始化一个curl会话
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $request_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
$result = $this->response($result);

//获取token和openid成功,数据解析
$access_token = $result['access_token'];
$refresh_token = $result['refresh_token'];
$openid = $result['openid'];

//请求微信接口,获取用户信息
$userInfo = $this->getUserInfo($access_token,$openid);
$user_check = WechatUser::find()->where(['openid'=>$openid])->one();
if ($user_check) {
//更新用户资料
} else {
//保存用户资料
}

//前端网页的重定向
if ($openid) {
return $this->redirect($state.$openid);
} else {
return $this->redirect($state);
}
}

2.从微信获取用户资料

1
2
3
4
5
6
7
8
9
10
11
12
public function getUserInfo($access_token,$openid)
{

$request_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
//初始化一个curl会话
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $request_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
$result = $this->response($result);
return $result;
}

3.获取用户资料接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public function actionUserinfo()
{

if(isset($_REQUEST["openid"])){
$openid = $_REQUEST["openid"];
$user = WechatUser::find()->where(['openid'=>$openid])->one();
if ($user) {
$result['error'] = 0;
$result['msg'] = '获取成功';
$result['user'] = $user;
} else {
$result['error'] = 1;
$result['msg'] = '没有该用户';
}
} else {
$result['error'] = 1;
$result['msg'] = 'openid为空';
}
return $result;
}
八宝粥 wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!