在小程序中获取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); } }) },

【在小程序中获取openId,附加具体代码】2.后台 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中调用,并返回 public function openId() { $code = $this->request->post('code'); echo $this->getOpenId($code); }

    推荐阅读