|
define(function(require) {
var $ = require("jquery");
var justep = require("$UI/system/lib/justep");
require("cordova!com.justep.cordova.plugin.weixin.v3");
require("cordova!plugin.http.request");
// 仅作为示例用,如果正式开发,更好的方案参见takeout,从云服务器去请求微信
var weixinApp = "wxc08fa78b0a117595";
var weixinSecrt = "648dc0f1d889525095ed0cb2bea05720";
var Model = function() {
this.callParent();
};
// 图片路径转换
Model.prototype.getImageUrl = function(url) {
return require.toUrl(url);
};
Model.prototype.loginWeixinClicked = function(event) {
var self = this;
if (!navigator.weixin) {
justep.Util.hint("请安装最新版本(含插件)体验!");
return;
}
;
var weixin = navigator.weixin;
weixin.auth(function(info) {
self.weixinCode2Token(info, self.authSuccess);
alert("xiaojing3-32"); //测试运行结果
},
function(reason) {
justep.Util.hint("登录失败37行: " + JSON.stringify(reason), {
"type" : "danger"
});
});
};
Model.prototype.authSuccess = function(access_token, openid) {
alert(access_token);
//https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID
//???access_token有问题,运行到这里会提示“登录失败49行:”,去掉可以运行正常,但是没有用户名
if (!(access_token && openid)) {
justep.Util.hint("登录失败49行:", {
"type" : "danger"
});
return;
}
var url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid + "lang=zh-CN";
console.log(url);
var httpReq = new plugin.HttpRequest();
httpReq.getJSON(url, function(status, data) {
if (status) {
justep.Util.hint("登录失败61行:", {
"type" : "danger"
});
}
var user = {};
user.userid = data.openid;
user.accountType = "WX";
user.name = data.nickname || "NONAME";
justep.Shell.userType.set(user.accountType);
justep.Shell.userName.set(user.name);
localStorage.setItem("userUUID", JSON.stringify(user));
justep.Util.hint("登录成功");
setTimeout(function() {
justep.Shell.showPage("main");
}, 3000);
// 微信的返回内容
// "openid":"OPENID",
// "nickname":"NICKNAME",
// "sex":1,
// "province":"PROVINCE",
// "city":"CITY",
// "country":"COUNTRY",
// "headimgurl":
// "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0",
// "privilege":[
// "PRIVILEGE1",
// "PRIVILEGE2"
// ],
// "unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL"
});
};
Model.prototype.weixinCode2Token = function(info, authSuccess) {
var code = info.code;
var url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + weixinApp + "&secret=" + weixinSecrt + "&code=" + code + "&grant_type=authorization_code";
var httpReq = new plugin.HttpRequest();
httpReq.getJSON(url, function(status, data) {
if (status) {
justep.Util.hint("登录失败103行:", {
"type" : "danger"
});
return;
}
var unionid = data.unionid || "none";
var openid = data.openid || "none";
alert("xiaojing1-110"); //测试运行结果
var access_token = data.access_token;
alert(access_token); //这里输出undefined
authSuccess(access_token, openid);
alert("xiaojing2-113"); //测试运行结果
});
};
return Model;
}); |
|