function getWxUrl($url, $param = null) {
if($param != null) {
$query = http_build_query($param);
$url = $url . '?' . $query;
}
$ch = curl_init();
if(stripos($url, "https://") !== false){
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
$content = curl_exec($ch);
$status = curl_getinfo($ch);
curl_close($ch);
if(intval($status["http_code"]) == 200) {
return $content;
}else{
echo $status["http_code"];
return false;
}
}
function getWxAll(){
if(!strpos($_SERVER['HTTP_USER_AGENT'],"MicroMessenger")){echo '请在微信中打开1'; exit();}
$AppID = C("Wx_appid"); $AppSecret = C("Wx_token");
$url = urlencode('http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
$openid_cookiename = substr(md5($_SERVER['HTTP_USER_AGENT'].get_client_ip()),8,8);
$openid = cookie($openid_cookiename);
//$openid = ""; //这里是测试的时候用的 测试的时候打开
if(empty($openid)){
$codeid = $_GET['code'];
if(empty($codeid)){
//echo "a";
Redirect('https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$AppID.'&redirect_uri='.$url.'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect');
exit();
}else{
//echo "b";
$response = getWxCode($codeid);
if($response == false) {
return false;
}
$user = $response;
// dump($user);die;
if (isset($user->error) || $user->openid == "") {
echo '请在微信中打开2'; exit();
}
$openid = $user->openid;
if(empty($openid)){echo '请在微信中打开3';exit();}
cookie($openid_cookiename,$openid,30*24*60*60);
}
}
}
//通过第三方获取CODE用户基本信息(未关注也可以获取)
function getWxCode($code){
$AppID = C("Wx_appid"); $AppSecret = C("Wx_token");
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$AppID."&secret=".$AppSecret."&code=".$code."&grant_type=authorization_code";
$res = getWxUrl($url);
$data = json_decode($res, true);
$scope = $data['scope'];
//当为弹出授权时
if ($scope == 'snsapi_userinfo'){
$access_token = $data['access_token'];
$openid = $data['openid'];
$url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid;
$res = getWxUrl($url);
}
return json_decode($res, true);
}
声明:此文系舞林cuzn(www.wulinlw.org)原创稿件,转载请保留版权