//原生
use EasyWeChat\Foundation\Application;
use Ws\Http\Request;
public function wx_login()
{
$code = input('post.code');
if (is_null($code)) {
$this->returnAPI('微信登录失败');
}
$http = Request::create();
$resp = $http->get('https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . config('wechat.app_id') . '&secret=' . config('wechat.secret') . '&code=' . $code . '&grant_type=authorization_code');
$res = json_decode($resp->raw_body, true);
if (isset($res['errcode'])) {
trace('微信登录失败' . $resp->raw_body);
$this->returnAPI('微信登录失败');
}
$user = model('user')->get(['wx_openid' => $res['openid']]);
if (is_null($user)) {
$resp = $http->get('https://api.weixin.qq.com/sns/userinfo?access_token=' . $res['access_token'] . '&openid=' . $res['openid']);
$res = json_decode($resp->raw_body, true);
if (isset($res['errcode'])) {
trace('微信获取用户个人信息失败' . $resp->raw_body);
$this->returnAPI('微信登录失败');
}
cache('wx_user_info_' . $res['openid'], $resp->raw_body);
$this->returnAPI('', 2, ['openid' => $res['openid']]);
}
$this->log_suc($user, '登录成功');
}
//
use Wechat\Wechat;
/**
* @api {get} api/index/wxLogin
* @apiName 微信登录
* @apiGroup 注册登录
* @apiParam {string} code
*/
public function wxLogin($code, UserModel $userModel)
{
return outJson('', 0, "请升级到最新版本");
$wechat = new Wechat(config('wechat.open_platform.default'));
$wx = $wechat->wxAccesstoken($code);
if (isset($wx['errcode']) && $wx['errcode'] > 0) {
return outJson('', 0, $wx['errmsg']);
}
$return = [];
if (isset($wx['unionid']) && !empty($wx['unionid'])) {
$res = $userModel->dologin(['union_id', $wx['unionid']]);
$return['unionid'] = $wx['unionid'];
} else {
$res = $userModel->dologin(['openid', $wx['openid']]);
}
$return['openid'] = $wx['openid'];
if ($res['status'] != 1) {
//昵称
$us = $wechat->getUserInfo($wx['access_token'], $wx['openid']);
$return['nickname'] = $us['nickname'];
return outJson($return, 0, "请完善信息以完成注册");
}
return outJson($res['data'], 1, '登录成功');
}