微信小程序 微信小程序获取openID
直接上代码:
小程序端:
.wxml文件
<button bindtap="getCode">获取openid</button> .js文件 getCode() { let that = this; wx.login({ success(res) { that.getOpenid(res.code) } }) }, getOpenid(wxCode) { wx.request({ url: 'http://127.0.0.1/wxlogin/getOpenid.php/', data: { code: wxCode }, success(res) { console.log(res); }, fail(res) { console.log('获取失败', res) } }) }
服务器端:
//getOpenid.php文件(拼接url返回数据)
<?php include_once 'requestion.php'; include_once 'config.php'; getOpenid($appid, $appSecret); function getOpenid($appid, $appSecret) { $code = $_GET['code'];//小程序传来的code值 $wxUrl = 'https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code'; $getUrl = sprintf($wxUrl, $appid, $appSecret, $code);//把appid,appsecret,code拼接到url里 $result = curl_get($getUrl);//请求拼接好的url //return $result; $wxResult = json_decode($result, true); if (empty($wxResult)) { echo '获取openid时异常,微信内部错误'; } else { $loginFail = array_key_exists('errcode', $wxResult); if ($loginFail) {//请求失败 var_dump($wxResult); } else {//请求成功 $openid = $wxResult['openid']; $text=json_encode($wxResult); $myfile = fopen("hc.txt", "w") or die("Unable to open file!"); fwrite($myfile, $text); fclose($myfile); echo $openid; } } }
//requestion.php页面(封装了get和post请求)
<?php //发送get请求 function curl_get($url, &$httpCode = 0) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //不做证书校验,部署在linux环境下请改为true curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); $file_contents = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); return $file_contents; } //发送post请求 function curlPost($url,$data) { $ch = curl_init(); $params[CURLOPT_URL] = $url; //请求url地址 $params[CURLOPT_HEADER] = FALSE; //是否返回响应头信息 $params[CURLOPT_SSL_VERIFYPEER] = false; $params[CURLOPT_SSL_VERIFYHOST] = false; $params[CURLOPT_RETURNTRANSFER] = true; //是否将结果返回 $params[CURLOPT_POST] = true; $params[CURLOPT_POSTFIELDS] = $data; curl_setopt_array($ch, $params); //传入curl参数 $content = curl_exec($ch); //执行 curl_close($ch); //关闭连接 return $content; }
//config.php页面(配置文件)
<?php $appid = 'APPID';//小程序的appid $appSecret = 'SECRET';// 小程序的$appSecret
运行结果:
转载至:QSYQ_清殇论坛
1 对 “微信小程序 微信小程序获取openID”的想法;