vue.js微信公众号登录,获取当前用户openid等基本信息

声明:此处为博主,真实开发过程的记录,直奔主题,没有测试环节,请见谅。

一、前期准备工作

  1. 微信公众平台的注册好的appid、密钥,点我去注册了解
  2. 微信公众平台中需要设置授权域名,遵循微信的规则
    在这里插入图片描述

二、登录获取openid

  1. 获取code
    获取state、appid、scope,这里重定向的地址redirect_uri我写死了,便于自己控制,根据重定向后的参数确认是否回来code,其它参数都放到数据库,后台管理即可。
getCode(){
      let methodName = "/你的后台接口地址";
        this.$http
          .post(methodName)
          .then(res => {
            let state = res.data.state;
            let appid = res.data.appId;
            this.$store.commit("set_appid", appid);
            let redirect_uri = "获取到code后你的回调地址";
            // let scope = "snsapi_userinfo";
            let scope = res.data.scope;

            let path =
              "https://open.weixin.qq.com/connect/oauth2/authorize?" +
              "appid=" +
              appid +
              "&redirect_uri=" +
              redirect_uri +
              "&response_type=code&scope=" +
              scope +
              "&state=" +
              state +
              "#wechat_redirect";

            location.replace(path);
          })
          .catch(error => {
            console.log(error);
            this.loading = false;
            this.$toast.error("获取code失败");
          });
    }

回调后vuex存储code

// 此处我是封装为一个方法,在每次created调用。
	let code = this.getQueryString("code");

    if (code) {
      this.$store.commit("set_code", code);
      //第二步:获取用户基本信息
	  this.getUserBaseInfo();
    } 
getUserBaseInfo(){
      this.$http
          .post(methodName, params)
          .then(res => {
            //存储token
            this.$store.commit("set_token", res.data.token);
            //存储用户基本信息
            this.$store.commit("set_openid", res.data.userBaseInfo.openid);
          })
          .catch(error => {
            console.log(error);
            this.loading = false;
            this.$toast.error("获取用户基本信息失败");
          });
    }

以上后台的代码具体的,参照下代码应该可以写好,这里就不详细说了,博主是专业前端开发,哪里有写的不妥的或者不对的,还请多多指教,大家互相学习。或者哪位有更好的方式方法请不吝赐教。

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值