PHP项目微信登录PHP端如何对接

wen PHP项目 28

本文目录导读:

PHP项目微信登录PHP端如何对接

  1. 准备工作
  2. 用户授权 - 获取code
  3. 回调处理 - 获取access_token和用户信息
  4. 完整封装类
  5. 使用示例
  6. 前端示例(HTML)
  7. 注意事项

我来详细说明PHP项目对接微信登录的完整流程:

准备工作

1 获取配置信息

在微信开放平台或公众号后台获取:

// 配置信息
define('WECHAT_APPID', 'your_appid');
define('WECHAT_APPSECRET', 'your_appsecret');
define('WECHAT_REDIRECT_URI', 'https://yourdomain.com/wechat/callback');

用户授权 - 获取code

前端跳转

<?php
// auth.php - 用户点击微信登录
$appid = WECHAT_APPID;
$redirect_uri = urlencode(WECHAT_REDIRECT_URI);
$state = md5(uniqid(rand(), true)); // 防止CSRF攻击
// 保存state到session用于验证
session_start();
$_SESSION['wechat_state'] = $state;
// 构建授权URL
$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_userinfo&state={$state}#wechat_redirect";
// 跳转到微信授权页面
header("Location: $url");
exit;
?>

回调处理 - 获取access_token和用户信息

1 回调接口

<?php
// callback.php - 微信回调处理
session_start();
// 获取code和state
$code = $_GET['code'] ?? '';
$state = $_GET['state'] ?? '';
// 验证state防止CSRF
if ($state !== $_SESSION['wechat_state']) {
    die('Invalid state parameter');
}
// 第一步:通过code获取access_token
$token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . WECHAT_APPID . 
             "&secret=" . WECHAT_APPSECRET . 
             "&code=" . $code . 
             "&grant_type=authorization_code";
$token_data = httpGet($token_url);
$token_result = json_decode($token_data, true);
if (isset($token_result['errcode'])) {
    die('获取access_token失败:' . $token_result['errmsg']);
}
$access_token = $token_result['access_token'];
$openid = $token_result['openid'];
// 第二步:获取用户信息
$userinfo_url = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $access_token . 
                "&openid=" . $openid . 
                "&lang=zh_CN";
$userinfo_data = httpGet($userinfo_url);
$userinfo = json_decode($userinfo_data, true);
// 处理用户登录逻辑
loginWithWechat($userinfo);
/**
 * 处理微信登录
 */
function loginWithWechat($userinfo) {
    $openid = $userinfo['openid'];
    // 检查用户是否已存在
    $user = findUserByOpenid($openid);
    if (!$user) {
        // 注册新用户
        $user = createUser([
            'openid' => $openid,
            'nickname' => $userinfo['nickname'],
            'avatar' => $userinfo['headimgurl'],
            'sex' => $userinfo['sex'],
            'country' => $userinfo['country'],
            'province' => $userinfo['province'],
            'city' => $userinfo['city'],
            'login_type' => 'wechat'
        ]);
    }
    // 生成登录token
    $token = generateToken($user['id']);
    // 保存登录状态
    $_SESSION['user'] = $user;
    $_SESSION['token'] = $token;
    // 跳转到首页或来源页面
    header("Location: /index.php");
    exit;
}
/**
 * HTTP GET请求
 */
function httpGet($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}
?>

完整封装类

