VUE SPA 单页面应用 微信oauth网页授权

本文介绍了如何在Vue项目中结合微信OAuth实现用户授权登录。前端利用history模式处理重定向,获取code并请求后端获取access_token和用户信息。后端使用Laravel接收code,获取access_token和用户详情,完成用户注册或更新。配置Apache的.htaccess文件以支持history模式。
摘要由CSDN通过智能技术生成

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

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

    虚拟主机目录结构
    虚拟主机的配置内容
  2. 由于使用了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

  1. 后端代码,主要实现功能:拿到前端传递过来的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()]);
            }
        }
    }
Vue项目中使用微信OAuth2.0授权登录,可以通过以下步骤实现: 1. 在微信公众平台或开放平台中申请应用,并获取到appID和appSecret。 2. 在Vue项目中安装wechat-oauth模块,该模块提供了微信OAuth2.0的相关接口。 ``` npm install wechat-oauth ``` 3. 在Vue项目的后端服务器中,编写一个处理微信OAuth2.0授权登录的回调接口,并在该接口中调用wechat-oauth模块提供的接口,实现用户授权登录。 ``` const OAuth = require('wechat-oauth'); const client = new OAuth(appId, appSecret); // 获取授权地址并重定向到该地址 router.get('/wechat/login', async (ctx, next) => { const redirectUrl = client.getAuthorizeURL( 'http://your-redirect-url', '', 'snsapi_userinfo' ); ctx.redirect(redirectUrl); }); // 处理授权回调 router.get('/wechat/callback', async (ctx, next) => { const code = ctx.query.code; const token = await client.getAccessToken(code); const openid = token.data.openid; const userInfo = await client.getUser(openid); // TODO: 处理用户信息 }); ``` 4. 在Vue项目中,提供一个“使用微信登录”的按钮,点击该按钮时,重定向到后端服务器中的授权接口,实现用户授权登录。 ``` <template> <div> <button @click="loginWithWechat">使用微信登录</button> </div> </template> <script> export default { methods: { loginWithWechat() { window.location.href = 'http://your-server/wechat/login'; } } } </script> ``` 需要注意的是,使用微信OAuth2.0授权登录,需要用户在微信客户端中进行操作,因此需要在移动端或微信公众号中使用。同时,需要在微信公众平台或开放平台中配置授权回调地址,并保证该地址可以被访问到。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值