h5 微信授权

微信授权之前准备工作,微信公众号后台,需要配置白名单,业务域名,以及网页授权域名,配置完成之后进行下面操作

一、获取code

const reUrl = location.href.split('#')[0]  //获取code 之后返回的页面
        const appid = 'xxxxxx'  //公众号的appid
		// 获取code 的url 地址 ,scope 的值有snsapi_userinfo和snsapi_base
		//此处我用的是静默的方式
        const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(reUrl)}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`
        location.href = url
        

在这里插入图片描述
注意:1) 接口域名需要在微信后台白名单以及微信后台绑定的域名和接口域名需要一致,我在使用扫码功能的时候就是这个原因不能使用
2)获取code时的那个返回的url , 如果是本地localhost:xxx会有问题,可以使用线上地址用微信编辑器调式

二、code 拿到之后,就可以通过获取url 参数的方法拿到code的值

我的具体案例如下,供参考:

 getCode() { // 获取code
      if (!this.getUrlCode('code')) {
        const reUrl = location.href.split('#')[0]
        const appid = 'xxxxx'  //公众号的appid
        const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(reUrl)}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`
        location.href = url
      } else {
        const code = this.getUrlCode('code')
        this.code = code
        // alert(this.code)
      }
    },
    getUrlCode(name) { // 截取url中的code方法
      var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
      var r = window.location.search.substr(1).match(reg)
      if (r != null) return unescape(r[2])
      return null
    },
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值