获取微信授权的code的方式
微信公众号。通过跳转到一个固定的拼接的url。然后获取到这个url页面中通过获取url上面带的参数code就行了url https://open.weixin.qq.com/connect/oauth2/authorize?appid公众号的appidredirect_uri${encodeURIComponent(跳转到的url的链接地址)} response_typecodescopesnsapi_userinfostate state #wechat_redirect;!DOCTYPE html html head meta charsetutf-8 title/title script srchttps://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js/script /head body script //获取url的参数 function getUrlParam(name) { var reg new RegExp((^|) name ([^]*)(|$)); //构造一个含有目标参数的正则表达式对象 var r window.location.search.substr(1).match(reg); //匹配目标参数 if (r ! null) return unescape(r[2]); return null; //返回参数值 } var codegetUrlParam(code) console.log(code) if(code){//有Code var para{ sid:14661, code:code, schid:122 }; $.ajax({ url:https://wapitest.vvwx.net:9898/wechat/wechatminiprogramlogin/getuserinfo, type:POST, dataType: JSON, data:JSON.stringify(para), success: function (res) { console.log(res) } }) }else{ //没有code跳转去授权登录 var redirecturllocation.href; localStorage.setItem(redirect_url, redirecturl); var data{schid:122}; $.ajax({ url:https://wapitest.vvwx.net:9898/kyk/webchat/getstate, type:POST, dataType:JSON, data:JSON.stringify(data), headers: { x-access-token:251ac697b5a6cdfa4ba3be1a002d0c75 }, success: function (res) { if (res.code 1) { var appid res.data.appid; var state res.data.state; var url https://open.weixin.qq.com/connect/oauth2/authorize?appid${appid}redirect_uri${encodeURIComponent(localStorage.getItem(redirect_url))} response_typecodescopesnsapi_userinfostate state #wechat_redirect; console.log(url) window.location.href url; } } }); } /script /body /html