基类
<?php
/**
* User: Eden
* Date: 2019/3/21
* 共有内容
*/
namespace CommonService;
use VendorFuncHttp;
class AliService extends CommonService
{
public function __construct()
{
parent::__construct();
}
/**
* 获取access_token
* appkey
* appsecret
*/
public function getAccessToken($appkey = '', $appsecret = '')
{
$appkey = $appkey ?:C('ALI.APP_KEY');
$appsecret = $appsecret ?:C('ALI.APP_SECRET');
// 查询缓存中是否存在
$key = "ali_access_token_" . $appkey;
$ttl = $this->red->ttl($key);
if ($ttl == -2) { // 不存在
// step1 获取
$request_url = C('ALI.OAPI_HOST')."/gettoken?";
$request_url .= "appkey=" . $appkey . "&appsecret=" . $appsecret;
$data = json_decode(Http::doGet($request_url, 5), true);
// step2 存储
$this->red->setex($key, $data['expires_in'] - 1000, $data['access_token']);
return $data['access_token'];
} else {
return $this->red->get($key);
}
}
/**
* 获取用户信息
*/
public function getUserInfo($access_token, $code)
{
// step1 获取
$request_url = C('ALI.OAPI_HOST')."/user/getuserinfo";
$params = [
'access_token' => $access_token,
'code' => $code
];
$data = json_decode(Http::newDoGet($request_url,$params, 5), true);
return $data;
}
/**
* 获取用户信息
*/
public function getUser($access_token, $userid)
{
// step1 获取
$request_url = C('ALI.OAPI_HOST')."/user/get";
$params = [
'access_token' => $access_token,
'userid' => $userid
];
$data = json_decode(Http::newDoGet($request_url,$params, 5), true);
return $data;
}
}
登录
<?php
namespace ApiAction;
use CommonServiceAliService;
/**
* 需要登录的接口页面,从这里进入
* Class LoginAction
*/
class LoginAction extends CommonAction
{
public function _initialize()
{
parent::_initialize();
}
public function login() {
$aliService = new AliService();
$access_token = $aliService->getAccessToken();
$code = $_POST['authCode'];
$res = $aliService->getUserInfo($access_token,$code);
if ($res['errcode'] != 0) { // 获取成功
$this->json->E($res['errmsg']);
}
$userid = $res['userid'];
$user_res = $aliService->getUser($access_token,$userid);
if ($user_res['errcode'] != 0) { // 获取成功
$this->json->E($user_res['errmsg']);
}
$out_data = [
'userid' => $userid,
'name' => $user_res['name'],
'avatar' => $user_res['avatar'],
'openId' => $user_res['openId'],
'unionid' => $user_res['unionid'],
'mobile' => $user_res['mobile'],
];
$this->json->S($out_data);
}
}