由于是前后端分离的项目,所以需要特殊处理:
- 前端在未登录的情况下打开应用时,跳转到微信授权页面
 - 确认授权后微信服务器会重定向到之前设定的
 redirect_url,我们这里设置为/oauth- 重定向后,前端从
 url中获取到code后,请求服务器来获取access_token及用户信息
注意:需要熟悉微信的oauth网页授权流程 微信oauth文档
网页授权流程.png
其中:前端实现了第一步,服务端实现了第二步和第四步,其他步骤不需要
- 脚手架搭建Vue项目,添加vue-router插件
 - 创建Oauth.vue并加入到router中,特别注意,要开启
history模式,默认是hash模式 
<template>
    <div>
        oauth
    </div>
</template>
<script>
    import axios from 'axios'
    export default {
        name: "Oauth",
        beforeMount() {
            this.oauth();
        },
        methods: {
            oauth() {
                //1.跳转到授权页面
                let appid = process.env.VUE_APP_APPID;//根目录下的.env中获取到VUE_APP_APPID的值
                let target_url = location.href;
                window.console.log(target_url)//http://oauth.do.test/oauth
                // 2.返回后获取code
                let code = new URL(target_url).searchParams.get('code')//跳转微信服务器获取code后会重定向到本页面,并携带code
                if (code === null) {
                    //第一次进入
                    window.console.log(target_url)
                    let wechat_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + target_url + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
                    window.console.log(wechat_url)
                    location.href = wechat_url;
                } else {
                    //重定向返回,携带了code
                    window.console.log('code:', code)
                    // 3.请求服务器获取用户信息
                    axios.get('http://tbk.test/spaOauth?code=' + code)
                        .then((data) => {
                            window.console.log(data)
                            // 4.将用户信息存入cookie等
                            localStorage.setItem('user', data)//如果data是Object则需要使用JSON.stringify(data)转换为字符串,和后端协调
                        })
                        .catch((reason) => {
                            window.console.log(reason)
                            alert(reason)
                        })
                }
            }
        }
    }
</script>
//router/index.js
import 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,内容如下:
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>
目的是让网页可以正常访问,不会出现访问http://oauth.do.test/oauth访问不到的情况,使用其他服务器软件可以参考官方文档:https://router.vuejs.org/zh/guide/essentials/history-mode.html#%E5%90%8E%E7%AB%AF%E9%85%8D%E7%BD%AE%E4%BE%8B%E5%AD%90
- 后端代码,主要实现功能:拿到前端传递过来的code,再获取到access_token,并进一步获取用户信息,创建用户,返回用户信息等。
 
//laravel web.php
Router::get('/spaOauth','OauthController@spaOauth');
//laravel OauthController.php
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use EasyWeChat\Factory;
use Illuminate\Support\Str;
class OauthController extends Controller
{
    protected $config = [];
    public function __construct()
    {
        $config = [
            'app_id' => 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()]);
            }
        }
    }


