微信网页授权,微信登录,oauth2

时间:2023-03-09 02:26:45
微信网页授权,微信登录,oauth2

微信官方文档: http://mp.weixin.qq.com/wiki

微信公众平台OAuth2.0授权详细步骤如下:

1. 用户关注微信公众账号。
2. 微信公众账号提供用户请求授权页面URL。
3. 用户点击授权页面URL,将向服务器发起请求
4. 服务器询问用户是否同意授权给微信公众账号(scope为snsapi_base时无此步骤)
5. 用户同意(scope为snsapi_base时无此步骤)
6. 服务器将CODE通过回调传给微信公众账号
7. 微信公众账号获得CODE
8. 微信公众账号通过CODE向服务器请求Access Token
9. 服务器返回Access Token和OpenID给微信公众账号
10. 微信公众账号通过Access Token向服务器请求用户信息(scope为snsapi_base时无此步骤)
11. 服务器将用户信息回送给微信公众账号(scope为snsapi_base时无此步骤)

授权页面:oauth.php(引导用户点入...)

 <?php
require(dirname(__FILE__) . '/api.class.php');
require(dirname(__FILE__) . '/wechat.class.php'); //多微信帐号支持
$weixinconfig = $db->getRow ( "SELECT * FROM " . $GLOBALS['ecs']->table('weixin_config') . " WHERE `id` = 1" );
//多微信帐号支持
$id = intval($_GET['id']);//
$oid = intval($_GET['oid']);// if($id > 0){
$otherconfig = $db->getRow ( "SELECT * FROM " . $GLOBALS['ecs']->table('weixin_config') . " WHERE `id` = $id" );
if($otherconfig){
$weixinconfig['token'] = $otherconfig['token'];
$weixinconfig['appid'] = $otherconfig['appid'];
$weixinconfig['appsecret'] = $otherconfig['appsecret'];
}
}
$weixin = new core_lib_wechat($weixinconfig);
if($_GET['code']){
//echo $_GET['code'];die();
$json = $weixin->getOauthAccessToken();
//print_r($json);exit();
if($json['openid']){ $wxuser = $GLOBALS['db']->getRow("select ecuid,unionid,uid,access_token from " . $GLOBALS['ecs']->table('weixin_user') . " where fake_id='{$json['openid']}'");
//print_r($wxuser);exit();
//如果用户unionid多平台登录,自动绑定
if($wxuser['unionid']==""){
$wxuserinof = $weixin->getUserInfo($json['openid']);
$sql = "update ".$GLOBALS['ecs']->table('weixin_user')." set `unionid`='".$wxuserinof['unionid']."' where uid='".$wxuser['uid']."'";
$GLOBALS['db']->query($sql);
}
$ecuid = $wxuser['ecuid']; if($ecuid > 0){
$username = $GLOBALS['db']->getOne("select user_name from ".$GLOBALS['ecs']->table('users')." where user_id='{$ecuid}'");
$GLOBALS['user']->set_session($username);
$GLOBALS['user']->set_cookie($username,1);
update_user_info(); //更新用户信息
recalculate_price(); //重新计算购物车中的商品价格
}
} $url = $api->dir."/mobile/user.php";
if($oid > 0){
$url = $db->getOne ( "SELECT weburl FROM " . $GLOBALS['ecs']->table('weixin_oauth') . "
WHERE `oid` = $oid" );
$db->query("update " . $GLOBALS['ecs']->table('weixin_oauth') . "
set click=click+1 WHERE `oid` = $oid ");
}
header("Location:$url");exit;
}
$url = $GLOBALS['ecs']->url()."/oauth.php?id={$id}&oid={$oid}";
$url = $weixin->getOauthRedirect($url,1,'snsapi_base');
header("Location:$url");exit;