api.WechatAuth.php
1.73 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
<?php
/**
* 登录逻辑,获取用户openid,用于锁定唯一的用户身份
*/
include "Common/JsonResponse.php";
include "Common/mysqlHelper.php";
include "Common/WechatHelper.php";
include "Common/Encrypter.php";
$wechar = new WechatHelper();
// 查看是否有cookie
if (isset($_COOKIE['openid'])) {
$enctypt = new Encrypter();
$openid = $enctypt->decrypt($_COOKIE['openid']);
$mysql = new mysqlHelper();
$data = $mysql->fetch('select * from user where openid=?',[$openid]);
if ($data) {
header('location:' . $wechar->IndexPageURL());
}
} else {
// 本地没有记录,去微信获取openid
if (!isset($_GET['code'])) {
// 获取openid先获取code
$appid = WechatHelper::APPID;
$redirect_uri=urlencode($wechar->curPageURL());
$url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_base&state=1#wechat_redirect";
header("location:" . $url);
} else {
// 获取openid
$openid = $wechar->getOpenid($_GET['code']);
// openid写入数据库
$mysql = new mysqlHelper();
$data = $mysql->fetch('select * from user where openid=?',[$openid]);
if (!$data) {
$mysql->insert('user', ['openid' => $openid, 'created' => time() ]);
}
// openid加密写入cookie
$enctypt = new Encrypter();
setcookie("openid",$enctypt->encrypt($openid),time()+3600*24, '/', $_SERVER["SERVER_NAME"]);
header('location:' . $wechar->IndexPageURL());
}
}