1. 程式人生 > >小程式request請求PHP伺服器session失效的解決,header頭部加cookie

小程式request請求PHP伺服器session失效的解決,header頭部加cookie

經過各種百度查詢,總算摸索出來了,跟php的小夥伴們分享下:
app.js:

//登入流程
    //獲取openid 等資訊並存儲資料
    wx.login({
      success: function (res) {
        if (res.code) {

          //小程式第一次發起網路請求
          wx.request({
            url: that.globalData.url ,
            data: {
              code: res.code,
            },
            method: "POST"
, header: { 'content-type': 'application/x-www-form-urlencoded' }, success: function (res) { console.log(res.data) var wxSecretData = res.data.data.info; var wxSession = res.data.data.session_id; //儲存快取資料
//伺服器的session_id值 wx.setStorageSync('PHPSESSID', wxSession); //3rd_session wx.setStorageSync('wxSecretData', wxSecretData); //儲存成功後設置全域性登入狀態 that.globalData.wxlogin = true } }) } else { console.
log('獲取使用者登入態失敗!' + res.errMsg) } } })

第二次及以後每次其他請求時必須加上cookie頭,伺服器端才會認為倆次請求為同一使用者

 //獲取手機號時對後端的請求
  getPhoneNumber: function (e) {
     //檢測登入態
    wx.checkSession({
      success: function () {
        if (e.detail.errMsg ==="getPhoneNumber:ok"){
          //session 未過期,並且在本生命週期一直有效
          var session_id = wx.getStorageSync('PHPSESSID');//獲取本地取儲存的sessionID  
          //header頭部加入cookie   PHPSESSID為php伺服器跟瀏覽器中cookie中的session_id名字,不能更換,java為:JSESSIONID
          var header = { 'content-type': 'application/x-www-form-urlencoded', 'Cookie': 'PHPSESSID=' + session_id }
          //傳值給伺服器獲取並存儲
          wx.request({
            url: app.globalData.url ,
            data: {
              iv: e.detail.iv,
              secretCode: e.detail.encryptedData
            },
            method: 'POST',
            header: header,
            success: function (res) {
              console.log(res.data);
              return;
              if (res.data.status == 1) {
                //獲取手機號。。。
              } else {
                wx.showToast({
                  title: '讀取手機號失敗',
                  image: app.globalData.wrongSrc,
                  duration: 2000
                })
              }
            },
            fail: function () {
              wx.showToast({
                title: '獲取失敗',
                image: app.globalData.wrongSrc,
                duration: 2000
              })
            }

          });
        }

      },
      fail: function () {
        //登入態過期
        wx.login() //重新登入

      }
    })

  },

PHP伺服器端:

//獲取當前伺服器端的session_id,然後給小程式傳值過去
 session_id();