一:小程序登錄
1.在小程序全局js app.js文件中,調(diào)用小程序微信登錄接口
將小程序獲取到用戶的code POST方式發(fā)送到服務(wù)器端
//調(diào)用登錄接口
wx.login({
success:function(res){
console.log(res)
if(res.code){
//存在code
wx.request({
url:'http://shop.yunapply.com/home/user/saveOpenId',
data: {code:res.code},
method:'POST',
header: {
"content-type": "application/x-www-form-urlencoded"
},
success: function(res){
that.globalData.userId = res.data.info
},
fail: function() {
console.log('服務(wù)器請(qǐng)求失敗!')
},
})
}else{
console.log('獲取用戶信息失敗!'+res.errMsg)
}
}
})
|
調(diào)用接口成功以后打印出接口對(duì)象,可以得到如下信息
這里的code,有效時(shí)間是5分鐘,需要將這個(gè)code發(fā)送到服務(wù)器,用code換取session_key API,將code換成OPENID和session_key
2.在服務(wù)器端將帶有appid、secret、js_code、grant_type數(shù)據(jù),發(fā)送到微信服務(wù)器,換取session_key和openid
這里JSCODE就是放置code的地方
3.服務(wù)器端代碼
public function saveOpenId(){
if (IS_POST) {
$code = I('post.code');
if($code){
$url = "https://api.weixin.qq.com/sns/jscode2session?appid=XXXX&js_code=".$code."&grant_type=authorization_code";
$res = file_get_contents($url); //獲取文件內(nèi)容或獲取網(wǎng)絡(luò)請(qǐng)求的內(nèi)容
$result = json_decode($res);
if($result->openid){
$openid = $result->openid;
$user = D('user');
$userInfo = $user->where(array('openid'=>$openid))->find();
if(!$userInfo){
$data['openid'] = $openid;
$data['modifytime'] = date("Y-m-d H:i:s");
$userId = $user->add($data);
$this->success($userId,'',true);
}else{
$this->success($userInfo['id'],'',true);
}
}
}
}
|
流程:發(fā)送帶有codeURL,獲取網(wǎng)頁內(nèi)容,判斷openid是否存在,存在就將用戶ID返回,不存在就添加用戶然后將ID返回。
wx.login成功獲取了用戶ID,再把這個(gè)ID賦值給全局變量,UserId
二:頁面跳轉(zhuǎn)數(shù)據(jù)交互 頁面攜帶參數(shù)跳轉(zhuǎn),處理參數(shù)
這里是普通的跳轉(zhuǎn),相當(dāng)于HTML的a
參數(shù)形式key=value&key2=value2
這里是跳轉(zhuǎn)到index/index頁面
參數(shù)是
id = 1 name = zhouqi work = php
在index頁面的js中
Page({
data: {},
onLoad:function(options){
console.log(options)
wx.request({
url: 'http://shop.com/home/product/test',
data: {id:options.id,name:options.name,work:options.work},
success: function(res){
console.log(res)
},
})
|
option有攜帶過來的參數(shù)情況
這樣就可以得到攜帶過來的參數(shù)
可以通過wx.request對(duì)服務(wù)器進(jìn)行請(qǐng)求獲取數(shù)據(jù)或者其他操作
服務(wù)器端返回的數(shù)據(jù)
服務(wù)器端代碼