微信的类文件
我写在weichat.php中
<?php
namespace app\common;
class Wechat {
//高级功能-》开发者模式-》获取
private $app_id = 'xxxxxxxxxxxxxxxxxxxx'; //公众号appid
private $app_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; //公众号app_secret
private $redirect_uri = 'http://www.xxxx.com/dovxlogin'; //授权之后跳转地址
/**
* 获取微信授权链接
*
* @param string $redirect_uri 跳转地址
* @param mixed $state 参数
*/
public function get_authorize_url($state)
{
$redirect_uri = urlencode($this->redirect_uri);
return "https://open.weixin.qq.com/connect/qrconnect?appid={$this->app_id}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_login&state={$state}#wechat_redirect";
}
/**
* 获取授权token
*
* @param string $code 通过get_authorize_url获取到的code
*/
public function get_access_token($code)
{
$token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->app_id}&secret={$this->app_secret}&code={$code}&grant_type=authorization_code";
$token_data = $this->https_request($token_url);
//return $token_data;
return json_decode($token_data, TRUE);
}
/**
* 获取授权后的微信用户信息
*
* @param string $access_token
* @param string $open_id
*/
public function get_user_info($access_token,$open_id)
{
if ($access_token && $open_id) {
$info_url = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$open_id}&lang=zh_CN";
$info_data = $this->https_request($info_url);
return json_decode($info_data, TRUE);
}
}
//https请求
public function https_request($url, $data = null)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
if (!empty($data)){
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
}
?>
controller中的方法
/**
* 第三方 微信登录
*/
public function VxLogin()
{
$weixin = new Wechat();
$url = $weixin->get_authorize_url('xxxxxx');
header("Location: ".$url."");
die;
}
/**
* 第三方 微信登录
*/
public function doVxLogin()
{
$weixin = new Wechat();
if (isset($_GET['code']))
{
$data = $weixin->get_access_token($_GET['code']);
//获取个人信息
$user = $weixin->get_user_info($data["access_token"],$data["openid"]);
// // 已经拿到各种信息 ,这里写你需要处理的方法
}else{
//没有openID的情况
//
}
}else{
echo "NO CODE";
}
}