HaniBlindBox/server/php/app/common/server/AppWechat.php
2026-01-01 20:46:07 +08:00

96 lines
2.7 KiB
PHP

<?php
namespace app\common\server;
class AppWechat
{
private $wx_appid = "wx112eed47787bcc0a";
private $wx_secret = "6fcc2b8fd22595bd88889157ad9cddd9";
/**
* 获取用户基础信息
* @param mixed $code
* @return array|\think\response\Json
*/
public function getAccessToken($code)
{
//connect/oauth2/authorize
//https://open.weixin.qq.com/connect/oauth2/authorize
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $this->wx_appid . "&secret=" . $this->wx_secret . "&code=" . $code . "&grant_type=authorization_code";
$resUserInfo = $this->get_curl_data($url);
if (isset($resUserInfo['errcode'])) {
return null;
}
$openid = $resUserInfo['openid'];#openid
$access_token = $resUserInfo['access_token']; # 7200
$unionid = ''; # 7200
if (isset($resUserInfo['unionid'])) {
$unionid = $resUserInfo['unionid'];
}
$data = [
'openid' => $openid,
'unionid' => $unionid,
'access_token_time' => $access_token,
];
return $data;
}
/**
* 拉取用户信息(需scope为 snsapi_userinfo)
* @param mixed $data
* @return mixed
*/
public function getUserInfo($data)
{
$openid = $data['openid'];
$access_token = $data['access_token_time'];
//connect/oauth2/authorize
$url = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $access_token . "&openid=" . $openid . "&lang=zh_CN";
$resUserInfo = $this->get_curl_data($url);
if (isset($resUserInfo['errcode'])) {
return null;
}
$user = $resUserInfo;#openid
return $user;
}
public function getAccountUserInfo($code)
{
$account = $this->getAccessToken($code);
if ($account) {
return $this->getUserInfo($account);
}
return null;
}
/**
* @param $url 请求链接
*/
public function get_curl_data($url)
{
$headerArray = array("Content-type:application/json;", "Accept:application/json");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
$response = curl_exec($ch);
if ($response) {
curl_close($ch);
return json_decode($response, true);
} else {
$error = curl_errno($ch);
curl_close($ch);
return ['errcode' => 1];
}
}
}