
接口出處:https://mp.weixin.qq.com/debug/wxadoc/dev/api/api-login.html
App({
onLaunch: function() {
wx.login({
success: function(res) {
if (res.code) {
//發(fā)起網(wǎng)絡(luò)請求
wx.request({
url: 'https://test.com/onLogin',
data: {
code: res.code
}
})
} else {
console.log('獲取用戶登錄態(tài)失??!' + res.errMsg)
}
}
});
}
})
|
緩存用戶的基本信息
index.js
onLoad: function(){
var that = this
//調(diào)用應(yīng)用實(shí)例的方法獲取全局?jǐn)?shù)據(jù)
app.getUserInfo(function(userInfo){
//請求登錄
console.log(userInfo.nickName);
app.httpService(
'user/login',
{
openid: userInfo.nickName
},
function(response){
//成功回調(diào)
console.log(response);
// 本地緩存uid以及accessToken
var userinfo = wx.getStorageSync('userinfo') || {};
userinfo['uid'] = response.data.uid;
userinfo['accessToken'] = response.data.accessToken;
console.log(userinfo);
wx.setStorageSync('userinfo', userinfo);
}
);
})
}
|
app.js
定義一個(gè)通用的網(wǎng)絡(luò)訪問函數(shù):
httpService:function(uri, param, cb) {
// 分別對(duì)應(yīng)相應(yīng)路徑,參數(shù),回調(diào)
wx.request({
url: 'http://financeapi.applinzi.com/index.php/' + uri,
data: param,
header: {
'Content-Type': 'application/json'
},
success: function(res) {
cb(res.data)
},
fail: function() {
console.log('接口錯(cuò)誤');
}
})
},
|
這里method默認(rèn)為get,如果設(shè)置為其他,比如post,那么服務(wù)端怎么也取不到值,于是改動(dòng)了服務(wù)端的取值方式,由$_POST改為$_GET。
在Storage面板中,檢查到數(shù)據(jù)已成功存入