vue h5微信公众号授权获取用户信息

1.申请测试账号

https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login

2.修改网页授权,填写自己需要申请授权的前端首页

(比如我这里xuexiao.zhangdengzhen.top,是我的登录页面,我在登录页面申请授权)

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

3填写申请授权的前端url,token随便写。

提交时,提示错误也不用管它
在这里插入图片描述

具体流程

1 第一步:用户同意授权,获取code

2 第二步:通过code换取网页授权access_token

3 第三步:刷新access_token(如果需要)

4 第四步:拉取用户信息(需scope为 snsapi_userinfo)

前端代码

在登录页面获取用户权限
在这里插入图片描述

<template>
  <div class="login">


<van-row>
  <van-col span="10" offset="4">
         <van-image
             round
             width="10rem"
             height="10rem"
             src="https://img1.baidu.com/it/u=1565027473,2004361185&fm=26&fmt=auto&gp=0.jpg"
           />

  </van-col>
</van-row>

      <!-- 居中 -->
<van-row type="flex" justify="center" >
  <van-col span="20" style="margin-top:20px;box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)">

        <van-field v-model="text" label="学号"   placeholder="请输学号" />
       <van-field v-model="password" type="password" label="密码"   placeholder="请输入密码" />
       <van-field
            v-model="sms"
            center
            clearable
            label="验证码"
            placeholder="请输入验证码"
          >
            <template #button>
                   <van-image
                   width="4.096rem"
                   src="https://img01.yzcdn.cn/vant/cat.jpeg"/>
            </template>
       </van-field>

  </van-col>
</van-row>

<!-- 居中 -->
<!-- <van-row type="flex" justify="center" style="margin-top:10px;" > -->
   <van-row type="flex" justify="center" style="margin-top:0.64rem;" >
  <van-col span="6">
      <van-button @click="tohome" type="primary" size="large" style="box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)">登录</van-button>
      </van-col>
</van-row>


  </div>
</template>
<style scoped>

</style>
<script>

import axios from 'axios'
export default {
   data(){
       return{
           text:"",
           password:"",
           sms:"",
           search:"",
           urlpost:""
       }
   },
   methods:{
       tohome(){

         localStorage.setItem('password', this.password);
         localStorage.setItem('text', this.text);
            axios({
           method:"post",
           url:this.urlpost,
           data:{
             zhanghao:this.text,
             mima:this.search,
             yanzhengma:this.sms,
             openid:JSON.parse(localStorage.getItem("userinfo")).openid
           }
         }).then(res=>{
            console.log(res.data)
                Toast("登录成功")
              
         })
           this.$router.push('/index') 
         
       },
       getCode(){
            axios
              .get('http://if:3000/getCode')
              .then(response => (window.location.href=response.data))
              .catch(function (error) { // 请求失败处理
                console.log(error);
              });
        },
       isCode(){
   
         return  window.location.search.includes('code=')
       },

       getUserinfo(){
         this.search=window.location.search
         const url_params=Object.fromEntries(window.location.search.slice(1).split('&').map(v=>v.split('=')))
         console.log(url_params)
         console.log(this.search)
         axios({
           method:'post',
           url:"http://ip:3000/getUserInfo",
           data:{
             code:url_params.code,
             search:this.search

           }
         }).then(res=>{
            console.log(res.data)
              localStorage.setItem("userinfo",JSON.stringify(res.data))
              
         })
       }
   },
   created(){
    //  this.getCode()
            this.urlpost=window.g.pachong
           if(this.isCode()){
              this.getUserinfo()
              console.log(this.isCode())
           }else{
               this.getCode()
           }
   },
  //  updated(){
  //    this.getUserinfo()
  //      if(this.isCode){
  //             this.getUserinfo()
  //             console.log(this.isCode())
  //          }else{
  //              this.getCode()
  //          }
  //  }
}
</script>

后端代码

1.目录结构
在这里插入图片描述
2.env文件内容(填写你测试号的APPID和APPSECRET)
在这里插入图片描述
3.serve.js内容

const app=require("express")()
const bodyParser=require("body-parser")
const cors=require("cors")
const axios=require("axios")
app.use(bodyParser.json())

require('dotenv').config()
app.use(cors())

app.get('/',async(req,res)=>{

    res.send("ok")
})
app.post('/ceshi',async(req,res)=>{
   
       console.log("账号",req.body.zhanghao)
    console.log("密码",req.body.mima)
    console.log("验证码",req.body.yanzhengma)
    console.log("openid",req.body.openid)
    res.send("ok")
})
app.get('/getCode',async(req,res)=>{

    let url=`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${process.env.APPID}&redirect_uri=${encodeURIComponent(`http://xuexiao.zhangdengzhen.top`)}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
    //console.log(url)
    res.send(url)
})
app.post('/getUserInfo',async(req,res)=>{
   let code=req.body.code;
 // console.log(req.body.search,"mysearch")
  // console.log(code)
   let accessaccess_token_url= `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${process.env.APPID}&secret=${process.env.APPSECRET}&code=${code}&grant_type=authorization_code`
   let token=(await axios.get(accessaccess_token_url)).data.access_token
   let userInfo=`https://api.weixin.qq.com/sns/userinfo?access_token=${token}&openid=OPENID&lang=zh_CN`
   let user=(await axios.get(userInfo)).data
 //  console.log(accessaccess_token_url)
  console.log(user,'user')
   res.send(user)
})
app.listen(3000,()=>{
    console.log("http://localhost:3000")
})

后端返回的数据情况

在这里插入图片描述

Logo

前往低代码交流专区

更多推荐