在小程序中獲取openId,附加具體代碼

1.客戶端代碼

 // 獲取 code
  getLogin: function () {
    var that = this;
    wx.login({
      success: function (res) {
        that.getOpenId(res.code);
        console.log(res);
      }
    });
  },
  //獲取openid
  getOpenId: function (code) {
    var that = this;
    wx.request({
      url: that.url.openId,
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: { 'code': code },
      success: function (res) {
        var openId = res.data.openid;
        console.log(res.data.openid);
        // that.xiadan(openId);
      }
    })
  },

2.后臺(tái) php端 代碼:

//    獲取openId
    function getOpenId($code)
    {
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='
               . $this->appid . '&secret=' 
              . $this->secret . '&js_code=' 
             . $code . '&grant_type=authorization_code';
        return $this->getHTTPS($url);
    }

    //獲取https頁面信息
    function getHTTPS($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_REFERER, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

//  封裝到公共的方法之后  在其它php中調(diào)用,并返回
  public function openId()
    {
        $code = $this->request->post('code');
        echo $this->getOpenId($code);
    }

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,680評(píng)論 19 139
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,283評(píng)論 25 708
  • 從小學(xué)一年級(jí)我們就接觸英語一直學(xué)習(xí)到大學(xué),可是大多數(shù)人都無法與老外應(yīng)答如流。我們花在英語學(xué)習(xí)上的時(shí)間不算少,但為何...
    周子魚Jo閱讀 1,142評(píng)論 1 7
  • 想罵人 對(duì)鏡子吐痰 想罵人 翻亂門前的花園 想罵人 想惹人嫌討人煩 想罵人 蹲在房檐把寫給你的歌再唱十遍二十遍 想...
    擼串兒評(píng)論員閱讀 135評(píng)論 2 1
  • # 聯(lián)系方式 - 手機(jī):18059291620 - Email:chenwentao9562@gmail.com ...
    滄溟宗主閱讀 774評(píng)論 0 0

友情鏈接更多精彩內(nèi)容