public function wechatAuth()
{
//授权登录基于oauth2.0
//微信授权H5网页移动应用在手机端打开必须申请公众号
//第一步与微信交互换取code
$pid = $_GET['pid'];//自定义参数放到state中 此处传入二维码的上级id
//应用Appid
$appid = "";
$toredirect = urlencode("http://xyp.pingtouge9.com/php/home/login.php?path=wechatRegister");//回调地址 对URL编码
//此处的scope使用时应该注意
//如果是微信公众号获取微信授权信息scope=snsapi_userinfo或者scope=snsapi_base(静默授权,只能拿到openid,不需要用户同意)
//如果是微信网页移动应用授权scope=snsapi_login
header("Location:https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $appid . "&redirect_uri=" . $toredirect . "&response_type=code&scope=snsapi_userinfo&state=" . $pid . "#wechat_redirect");
}
//微信扫码回调地址
public function wechatRegister()
{
//第二步使用code换取access_token
//$code是回调的时候地址上带的 只需要get方式接收就可以了
$code = $_GET["code"];
//获取自定义参数,state用于传递自己的自定义参数
$pid = $_GET["state"];
$appid = "";//应用Appid
$appSecret = "";//应用密钥
$openurl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$appSecret&code=$code&grant_type=authorization_code";
$globalaccesObj = json_decode(curlGet($openurl));
//第三步获取微信用户详细信息
$userUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $globalaccesObj->access_token . "&openid=" . $globalaccesObj->openid . "&lang=zh_CN";
$wechatUserInfo = json_decode(curlGet($userUrl));//获取到微信基本用户
$wechatUserInfo = to_array($wechatUserInfo);
**//如果您的返回信息没有unionid,那就请先去将本应用绑定微信开放平台**
//TODO 业务逻辑
}
//用到的另外两个函数
//php get请求
function curlGet($url, $method = 'get', $data = '') {
$ch = curl_init ();
$header = "Accept-Charset: utf-8";
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, strtoupper ( $method ) );
curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, FALSE );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $header );
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_POSTFIELDS, $data );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
$temp = curl_exec ( $ch );
// 释放curl句柄
curl_close ( $ch );
return $temp;
}
function to_array($obj){
// 定义空数组
$data = array();
// 循环遍历对象,对数组赋值
foreach ($obj as $key => $value) {
$data[$key] = $value;
}
// 打印数组
return $data;
}
PHP获取微信授权信息
最新推荐文章于 2022-08-22 10:15:45 发布