ionic3 獲取微信授權(quán)登錄魂拦,雖然插件齊全深纲,但是還是遇到了不少坑。完整的親測有效代碼如下:
import { Wechat } from '@ionic-native/wechat';
import { HTTP } from '@ionic-native/http';
上面這兩個(gè)插件就不用說了,能找到這里的都知道這兩個(gè)是什么插件。主要是為什么要用HTTP這個(gè)插件欠动,因?yàn)檫@個(gè)插件解決了獲取微信授權(quán)跨域的問題,囧。
//登錄
tapLogin() {
try {
// 1. 獲取code
let scope = "snsapi_userinfo";
let state = "_" + (+new Date());
//1.先用插件獲取到code
Wechat.auth(scope, state, (response) => {
console.log("獲取code", response);
alert("獲取code:" + JSON.stringify(response));
let appId = "";//你自己的id
let appSecret = "";//你自己的
let accessTokenUrl = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' + appId + '&secret=' + appSecret + '&code=' + response.code + '&grant_type=authorization_code'
//2.獲取token具伍,openid翅雏,等
this.http.get(accessTokenUrl, {}, {})
.then(data => {
console.log(data.status);
console.log(data.data); // data received by server
console.log(data.headers);
alert("data==" + JSON.stringify(data));
//這個(gè)自己解析獲取正確的accessToken
let accessToken = data.data.access_token;
let openId = data.data.openid;
//3.獲取個(gè)人信息
let userInfoUrl = `https://api.weixin.qq.com/sns/userinfo?access_token=${accessToken}&openid=${openId}`;
this.http.get(userInfoUrl, {}, {}).then(data => {
console.log(data)
alert("data2==" + JSON.stringify(data));
}).catch(error => {
alert("error==" + JSON.stringify(error))
console.log(error.status);
console.log(error.error); // error message as string
console.log(error.headers);
});
})
.catch(error => {
alert("error==" + JSON.stringify(error))
console.log(error.status);
console.log(error.error); // error message as string
console.log(error.headers);
});
}, (reason) => {
alert("Failed: " + reason);
});
} catch (error) {
alert("Failed: " + error);
console.log(error);
}
}