前端-微信公众号获取code给后端换取openid 以及access_token 并拿到用户相关信息

只含前端操作!!!只含前端操作!!!只含前端操作!!!

首先,最先做的就是配置你的回调域名,这里直接上图(开通公众号这里不做赘述,毕竟只从事前端开发工作)
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
配置好回调域名以后,为了获取code,需要打开如下页面:

https://open.weixin.qq.com/connect/oauth2/authorize?appid=你的公众号appid&redirect_uri=你想打开的地址首页&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect
在这里插入图片描述如果用户同意授权,页面将跳转至 redirect_uri/?code=CODE&state=STATE。

	mounted() {
	   if(!window.localStorage.getItem('code')){ // 如果缓存localStorage中没有微信openId,则需用code去后台获取
	     this.getCode()
	   } else {
	       // 你的业务需求代码
	   }
	 },
	getCode () { // 非静默授权,第一次有弹框
      this.code = '';
      var local = window.location.href;// 获取页面url
      var appid = '你的公众号appid';
      this.code = this.getUrlCode().code; // 截取code
      console.log(this.code);
      if (this.code == null || this.code === '') { // 如果没有code,则去请求
          window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=你想打开的地址首页&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`
      } else {
          localStorage.setItem('code', this.code);
      }
    },
    getUrlCode() { // 截取url中的code方法
      var url = location.search
      this.winUrl = url
      var theRequest = new Object()
      if (url.indexOf("?") != -1) {
        var str = url.substr(1)
        var strs = str.split("&")
        for(var i = 0; i < strs.length; i ++) {
          theRequest[strs[i].split("=")[0]]=(strs[i].split("=")[1])
        }
      }
        return theRequest
    },

当你成功获取到code之后,把code传给后端 之后就与前端无关了,因为从第二步开始,操作都得在服务端进行
在这里插入图片描述
把code通过后端给你的接口传给他 等着后端传给你用户相关数据就好了

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值