//以下三个变量内容需换成本应用的$APPID = ""; //在open.yiban.cn管理中心的AppID$APPSECRET = ""; //在open.yiban.cn管理中心的AppSecret$CALLBACK = ""; //在open.yiban.cn管理中心的oauth2.0回调地址,授权后返回的地址。
if(isset($_GET["code"])){ //用户授权后跳转回来会带上code参数,此处code非access_token,需调用接口转化。 $getTokenApiUrl = "https://oauth.yiban.cn/token/info?code=".$_GET['code']."&client_id={$APPID}&client_secret={$APPSECRET}&redirect_uri={$CALLBACK}"; $res = sendRequest($getTokenApiUrl); if(!$res){ throw new Exception('Get Token Error'); } $userTokenInfo = json_decode($res);
//格式转换
$userTokenInfo_arr=get_object_vars($userTokenInfo);
$access_token = $userTokenInfo["access_token"];}else{ $postStr = pack("H*", $_GET["verify_request"]); if(strlen($APPID) == '16') { $postInfo = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $APPSECRET, $postStr, MCRYPT_MODE_CBC, $APPID); }else { $postInfo = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $APPSECRET, $postStr, MCRYPT_MODE_CBC, $APPID); } $postInfo = rtrim($postInfo); $postArr = json_decode($postInfo, true); if(!$postArr['visit_oauth']){ //说明该用户未授权需跳转至授权页面 header("Location: https://openapi.yiban.cn/oauth/authorize?client_id={$APPID}&redirect_uri={$CALLBACK}&display=web"); die; } $access_token = $postArr['visit_oauth']['access_token'];}
//拿到access token了,接下来我们获取当前用户的基本信息试试看,so easy!$userInfoJsonStr = sendRequest("https://openapi.yiban.cn/user/me?access_token={$access_token}");$userInfo = json_decode($userInfoJsonStr,true);
//获取到的数据格式,二维数组$_SESSION['accesstaken']=$access_token;$_SESSION['id']=$userInfo['info']['yb_userid'];$_SESSION['name']=$userInfo['info']['yb_username'];$_SESSION['nick']=$userInfo['info']['yb_usernick'];$_SESSION['sex']=$userInfo['info']['yb_sex'];$_SESSION['school']=$userInfo['info']['yb_schoolname'];$_SESSION['head']=$userInfo['info']['yb_userhead'];$_SESSION['money']=$userInfo['info']['yb_money'];
function sendRequest($uri){ $ch = curl_init(); curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_setopt($ch, CURLOPT_USERAGENT, 'Yi OAuth2 v0.1'); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_ENCODING, ""); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_URL, $uri); curl_setopt($ch, CURLOPT_HTTPHEADER, array()); curl_setopt($ch, CURLINFO_HEADER_OUT, true); $response = curl_exec($ch); return $response;}?>
说明:
1.仅作为易班轻应用开发的授权登录参考方案。
2.源码与官方提供的源码差不多,修改了一点点。
3.仅仅是个人的使用心得。