微信环境下获取code、access_token和openid

//获取code
getCode ()

function getCode() {
    var code = GetRequest()['code'];
    var local = window.location.href;
    if (code == null || code === '') {
        window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + window.APPID + '&redirect_uri=' + encodeURIComponent(local) + '&response_type=code&scope=snsapi_base&state=1#wechat_redirect'
    } else {
        getOpenId(code) //把code传给后台获取用户信息
    }
}

//从url中获取code
function GetRequest() {
   var url = location.search;
   var theRequest = new Object();
   if (url.indexOf("?") != -1) {
       var str = url.substr(1);
       strs = str.split("&");
       for (var i = 0; i < strs.length; i++) {
           theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
       }
   }
   return theRequest;
}

//向后台请求获取openid的接口
function getOpenId(code) {
   $.ajax({
       url: "/getOpenid",
       type: "POST",
       data: {
           code: code
       },
       success: function (res) {
           console.log('获取成功')
       },
       error: function (err) {
           console.log("失败")
       }
   })
}


// 后台根据code获取access_token和openId

// 调取接口:https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
    // ````	
    // | 参数		| 是否必须	| 说明						|
    // | ----		| ----						| ----
    // | appid		| 是		| 公众号的唯一标识			|
    // | secret	| 是		| 公众号的appsecret			|
    // | code		| 是		| 填写第一步获取的code参数	|
    // | grant_type | 是		| 填写为authorization_code	


    //返回的参数
    // {
    //   "access_token":"ACCESS_TOKEN",
    //   "expires_in":7200,
    //   "refresh_token":"REFRESH_TOKEN",
    //   "openid":"OPENID",
    //   "scope":"SCOPE" 
    // }

    // |参数|描述|
    // |----|----|
    // |access_token	|网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同 |
    // |expires_in		|access_token接口调用凭证超时时间,单位(秒)	 |
    // |refresh_token	|用户刷新access_token		 |
    // |openid			|用户唯一标识,请注意,在未关注公众号时,用户访问公众号的网页,也会产生一个用户和公众号唯一的OpenID	|
    // |scope			|用户授权的作用域,使用逗号(,)分隔	|

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值