获取微信相关资料

<?php
namespace Home\Controller;
use Think\Controller;
class UserController extends Controller {
public function index(){

$code = I("get.code");

if(!empty($code)){
$appid = "wxbd578791349a4ce8";
$appsecret = "9128ea15137fc672d5431709ec1aff95";
if(!empty($appid) && !empty($appsecret)){
$tokenData = $this->GetOpenid($code,$appid,$appsecret); //通过code换取网页授权access_token
if(!empty($tokenData)){
$arrData = explode("*",$tokenData);
$wxid = $arrData[0]; //openid
$access_token_ = $arrData[1]; //access_token
}
}
}else{
$url = "你的网址";
$code_url = urlencode($url);
$wechat_url= 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$code_url.'&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect';
header('Location:'.$wechat_url);
}

if(strlen($wxid) == 28){
if(!empty($access_token_)){
$user_wecha = $this->getUser($access_token_,$wxid);
$user_wecha = explode("*",$user_wecha);
}
}


// 获取用户信息
function getUser($token,$openId)
{
$url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$token."&openid=".$openId."&lang=zh_CN";
$result = $this->getData_($url);
$jsondecode = json_decode($result);
if($jsondecode != null){
if(property_exists ( $jsondecode, "headimgurl" ) )
{
$headimgurl = $jsondecode->{"headimgurl"};
}


if(property_exists ( $jsondecode, "nickname" ) )
{
$nickname = $jsondecode->{"nickname"};
}
if(property_exists ( $jsondecode, "subscribe_time" ) )
{
$subscribe_time = $jsondecode->{"subscribe_time"};
}
if(property_exists ( $jsondecode, "sex" ) )
{
$sex = $jsondecode->{"sex"};
}
return $headimgurl."*".$nickname."*".$subscribe_time."*".$sex;

}

}


//获取微信的openid
function GetOpenid($c_code,$appId,$ser)
{
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appId."&secret=".$ser."&code=".$c_code."&grant_type=authorization_code";
$result = $this->getData_($url);
$jsondecode = json_decode($result);
if($jsondecode != null){
if(property_exists ( $jsondecode, "openid" ) )
{
$openid = $jsondecode->{"openid"};
}
if(property_exists ( $jsondecode, "access_token" ) )
{
$access_token_ = $jsondecode->{"access_token"};
}
return $openid."*".$access_token_;
}

return null;
}


//获取https的get请求结果
function getData_($c_url)
{
$curl = curl_init(); // 启动一个CURL会话
curl_setopt($curl, CURLOPT_URL, $c_url); // 要访问的地址
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
$tmpInfo = curl_exec($curl); // 执行操作
if (curl_errno($curl)) {
echo 'Errno'.curl_error($curl);//捕抓异常
}
curl_close($curl); // 关闭CURL会话
return $tmpInfo; // 返回数据
}

$this->display();
}
}

posted @ 2016-11-10 15:32  流年沉默的如此苍凉╰╮  阅读(327)  评论(0)    收藏  举报