欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

如何用PHP获取微信用户的openid和基本信息?

程序员文章站 2022-03-26 11:04:53
基本配置 public function getcode(){ //基本配置 $appid=''; $redirect_uri=...

基本配置

public function getcode(){
    //基本配置
    $appid='';
    $redirect_uri=urlencode("https://授权回调页面域名/plugs/task/getuserinfo");
    $url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
    header("location:".$url);
}

获取信息

public function getuserinfo(){
    $appid  = "";
    $secret = "";

    //这里获取到了code
    $code   = $_GET['code'];

    //第一步:取得openid
    $oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$secret."&code=".$code."&grant_type=authorization_code";
    $oauth2 = $this->http_curl($oauth2Url);
    //accestoken
    $access_token = $oauth2["access_token"];
    //openid
    $openid = $oauth2['openid'];


    //第二步:根据全局access_token和openid查询用户信息
    $get_user_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
    $userinfo = $this->http_curl($get_user_info_url);

    dump($userinfo);
    //打印用户信息

}

curl请求

function http_curl($url){
    //用curl传参
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);

    //关闭ssl验证
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);


    curl_setopt($ch,CURLOPT_HEADER, 0);
    $output = curl_exec($ch);
    curl_close($ch);
    return json_decode($output, true);
}