You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
86 lines
2.9 KiB
86 lines
2.9 KiB
<?php
|
|
defined('BASE_PATH') or exit('No direct script access allowed');
|
|
|
|
class wechat
|
|
{
|
|
|
|
private $wechat = '';
|
|
|
|
/**
|
|
* 构造函数
|
|
*
|
|
* @param unknown $config
|
|
*/
|
|
public function __construct($config)
|
|
{
|
|
$options = array(
|
|
'appid' => $config['app_id'],
|
|
'appsecret' => $config['app_secret'],
|
|
);
|
|
$this->wechat = new \vendor\Wechat($options);
|
|
}
|
|
|
|
/**
|
|
* 获取授权地址
|
|
*/
|
|
public function redirect($callback_url)
|
|
{
|
|
return $this->wechat->getOauthRedirect($callback_url, 'wechat_oauth');
|
|
}
|
|
|
|
/**
|
|
* 回调用户数据
|
|
*/
|
|
public function callback($callback_url, $code)
|
|
{
|
|
// code参数有时效性 若不为空 则证明已经授权登录
|
|
if (! empty($code)) {
|
|
$token = $this->wechat->getOauthAccessToken();
|
|
$userinfo = $this->wechat->getOauthUserinfo($token['access_token'], $token['openid']);
|
|
if (! empty($userinfo)) {
|
|
$_SESSION['openid'] = $userinfo['openid'];
|
|
$data = array(
|
|
'openid' => basename(__FILE__, '.php') . '_' . $userinfo['openid'],
|
|
'name' => $userinfo['nickname'],
|
|
'sex' => $userinfo['sex'],
|
|
'avatar' => $userinfo['headimgurl']
|
|
);
|
|
//更新粉丝信息
|
|
$controller = '\apps\wechat\controllers\IndexController';
|
|
if(class_exists($controller))$this->updateInfo($userinfo);
|
|
return $data;
|
|
} else {
|
|
return false;
|
|
}
|
|
} else {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 粉丝信息更新
|
|
*/
|
|
private function updateInfo($userinfo = array()){
|
|
if(!empty($userinfo)){
|
|
$info = model()->table('wechat_user')->field('openid, ect_uid')->where(array('openid'=>$userinfo['openid']))->find();
|
|
if(!empty($info)){
|
|
$ect_uid = 0;
|
|
if(empty($info['ect_uid']) && isset($userinfo['unionid'])){
|
|
$ect_uid = model()->table('wechat_user')->field('ect_uid')->where(array('unionid'=>$userinfo['unionid']))->one();
|
|
}
|
|
$userinfo['ect_uid'] = $ect_uid;
|
|
model()->table('wechat_user')->data($userinfo)->where(array('openid'=>$info['openid']))->update();
|
|
}
|
|
else{
|
|
$ect_uid = 0;
|
|
if(isset($userinfo['unionid'])){
|
|
$ect_uid = model()->table('wechat_user')->field('ect_uid')->where(array('unionid'=>$userinfo['unionid']))->one();
|
|
}
|
|
$userinfo['ect_uid'] = $ect_uid;
|
|
$userinfo['wechat_id'] = 1;
|
|
model()->table('wechat_user')->data($userinfo)->insert();
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
}
|
|
|