Skip to content

Instantly share code, notes, and snippets.

@edk24

edk24/Login.php Secret

Created November 16, 2023 16:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edk24/e8c368ea548a4d209876ded94828a8f3 to your computer and use it in GitHub Desktop.
Save edk24/e8c368ea548a4d209876ded94828a8f3 to your computer and use it in GitHub Desktop.
微信公众号授权登录处理类库
<?php
namespace library\wechat;
use RuntimeException;
class Login {
protected $appid;
protected $appsenret;
public function __construct(string $appid, string $appsenret)
{
$this->appid = $appid;
$this->appsenret = $appsenret;
}
/**
* 生成授权登录地址
*
* @param string $scope 授权类型: snsapi_base 静默 | snsapi_userinfo 完全
* @param string $redirect_uri 重定向地址
* @return string
* @link https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html
*/
public function buildAuthorizeUrl(string $scope = 'snsapi_userinfo', string $redirect_uri): string
{
$redirect_uri = urlencode($redirect_uri);
$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=STATE#wechat_redirect";
$url = sprintf($url, $this->appid, $redirect_uri, $scope);
return $url;
}
/**
* code换access_token
*
* @param string $code
* @return array 返回 array($access_token, $openid)
* @link https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html
*/
public function code2accessToken(string $code): array
{
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
$url = sprintf($url, $this->appid, $this->appsenret, $code);
$response = json_decode(file_get_contents($url), true);
if (!isset($response['access_token'])) {
throw new RuntimeException('微信授权失败: ' . json_encode($response));
}
return [$response['access_token'], $response['openid']];
}
/**
* 获取用户信息
*
* @param string $access_token
* @param string $openid
* @return array
* @link https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html
*/
public function getUserInfo($access_token, $openid): array
{
$url = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN";
$url = sprintf($url, $access_token, $openid);
$response = json_decode(file_get_contents($url), true);
if (!isset($response['openid'])) {
throw new RuntimeException('微信获取用户信息失败: ' . json_encode($response));
}
return $response;
}
}
@edk24
Copy link
Author

edk24 commented Nov 16, 2023

使用方法

接口部分

// 跳转登录
public function jumpLogin() {
        $appid = env('WEIXIN.APPID');
        $appsenret = env('WEIXIN.APPSENRET');

        $h5 = new Login($appid, $appsenret);
        $url = $h5->buildAuthorizeUrl('snsapi_userinfo', url('/api/user/login', [], false, true)->build()); // thinkphp8
        // $url = $h5->buildAuthorizeUrl('snsapi_userinfo', 'http://192.168.10.67:5173/api/user/login');

        return redirect($url);
}

// 通过openid登录
    public function login(string $code)
    {
        $appid = env('WEIXIN.APPID');
        $appsenret = env('WEIXIN.APPSENRET');

        $h5 = new Login($appid, $appsenret);
        list($access_token, $openid) = $h5->code2accessToken($code);
        $wxuser = $h5->getUserInfo($access_token, $openid);

        $user = UserModel::where('openid', $openid)->find();
        if (!$user) { // 不存在, 创建新用户
            $user = new UserModel();
            $user->setAttr('openid', $openid);
            $user->setAttr('nickname', $wxuser['nickname']);
            $user->setAttr('avatar', $wxuser['headimgurl']);
            $user->setAttr('gender', $wxuser['sex']);
            $user->setAttr('nickname', $wxuser['nickname']);
            $user->save();
        }

        session('uid', $user->id);
    }


// 获取用户信息
 public function getUser()
{
    // 此处通过 session 获取用户id  查询用户信息返回即可,  找不到返回特殊code, 前端用于判断
}

接口

  • jumpLogin 跳转登录
  • login 网页code授权
  • getUser 获取用户信息

前端部分

// 程序入口, 如uniapp的 onLaunch
getUser()
    .then((res) => {
        if (res.code == 4008) { // 用户未登录
            window.location.href = '/api/user/jumpLogin' // 跳转授权登录
        }
    })

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment