天天看点

destoon获取微信公众号用户的openid

//获取用户的openid

$session = new dsession();

$openid = $_SESSION[‘wxopenid’];

if(empty( $openid))

{

o a u t h = n e w o a u t h ( ) ; i f ( ! e m p t y ( oauth = new oauth(); if (!empty( oauth=newoauth();if(!empty(_GET[‘code’])) {

$openid = $oauth->GetOpenid();

$_SESSION[‘wxopenid’] = $openid;

}

else{

$oauth->GET_Code();

}

}

class oauth {

public $appid = 'XXXXXXXXXXXXXXXXX';
public $secret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXX';

//获取用户openid
public function GetOpenid() {
    $get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $this->appid . '&secret=' . $this->secret . '&code=' . $_GET['code'] . '&grant_type=authorization_code';
    $json_obj = $this->https_request($get_token_url);
    $openid = $json_obj['openid'];
    return $openid;
}

//发起获得code值链接
public function GET_Code() {
    $get_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $this->appid;
    $url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    header("location:" . $get_url . "&redirect_uri=" . $url . "&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect");
}


//通用数据处理方法
public function https_request($get_token_url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $get_token_url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $temp = curl_exec($ch);
    return json_decode($temp, true);
}
           

}

继续阅读