Vue与微信交互

获取网页授权

1、官方参考文档

https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html

2、核心步骤

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

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

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

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

5 附:检验授权凭证(access_token)是否有效

3、开发准备

https://www.cnblogs.com/yuyujuan/p/10824476.html

(1)下载花生壳进行内网穿透

  • 因为与微信交互,需要有域名,但是一般开发的机子上只有IP,因此,通过第三方工具,将自己的域名进行映射

(2)注册公众平台测试账号

  • 在生产环境中,一般域名都是固定的,不方便该,因此在开发过程中需要用测试账号进行

  • 注意:在配置的时候,需要和花生壳的配置对应

4、开发

(1)配置项目

在项目搭建好后,在项目文件夹的根目录下新建vue.config.js文件,并设置跨域,因为vue访问微信端口需要跨域

module.exports = {
    configureWebpack: {
        devServer: {

            disableHostCheck: true,
            host: "192.168.31.57",
            port: 8080,
            proxy: {
                //名字可以自定义,用于指定哪些请求需要被 target 对应的主机代理
                // 当前 devServer 的地址是 localhost:8080 , 需要代理的地址是 localhost:3000
                '/api': {
                    target: 'https://api.weixin.qq.com', //设置你调用的接口域名和端口号 别忘了加http
                    changeOrigin: true, //这里设置是否跨域
                    pathRewrite: { // 路径重写
                        '^/api': ''
                    }
                }
            }
        }
    }
}

(2)按步骤进行开发

步骤一:获取code
// 获取微信的code,通过该方法会返回一个带code的链接
getCodeApi() {
      console.log("获取code");
      //获取code
      let urlNow = encodeURIComponent(window.location.href);
      //let scope='snsapi_userinfo';    //snsapi_userinfo snsapi_base   //静默授权 用户无感知
      console.log('urlNow---------'+urlNow);
      let url =
        'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
        this.appid +
        '&redirect_uri=' +
        urlNow +
        '&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
        console.log('urlNow---------'+url);
        window.location.href = url;
    },
 // 从返回的链接中获取code,调用方法为 getUrlKey('code');
 getUrlKey: function(name) {
    //获取url 参数
      return (
        decodeURIComponent(
          (new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(
            location.href
          ) || [, ''])[1].replace(/\+/g, '%20')
        ) || null
      );
    } 
步骤二:获取openid
//注意:/api 是配置了跨域的,本质是 https://api.weixin.qq.com
let urlPath =
        '/api/sns/oauth2/access_token?appid=' +  
        this.appid +
        '&secret=' +
        this.appsecret +
        '&code=' +
        code +
        '&grant_type=authorization_code';

      console.log("获取openid----->"+urlPath);

      this.$axios
        .get( urlPath )
        .then(res => {
          console.log(res.data);
          // this.openid = res;
        })
        .catch(error => {});
整合步骤1、2
export default {
  name: 'login',
  data() {
    return {
      appid: 'wx23e27a84f99bc225', // 申请的测试appid
      redirect_uri: encodeURIComponent('http://333j13t061.zicp.vip/#/home'), //申请的测试域名
      appsecret: 'dff17a3749ba48deb40f10df42b7b6e7' //申请的appsecret
    };
  },
  created() {
    const that = this;
    let code = this.getUrlKey('code');
    if (code) {
       let urlPath =
        '/api/sns/oauth2/access_token?appid=' +
        this.appid +
        '&secret=' +
        this.appsecret +
        '&code=' +
        code +
        '&grant_type=authorization_code';
      
      //通过异步访问  
      this.$axios
        .get( urlPath )
        .then(res => {
          console.log(res.data);
          // this.openid = res;
        })
        .catch(error => {});
    } else {
      this.getCodeApi();
    }
  },
  
 methods: {
    getCodeApi() {
      console.log("获取code");
      //获取code
      let urlNow = encodeURIComponent(window.location.href);
      //let scope='snsapi_userinfo';    //snsapi_userinfo snsapi_base   //静默授权 用户无感知
      console.log('urlNow---------'+urlNow);
      let url =
        'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
        this.appid +
        '&redirect_uri=' +
        urlNow +
        '&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
        console.log('urlNow---------'+url);
        window.location.href = url;
    },
    getUrlKey: function(name) {
      //获取url 参数
      return (
        decodeURIComponent(
          (new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(
            location.href
          ) || [, ''])[1].replace(/\+/g, '%20')
        ) || null
      );
    }
  }, 
 } 
}    
  • 通过上面的步骤可以获取

    access_token:

    expires_in:

    openid:

    refresh_token: "

    scope:

后面的步骤需要补充

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值