/*
* 获取公众号的openid
*/
public function test()
{
$param = $this->request->param();
$config = [
'appid' => '',//公众号的appid
'secret' => '',//公众号的secret
];
if (!isset($param['code']) || $param['code'] == '') {
$code_data = [];
$code_data['appid'] = $config['appid'];
//后面的方法根据自己的情况,自行填写
$code_data['redirect_uri'] = 'http://' . $_SERVER['HTTP_HOST'] . '/cn/pay/test?' . http_build_query($_GET);
$code_data['response_type'] = 'code';
$code_data['scope'] = 'snsapi_base';
$code_data['state'] = '';
$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?' . http_build_query($code_data) . '#wechat_redirect';
header('location:' . $url);
}
$code = $param['code'];
$openid_data = [];
$openid_data['appid'] = $config['appid'];
$openid_data['secret'] = $config['secret'];
$openid_data['code'] = $code;
$openid_data['grant_type'] = 'authorization_code';
$openid_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?' . http_build_query($openid_data);
$res = json_decode(file_get_contents($openid_url), true);
if (isset($res['openid'])) {
$getUserInfo = $this->getUserInfo($res['openid']);
if (empty($getUserInfo['unionid'])){
$this->error('请关注公众号!');
return;
}else{
$data=[
'openid' => $res['openid'],
];
$this->success('获取成功',$data);
}
} else {
$this->error('获取失败');
}
}
// 获取用户信息
function getUserInfo($openid)
{
$accessToken = $this->getAccessToken();
$url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $accessToken . "&openid=" . $openid . "&lang=zh_CN";
$response = file_get_contents($url);
$result = json_decode($response, true);
return $result;
}
// 获取 access_token
function getAccessToken()
{
// 公众号的 appid 和 appsecret
$appid = "";
$appsecret = "";
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $appsecret;
$response = file_get_contents($url);
$result = json_decode($response, true);
return $result['access_token'];
}
php 获取微信公众号用户信息
最新推荐文章于 2024-07-26 16:23:00 发布