版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wanghao725/article/details/52883384
//获取微信授权
function getOpenidDirectly($scope = 'snsapi_base'){
$appid = C('APPID');
$secret = C('APPSECRET');
$host = C('HOST');
$code = isset($_REQUEST['code'])?$_REQUEST['code']:'';
$state = isset($_REQUEST['state'])?$_REQUEST['state']:'';
//获取当前完整url
$redirect_uri = $host.$_SERVER['REQUEST_URI'];
$redirect_uri = UrlUnsetParam(array('code','scope','state'), $redirect_uri);
if(!$code || $scope != $state){
getWeixinCode($scope, $redirect_uri);
}else{
if($state=='snsapi_base'){
$openid = getOpenid($code);
if(!$openid){ //如果没取成功则再去取,直到取到为止
getWeixinCode('snsapi_base',$redirect_uri);
}
}else if($state=='snsapi_userinfo'){
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$secret."&code=".$code."&grant_type=authorization_code";
$return = curl_post_json($url);
$return = json_decode($return);
//echo '<pre>';print_r($return);exit('ddd');
return $return;
}
}
return $openid;
}
function getWeixinCode($snsaiptype,$redirect_uri){
$appid = C('APPID');
$secret = C('APPSECRET');
$host = C('HOST');
//获取code
//$redirect_uri = urlencode(get_url());
if(!$redirect_uri){
$redirect_uri = $host.$_SERVER['REQUEST_URI'];
}
$redirect_uri = urlencode($redirect_uri);
$get_code = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_uri."&response_type=code&scope=".$snsaiptype."&state=".$snsaiptype."#wechat_redirect ";
header("location:$get_code");
exit;
}
//获取Openid
function getOpenid($code){
$appid = C('APPID');
$secret = C('APPSECRET');
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$secret."&code=".$code."&grant_type=authorization_code";
$return = curl_post_json($url);
$return = json_decode($return);
return $return->openid;
}
//获取用户信息
function getAuthUserInfo($token, $openid,$lang='zh_CN'){
$url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$token."&openid=".$openid."&lang=".$lang;
$weixinUserinfo = curl_post_json($url);
$return = json_decode($weixinUserinfo);
return $return;
}
//去掉URL中的参数
function UrlUnsetParam($paramArray,$url) {
if($paramArray){
foreach ($paramArray as $val){
$url = preg_replace(
array("/{$val}=[^&]*/i", '/[&]+/', '/\?[&]+/', '/[?&]+$/',),
array('', '&', '?','',),
$url
);
}
}
return $url;
}