博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
VUE SPA 单页面应用 微信oauth网页授权
阅读量:4111 次
发布时间:2019-05-25

本文共 3133 字,大约阅读时间需要 10 分钟。

由于是前后端分离的项目,所以需要特殊处理:

  1. 前端在未登录的情况下打开应用时,跳转到微信授权页面
  2. 确认授权后微信服务器会重定向到之前设定的redirect_url,我们这里设置为/oauth
  3. 重定向后,前端从url中获取到code后,请求服务器来获取access_token及用户信息注意:需要熟悉微信的oauth网页授权流程
    网页授权流程.png
    其中:前端实现了第一步,服务端实现了第二步和第四步,其他步骤不需要
  1. 脚手架搭建Vue项目,添加vue-router插件
  2. 创建Oauth.vue并加入到router中,特别注意,要开启history模式,默认是hash模式
//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
  1. 编译项目并部署到apache虚拟主机目录中

    虚拟主机目录结构
    虚拟主机的配置内容
  2. 由于使用了history模式,所以要开启重写,在虚拟主机目录下创建一个文件.htaccess,内容如下:

RewriteEngine On RewriteBase / RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L]

目的是让网页可以正常访问,不会出现访问访问不到的情况,使用其他服务器软件可以参考官方文档:

  1. 后端代码,主要实现功能:拿到前端传递过来的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()]); } } }

转载地址:http://wlrsi.baihongyu.com/

你可能感兴趣的文章
Subsets 深搜
查看>>
Subsets II
查看>>
Edit Distance 字符串距离(重重)
查看>>
Gray Code 格雷码
查看>>
对话周鸿袆:从程序员创业谈起
查看>>
web.py 0.3 新手指南 - 如何用Gmail发送邮件
查看>>
web.py 0.3 新手指南 - RESTful doctesting using app.request
查看>>
web.py 0.3 新手指南 - 使用db.query进行高级数据库查询
查看>>
web.py 0.3 新手指南 - 多数据库使用
查看>>
一步步开发 Spring MVC 应用
查看>>
python: extend (扩展) 与 append (追加) 的差别
查看>>
「译」在 python 中,如果 x 是 list,为什么 x += "ha" 可以运行,而 x = x + "ha" 却抛出异常呢?...
查看>>
谷歌阅读器将于2013年7月1日停止服务,博客订阅转移到邮箱
查看>>
浅谈JavaScript的语言特性
查看>>
LeetCode第39题思悟——组合总和(combination-sum)
查看>>
LeetCode第43题思悟——字符串相乘(multiply-strings)
查看>>
LeetCode第44题思悟——通配符匹配(wildcard-matching)
查看>>
LeetCode第45题思悟——跳跃游戏(jump-game-ii)
查看>>
LeetCode第46题思悟——全排列(permutations)
查看>>
LeetCode第47题思悟—— 全排列 II(permutations-ii)
查看>>