/**
*用户授权登录
*/
public function getOauthRedirect()
{
$appid = $this->appid; //appid
$callback = ''; //回调地址
$res = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appid .
'&redirect_uri=' . urlencode($callback) . '&response_type=code&scope=snsapi_userinfo
&state=1&connect_redirect=1#wechat_redirect';
header("Location:" . $res);
}
/**
* 获取用户信息
* @param Request $request
* @return string
*/
public function getOauthUserinfo(Request $request)
{
$code = $request->input('code') ? $request->input('code') : ''; //获取code
//使用code和appid与秘钥 获取openid和access_token
$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' .
$this->appid . '&secret=' . $this->appsecret . '&code=' . $code . '&grant_type=authorization_code';
$data = file_get_contents($url); //获取openid
$data1 = json_decode($data, TRUE); //转数组
if(!isset($data1['access_token'])) return jsonReturn(-1,'授权失败');
$url1 = 'https://api.weixin.qq.com/sns/userinfo?access_token=' .
$data1['access_token'] . '&openid=' . $data1['openid'];
$data2 = file_get_contents($url1); //获取用户信息
$data3 = json_decode($data2, TRUE);
$openid = $data3['openid'];
$nickname = $data3['nickname'];
$sex = $data3['sex'];
if ($openid != '' && $nickname != '') {
$request->session()->put('openid', $openid);
try{
//逻辑操作
}catch (Exception $e){
return $e->getMessage();
}
}else{
$request->session()->put('member_id', $member['id']);
}
$target_url =empty(session('target_url')) ? '/web' : session('target_url');
header("Location:" . $target_url); //可能会失效 可改用js跳转
// echo "<script language='javascript' type='text/javascript'>
window.location.href=$target_url;</script>";return false;
} else {
// $this->getOauthRedirect();
return jsonReturn(-1,'授权失败');
}
}