关于ionic微信登录

关于ionic微信登录

最近有个ionic项目要求用户微信登录的,于是嘛,就开始搞起微信登录的模块。在搞的过程中呢,也借鉴了网上的资源,但网上资源都过于碎片化了,搞得自己有时候都很懵逼,因此写下这篇文章给自己留个底。
1.微信登录需要appId以及appSecret,需要去微信开发平台申请,其次,

微信开发平台的应用签名,其实是你得应用包名通过微信平台提供得签名工具转化出来得,而不是自己随便填填就行

2.申请完成后,在ionic执行
ionic cordova plugin add cordova-plugin-wechat --variable wechatappid=YOUR_WECHAT_APPID
ionic cordova platform add android

3.输入的appid就是微信申请得到的appid,然后参照官方文档提供的api,我们可以去获取相应的code。

4.好,当我们搞完这些后,就进行代码编写,下面是我自己的部分代码编写
weChatAuth() {
var t = this;
let loading = this.loadingCtrl.create({
content: “跳转微信登录中…”,//loading框显示的内容
dismissOnPageChange: true, // 是否在切换页面之后关闭loading框
showBackdrop: true //是否显示遮罩层
});
loading.present();
try {
let scope = “snsapi_userinfo”,
state = “_” + (+new Date());
// 1. 获取code
Wechat.auth(scope, state, (response) => {
let appId = “你的appId”;
let appSecret = “你的appSecret”;
//2.获取accesstoken和appid
this.http.get(‘https://api.weixin.qq.com/sns/oauth2/access_token?appid=’ + appId + ‘&secret=’ + appSecret + ‘&code=’ + response.code + ‘&grant_type=authorization_code’,{},{}).then(
function(resp:HTTPResponse){
let getnumber = JSON.parse(resp.data);
let accessToken = getnumber.access_token;
let openId = getnumber.openid;
t.getWechatUserInfo(accessToken,openId);
})
}, (reason) => {
alert("Failed: " + reason);
});
} catch (error) {
console.log(error);
} finally {
loading.dismiss();
}
}

getWechatUserInfo(AccessToken,Openid){
var t = this;
     let url=“https://api.weixin.qq.com/sns/userinfo
    url = url+"?access_token="+AccessToken+"&openid="+Openid;
this.http.get(url, {},{}).then(response => {
let result = JSON.parse(response.data);
t.weCharLogin(result.openid);
   })
    }

weCharLogin(openid){
let t = this;
this.http.get(AppConfig.apiRoot+‘token?openId=’+openid, {}, {}).then(
function(resp: HTTPResponse) {
let jsonMap = JSON.parse(resp.data);
t.storage.set(“token”,jsonMap[‘result’][‘token’]);
t.storage.set(“userId”,jsonMap[“result”][“userId”]);
t.getauth();
});
}

5.接下来就是进行发布apk,执行命令ionic cordova build android

好,然后运行即可,在整个过程中,比较需要注意的一点就是应用签名,以及打包apk过程中,应用签名以及应用包签名是否正确,应用包名我们可以通过config.xml上面的<widger id=“你的包名” version=“0.0.1”…

猜你喜欢

转载自blog.csdn.net/Nadou_/article/details/89711650