话不多说,直接上代码,仅限于fastadmin使用,其他的可能需要修改一下
/**
* @ApiTitle (微信登录)
* @ApiMethod (POST)
* @ApiParams (name="code", type="string", required=true, description="微信code")
*/
public function wxLogin()
{
$rules = [
'code' => 'require',
];
$message = [
'code.require' => 'code不能为空',
];
$validate = new \think\Validate($rules, $message);
$param = $this->request->param();
if (!$validate->check($param)) {
$this->error($validate->getError());
}
$config = \addons\wechat\library\Config::load();
$tokenResult = $this->getMpAccessTokenAndOpenid($param['code'], $config['app_id'], $config['secret']);
if (!$tokenResult || !isset($tokenResult['access_token'], $tokenResult['openid'])) {
$this->error("微信公众号登录失败");
}
$access_token = $tokenResult['access_token'];
$openid = $tokenResult['openid'];
$unionid = isset($tokenResult['unionid']) ? $tokenResult['unionid'] : '';
$userInfo = $this->getUserInfoFromWeixin($access_token, $openid);
$data = [
'openid' => $openid,
'unionid' => $unionid,
'userinfo' => [
'nickname' => $userInfo['nickname'] ?? '默认昵称',
'avatar' => $userInfo['headimgurl'] ?? '',
'unionid' => $unionid,
],
'access_token' => $access_token,
'refresh_token' => '',
'expires_in' => 0,
];
$extend = ['group_id' => 1, 'gender' => '1', 'is_third' => 1, 'openid' => $openid];
$ret = Service::connect('mp', $data, $extend);
if ($ret) {
$auth = Auth::instance();
$this->success("登录成功", ['userInfo' => $auth->getUserinfo(), 'sessionKey' => $tokenResult]);
} else {
$this->error("连接失败");
}
}
private function getMpAccessTokenAndOpenid($code, $appId, $appSecret)
{
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appId}&secret={$appSecret}&code={$code}&grant_type=authorization_code";
$res = $this->httpRequest($url,'get');
return json_decode($res, true);
}
private function getUserInfoFromWeixin($access_token, $openid)
{
$userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}&lang=zh_CN";
$userInfoResponse = $this->httpRequest($userInfoUrl,'get');
return json_decode($userInfoResponse, true);
}
1985

被折叠的 条评论
为什么被折叠?



