微信小程序获取openid js及php代码
先看看小程序的前端js代码如何编写
wx.login({ success: res => { // 发送 res.code 到后台换取 openId, console.log(res.code) wx.request({ url: '后端php访问地址', method: "GET", data: { code: res.code }, success: function (res) { if (res.statusCode == '200') { console.log(res); } } }) } })前端完了,我们来写后端代码
<?php $appid = "wx1231312321"; $appsecret = "12312334343534534535"; $code = $_GET['code']; if ($code == '') { echo json_encode([ 'code' => '201', 'data' => 'code不能为空' ]); exit(); } $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$appsecret.'&js_code='.$code.'&grant_type=authorization_code'; $result = http_curl($url); $token = json_decode($result, 1); if (isset($token['openid'])) { $openid = $token['openid']; //拿到openid echo json_encode([ 'code' => '200', 'data' => $openid ]); exit(); } echo json_encode([ 'code' => '201', 'data' => "登陆失败" ]); function http_curl($url) { $curlobj = curl_init(); curl_setopt($curlobj, CURLOPT_URL, $url); curl_setopt($curlobj, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curlobj, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($curlobj, CURLOPT_SSL_VERIFYHOST, FALSE); $output = curl_exec($curlobj); curl_close($curlobj); return $output; } ?>好了,写完了,