前序:

由于之前一直是后端直接调用微信授权后,拿到相关信息后再返回给我(就是以前的前后端不分离),所以对微信公众号开发的微信授权登录还一直处于懵逼情况,直到今天有一个项目需要前后端分离,要前端主动去获取微信授权,所以才有了今天的这篇文章。

一、通过接口获取appId(微信调用授权需要的jdk)

要想获取授权,必须要有公众号的相关信息,所以必须要通过接口获取appId。详情请看微信公众号网页开发授权登录[传送门]

二、微信授权登录

从前面的步骤,我们可以获取到appId信息,获取到appId之后,我们就可以调微信的授权登录地址了。

注释:
APPID :就是通过后端获取回来的公众号appId。
REDIRECT_URI:就是当前页面地址,前端可以使用encodeURIComponent(window.location.href.split("#")[0])方法获取。
response_type:默认code方式
scope:有snsapi_base,snsapi_userinfo两种。
snsapi_base:不弹出授权页面,只能获取openid。
snsapi_userinfo:弹出授权弹窗,可以通过openid获取到相关信息。
state:重定向之后会带上state参数
#wechat_redirect: 页面直接打开还是做页面302都必须带此参数

https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect

三、获取Code

通过微信授权登录,成功之后,微信会重定向回到我们开发的页面,并且带了一个Code参数在url链接里面。

四、获取token

获取到Code,我们就可以通过Code传给后端,然后其他操作可以让后端进行操作。code仅只可以用一次,5分钟未使用自动过期。(后面的操作,后端拿到code后,就去获取网页授权access_token,再刷新access_token,再拉取用户信息 最后还有校验授权凭证)

以上就是微信授权登录的流程。


再说下,具体的逻辑思路。

这里的逻辑判断,都是在vue路由router.js的router.beforeEach中(即路由拦截前)中写。

判断token是否存在

1、如果token存在,就可以直接跳转页面。
跳转页面之前,就要验证token是否过期(可以通过接口访问,如果接口报错,看报错是否是token过期导致)。
a、如果token是过期了,就重新走授权登录步骤。
b、如果token没过期,就进行正常的跳转页面。

2、如果token不存在,就要进行授权登录步骤。

微信公众号前端登录demo 前端公众号授权登录_vue

最后的最后说一下vue-router的history模式:

1、首先vue默认是hash模式,就是/#/后的name进行单页面路由变化,对于seo不够友好,还有不够美观。

2、history模式,可以让路由/name进行跳转,但是缺点就是要后端配置。
如果域名是根目录 ,比如www.a.com,就可以访问页面的话,前端配置mode:history模式就好了。
如果是配置到域名下面的目录,比如 www.a.com/h5/才可以访问页面的话,前端配置mode:history,还要在路由配置base: ‘/h5/’

3、后端配置:

a、如果是Apache:

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

b、 如果是nginx

location / {
  try_files $uri $uri/ /index.html;
}

c、 如果是Node.js

const http = require('http')
const fs = require('fs')
const httpPort = 80

http.createServer((req, res) => {
  fs.readFile('index.htm', 'utf-8', (err, content) => {
    if (err) {
      console.log('We cannot open "index.htm" file.')
    }

    res.writeHead(200, {
      'Content-Type': 'text/html; charset=utf-8'
    })

    res.end(content)
  })
}).listen(httpPort, () => {
  console.log('Server listening on: http://localhost:%s', httpPort)
})

d、 如果是Internet Information Services (IIS)
安装 IIS UrlRewrite
在你的网站根目录中创建一个 web.config 文件,内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="Handle History Mode and custom 404/500" stopProcessing="true">
          <match url="(.*)" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
          </conditions>
          <action type="Rewrite" url="/" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

e、 如果是Caddy

rewrite {
    regexp .*
    to {path} /
}

f、 如果是Firebase 主机

{
  "hosting": {
    "public": "dist",
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  }
}