微信网页授权获取用户基本信息(snsapi_userinfo)

本文介绍如何使用snsapi_userinfo权限在微信网页授权中获取用户的详细信息,包括配置config.php文件,设置appid和appsecret。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

snsapi_userinfo方式获取用户信息


config.php 存放appid和appsecret

<?php

$config = [
    'appid' => '************',
    'appsecret' => '*******************',
];

test.php跳转并获取code
<?php
require_once './config.php';

$appid = $config['appid'];
$redirect_uri = urlencode('http://www.haoyiya.cn/weixin/auth.php');

//授权url
$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";

//如果用户同意授权,页面将跳转至 redirect_uri/?code=CODE&state=STATE。
header("location:$url");
exit;


auth.php获取用户信息
<?php
header("Content-type:text/html;charset=utf-8");
require_once './config.php';

//获取code
if (isset($_GET['code'])){
    $code = $_GET['code'];
}else{
    die("NO CODE");
}


$obj = new snsapi_userinfo;
//获取access_token和openid
$res = $obj->access_token($config['appid'],$config['appsecret'],$code);
//获取用户信息
$userInfo = $obj->userInfo($res->access_token,$res->openid);

//输出用户信息
echo "<h1>";
print_r($userInfo);
echo "</h1>";


/**
 * Class snsapi_userinfo
 * 获取用户信息
 */
class snsapi_userinfo{

    //获取access_token和openid
    public function access_token($appid,$appsecret,$code){
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code";
        $res = json_decode($this->httpGet($url));

        return $res;
    }

    public function userInfo($access_token,$openid){
        $userUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
        $res = json_decode($this->httpGet($userUrl));

        return $res;
    }

    //curl方式获取返回值
    public function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);
        curl_setopt($curl, CURLOPT_URL, $url);

        $res = curl_exec($curl);
        curl_close($curl);

        return $res;
    }
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值