<?php
// WechatLogin.php - 微信登录类
class WechatLogin {
    private $appid;
    private $appsecret;
    private $redirect_uri;
    public function __construct($config) {
        $this->appid = $config['appid'];
        $this->appsecret = $config['appsecret'];
        $this->redirect_uri = $config['redirect_uri'];
    }
    /**
     * 获取授权URL
     */
    public function getAuthUrl() {
        $state = md5(uniqid(rand(), true));
        $_SESSION['wechat_state'] = $state;
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize";
        $params = [
            'appid' => $this->appid,
            'redirect_uri' => $this->redirect_uri,
            'response_type' => 'code',
            'scope' => 'snsapi_userinfo',
            'state' => $state
        ];
        return $url . '?' . http_build_query($params) . '#wechat_redirect';
    }
    /**
     * 处理回调
     */
    public function handleCallback($code, $state) {
        // 验证state
        if ($state !== ($_SESSION['wechat_state'] ?? '')) {
            throw new Exception('Invalid state parameter');
        }
        // 获取access_token
        $token = $this->getAccessToken($code);
        // 获取用户信息
        $userinfo = $this->getUserInfo($token['access_token'], $token['openid']);
        return $userinfo;
    }
    /**
     * 获取access_token
     */
    private function getAccessToken($code) {
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token";
        $params = [
            'appid' => $this->appid,
            'secret' => $this->appsecret,
            'code' => $code,
            'grant_type' => 'authorization_code'
        ];
        $result = $this->httpGet($url, $params);
        $data = json_decode($result, true);
        if (isset($data['errcode'])) {
            throw new Exception('获取access_token失败:' . $data['errmsg']);
        }
        return $data;
    }
    /**
     * 获取用户信息
     */
    private function getUserInfo($access_token, $openid) {
        $url = "https://api.weixin.qq.com/sns/userinfo";
        $params = [
            'access_token' => $access_token,
            'openid' => $openid,
            'lang' => 'zh_CN'
        ];
        $result = $this->httpGet($url, $params);
        $data = json_decode($result, true);
        if (isset($data['errcode'])) {
            throw new Exception('获取用户信息失败:' . $data['errmsg']);
        }
        return $data;
    }
    /**
     * HTTP GET请求
     */
    private function httpGet($url, $params = []) {
        if (!empty($params)) {
            $url .= '?' . http_build_query($params);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            throw new Exception('CURL Error: ' . curl_error($ch));
        }
        curl_close($ch);
        return $result;
    }
}

使用示例

1 配置和路由

// index.php - 使用示例
require_once 'WechatLogin.php';
session_start();
// 配置
$config = [
    'appid' => 'your_appid',
    'appsecret' => 'your_appsecret',
    'redirect_uri' => 'https://yourdomain.com/callback.php'
];
$wechat = new WechatLogin($config);
// 微信登录入口
if (isset($_GET['action']) && $_GET['action'] == 'login') {
    $url = $wechat->getAuthUrl();
    header("Location: $url");
    exit;
}

2 回调处理

// callback.php - 回调处理
require_once 'WechatLogin.php';
session_start();
if (isset($_GET['code']) && isset($_GET['state'])) {
    try {
        $config = [
            'appid' => 'your_appid',
            'appsecret' => 'your_appsecret',
            'redirect_uri' => 'https://yourdomain.com/callback.php'
        ];
        $wechat = new WechatLogin($config);
        $userinfo = $wechat->handleCallback($_GET['code'], $_GET['state']);
        // 处理登录
        // $userId = your_login_function($userinfo);
        // 登录成功
        echo json_encode([
            'code' => 200,
            'message' => '登录成功',
            'data' => $userinfo
        ]);
    } catch (Exception $e) {
        echo json_encode([
            'code' => 500,
            'message' => $e->getMessage()
        ]);
    }
}

前端示例(HTML)

<!DOCTYPE html>
<html>
<head>微信登录</title>
</head>
<body>
    <a href="auth.php">
        <img src="wechat_login_btn.png" alt="微信登录">
    </a>
    <!-- 或者使用按钮 -->
    <button onclick="wechatLogin()">微信登录</button>
    <script>
    function wechatLogin() {
        window.location.href = 'auth.php?action=login';
    }
    </script>
</body>
</html>

注意事项

  1. 安全性:必须验证state参数防止CSRF攻击
  2. HTTPS:回调URL必须使用HTTPS
  3. 域名验证:需要先在微信开放平台配置授权域名
  4. access_token:有效期通常为2小时,refresh_token有效期为30天
  5. 用户信息:snsapi_userinfo需要用户授权才能获取详细信息

这样就完成了PHP端微信登录的基本对接!

抱歉,评论功能暂时关闭!