<?php
function getOpenid($appid,$appSecret,$code) {
$code = $code;
$appid = $appid;
$appSecret = $appSecret;
$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);
$result = curl_get($getUrl);
$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'];
echo $openid;
}
}
}
function curl_get($url, &$httpCode = 0) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
$file_contents = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $file_contents;
}
getOpenid('AccessKeyId','AccessKeySecret',$_GET['code']);
?>