美文网首页
vue-微信登录

vue-微信登录

作者: 云高风轻 | 来源:发表于2023-05-11 17:15 被阅读0次

    1. 前言

    1. vue第三方登录 这个简单的写下 微信登录的流程 ,其实哪个都行 有接口前端就能做

    2. 安装 插件

    1. npm install vue-wechat-login

    3. 登录流程

    <template>
      <div>
        <button @click="wechatLogin">微信登录</button>
      </div>
    </template>
    
    <script>
    import { WechatLogin } from 'vue-wechat-login'
    import { ref } from 'vue'
    
    export default {
      components: {
        WechatLogin
      },
      setup() {
        const authUrl = ref('')
    
        const wechatLogin = () => {
          // 在这里调用后端接口,获取微信授权链接,然后跳转到该链接进行微信登录
          // 例如:
          axios.get('/api/wechat/getAuthUrl')
            .then(response => {
              authUrl.value = response.data.authUrl
            })
            .catch(error => {
              console.log(error)
            })
        }
    
        return {
          authUrl,
          wechatLogin
        }
      }
    }
    </script>
    
    1. 这里使用vue-wechat-login插件提供的WechatLogin组件来展示微信登录按钮,
      3.当点击按钮时会调用wechatLogin方法。
      4.使用ref函数创建了一个authUrl响应式变量,用于保存微信授权链接。

    4. 创建一个路由,用于处理微信登录回调

    1. 核心代码
    import { createRouter, createWebHistory } from 'vue-router'
    import WechatLoginCallback from '@/views/WechatLoginCallback.vue'
    
    const routes = [
      {
        path: '/wechatLoginCallback',
        name: 'WechatLoginCallback',
        component: WechatLoginCallback
      }
    ]
    
    const router = createRouter({
      history: createWebHistory(),
      routes
    })
    
    export default router
    
    
    1. 这里创建了一个名为WechatLoginCallback的组件,用于处理微信登录回调。
    2. 当用户从微信登录页面回调到该组件时,可以从回调URL中获取到授权码,
    3. 然后调用后端接口,获取用户的微信信息。

    5. 后端实现

    1. 首先需要在微信公众平台或者开放平台中创建应用,并获取到应用的AppIDAppSecret
    2. 同时需要在平台中配置回调URL,用于接收微信登录回调
    1. 在后端实现一个API,用于获取微信授权链接。该API需要使用应用的AppID和回调URL构建授权链接,并返回给前端。
    
    app.get('/api/wechat/getAuthUrl', (req, res) => {
      const redirectUrl = encodeURIComponent('http://example.com/wechatLoginCallback')
      const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${APP
    
    

    参考资料


    初心

    我所有的文章都只是基于入门,初步的了解;是自己的知识体系梳理,如有错误,道友们一起沟通交流;
    如果能帮助到有缘人,非常的荣幸,一切为了部落的崛起;
    共勉

    相关文章

      网友评论

          本文标题:vue-微信登录

          本文链接:https://www.haomeiwen.com/subject/bubssdtx.html