wanglizhong
2025-05-05 9b8a7157bb9c401de973a4107f74ff3e723ec156
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
<?php
//微信OAuth2授权
$APPID        = "wx70f6a7346ee842c0";
$APPSECRET    = "2d6c59de85e876b7eadebeba62e5417a";
 
$code=empty($_REQUEST['code'])!=false ? "" : addslashes($_REQUEST['code']);
if (isset($_COOKIE["openid"])){$openid=$_COOKIE["openid"];}else{$openid="";}
if ($code!="") {
    //通过code换取网页授权access_token和openid
    $wxinfo=file_get_contents("https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$APPID."&secret=".$APPSECRET."&code=".$code."&grant_type=authorization_code");
    $wxinfo=json_decode($wxinfo,true);
    extract($wxinfo);
    if (empty($openid)==false){setcookie("openid",$openid, time()+3600*24*365);}    //openid写入缓存
    
    //把state转为变量
    $state=empty($_REQUEST['state'])!=false ? "" : addslashes($_REQUEST['state']);
    if ($state!="" and $state!="[]") {
        $state=str_replace("\\","",$state);
        $state=json_decode($state, true);    //把json格式转为数组
        extract($state);    //把数组转为变量
    }
}
elseif ($openid=="") {
    $state=json_encode($_REQUEST);    //把传入参数转为json格式
    //echo $state;exit;
    header("Location: https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$APPID."&redirect_uri=https://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']."&response_type=code&scope=snsapi_base&state=".$state."#wechat_redirect"); 
    exit;
}
 
?>