由于是前后端分离的项目,所以需要特殊处理:
- 前端在未登录的情况下打开应用时,跳转到微信授权页面
- 确认授权后微信服务器会重定向到之前设定的
redirect_url
,我们这里设置为/oauth
- 重定向后,前端从
url
中获取到code
后,请求服务器来获取access_token
及用户信息注意:需要熟悉微信的oauth
网页授权流程其中:前端实现了第一步,服务端实现了第二步和第四步,其他步骤不需要
- 脚手架搭建Vue项目,添加vue-router插件
- 创建Oauth.vue并加入到router中,特别注意,要开启
history
模式,默认是hash
模式
oauth
//router/index.jsimport Vue from 'vue'import VueRouter from 'vue-router'import Home from '../views/Home.vue'Vue.use(VueRouter)const routes = [ //无关紧要的路由都删除了 { path: '/oauth', name: 'oauth', component: () => import('../views/Oauth.vue'), meta: { title: 'Oauth' } }]const router = new VueRouter({ mode:'history',//history模式 routes})export default router
-
编译项目并部署到apache虚拟主机目录中
由于使用了
history
模式,所以要开启重写,在虚拟主机目录下创建一个文件.htaccess
,内容如下:
RewriteEngine On RewriteBase / RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L]
目的是让网页可以正常访问,不会出现访问访问不到的情况,使用其他服务器软件可以参考官方文档:
- 后端代码,主要实现功能:拿到前端传递过来的code,再获取到access_token,并进一步获取用户信息,创建用户,返回用户信息等。
//laravel web.phpRouter::get('/spaOauth','OauthController@spaOauth');//laravel OauthController.php env('WECHAT_APPID'), 'secret' => env('WECHAT_SECRET'), // 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名 'response_type' => 'array', ]; $this->config = $config; }public function spaOauth() { // 1.获取客户端传来的code $code = request('code'); if (!$code) { return response()->json(['errcode' => 1, 'errmsg' => 'code为空']); } // 2.通过code获取access_token $appid = $this->config['app_id'];//你的AppID $secret = $this->config['secret'];//你的secret $response = file_get_contents("https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$secret}&code={$code}&grant_type=authorization_code"); $responseArr = json_decode($response, true); // 3.通过access_token获取用户信息 if (($access_token = array_get($responseArr, 'access_token')) && ($openid = array_get($responseArr, 'openid'))) { $response = file_get_contents("https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}&lang=zh_CN"); $responseArr = json_decode($response, true); // 4.注册或更新用户信息 try { $user = User::updateOrCreate([ 'openid' => $responseArr['openid'], 'headimgurl' => $responseArr['headimgurl'], 'nickname' => $responseArr['nickname'], 'name' => $responseArr['nickname'], 'email' => Str::random() . '@' . Str::random(5) . '.com', 'password' => md5(Str::random()) ]); // 5.返回用户信息 unset($user['password']); return response()->json(['data' => $user]); } catch (\Exception $e) { return response()->json(['errcode' => 2, 'msg' => $e->getMessage()]); } } }