1.首先引入jquery.js <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
2.页面加载的时候,引用getCode();
window.onload = function(){
getCode();
}
或者
$(document).ready(function(){
getCode();
});
function getCode(){
var getRequest = GetRequest();
var code = null;
//alert("getRequest.code1:"+getRequest.code)
if(!getRequest.code){
// var pageUrl = window.location.href
// .replace(/[/]/g, "%2f")
// .replace(/[:]/g, "%3a")
// .replace(/[#]/g, "%23")
// .replace(/[&]/g, "%26")
// .replace(/[=]/g, "%3d");
// //alert(pageUrl)
// var url =
// "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
// "wx73528b2e676f8008" +
// "&redirect_uri=" +
// pageUrl +
// "&response_type=code&scope=snsapi_base&state=STATE&connect_redirect=1#wechat_redirect";
// window.location.href = url;
$.ajax({
type:"GET",
url:host+"/wxpay/index",
dataType:"json",
data:{
url:location.href.split('#')[0]
},
success:function (data) {
console.log(JSON.stringify(data));
// alert("123"+JSON.stringify(data))
window.open(data)
window.history.back(-1);
},
error:function(jqXHR){
//alert("Error: "+jqXHR.status);
//没有code,再次请求获取code
}
})
}else{
//alert("getRequest.code2:"+getRequest.code)
$.ajax({
type:"GET",
url:host+"/wxpay/shouquan",
dataType:"json",
data:{
code:getRequest.code
},
success:function (data) {
console.log(JSON.stringify(data));
//alert("456"+JSON.stringify(data));
var data = data;
if(data.success){
if(data.state == 1){
var o = {
uid:data.uid,
phone:data.phone
};
o = JSON.stringify(o);
localStorage.setItem('userInfo', o);
if(localStorage.getItem('userInfo')){
//alert(JSON.stringify(localStorage.getItem('userInfo')))
userInfo = JSON.parse(localStorage.getItem('userInfo'));
//alert(userInfo.uid)
if(!!userInfo != 0){
uid = userInfo.uid;
my_phone = userInfo.phone;
}
// var href = './zhuce.html';
// $api.setHref(href);
// alert("授权成功!");
if(!!my_phone == 0 && !! uid != 0){
//微信授权获取code
var href = './zhuce.html';
$api.setHref(href);
}else if(!!my_phone != 0 && !!uid != 0){
window.location.reload();
}
}
}else{
alert(data.msg)
}
}
},
error:function(jqXHR){
alert("Error: "+JSON.stringify(jqXHR));
}
})
}
}
//获取页面请求路径中的参数
function GetRequest() {
var url = location.search; //获取url中"?"符后的字串
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;
}