You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 

250 lines
7.4 KiB

<?php
declare(strict_types=1);
/**
* WxService.php
* Created by PhpStorm.
* Date: 2026/10/17
* Time: 09:40
* Author: qian.guo
* E-mail: yiyezhiqiutel@gmail.com
*/
namespace app\service;
use app\BusinessException;
/**
* 微信小程序接口封装
* 设计说明:
* - 目前只需一个能力:code2Session,用 wx.login 的 code 换 openid
* openid 是小程序内的用户唯一身份,登录链路的一切都建立在它上面
* - 刻意不落盘 session_key:当前流程不需要解密 encryptedData
* 存一个敏感密钥只是扩大泄漏面,真要用时再按需取用
* - mock 模式用于开发期无凭据时跑通链路,生产开启会直接抛异常(见 checkMockAllowed)
* - 参数非空/长度不做校验,由前端负责(规范 8.3)
* code 不合法时微信会返回错误码,这里映射成业务异常,控制器统一出 400
*/
class WxService
{
// 微信侧表示「code 无效 / 已使用 / 频率超限 / 风险控制」的错误码,都归为同一类用户可恢复错误
const CODE_ERRCODES = [40029, 40163, 45011, 40226];
// 微信配置
private $config;
// 是否调试模式,用于拦住「生产开着 mock」这种致命配置
private $is_debug;
public function __construct($config, $is_debug = false)
{
$this->config = $config;
$this->is_debug = $is_debug;
}
/**
* code 换 openid
* code2Session
* @param string $code wx.login 返回的登录凭证
* @return array 含 openid 与 unionid
*/
public function code2Session($code)
{
if (!empty($this->config['mock'])) {
$this->checkMockAllowed();
$data = [];
$data['openid'] = $this->createMockOpenid($code);
$data['unionid'] = '';
return $data;
}
return $this->requestCode2Session($code);
}
/**
* 是否 mock 模式
* isMock
* @return bool
*/
public function isMock()
{
return !empty($this->config['mock']);
}
/**
* 校验是否允许使用 mock 模式
* checkMockAllowed
* @return void
*
* 这里选择直接抛异常而不是打日志继续跑:靠人「记得关掉 mock」不可靠
* 而一旦漏关就是全站身份可伪造。宁可生产直接不可用,也不能静默不安全
*/
private function checkMockAllowed()
{
if ($this->is_debug) {
return;
}
throw new BusinessException(
config('code.err.server_busy'),
'WX_MOCK 只能在 APP_DEBUG=true 时开启,请配置真实 WX_APPID / WX_SECRET'
);
}
/**
* 生成 mock openid
* createMockOpenid
* @param string $code 登录凭证
* @return string
*
* 同一 code 必得同一 openid,便于本地重复登录与自动化测试
* 用 hash 而非自增:openid 会出现在日志与响应里,不应可被枚举推算
*/
private function createMockOpenid($code)
{
return 'mock_' . substr(hash('sha256', 'zhunxin|' . $code), 0, 24);
}
/**
* 请求微信 code2session 接口
* requestCode2Session
* @param string $code 登录凭证
* @return array 含 openid 与 unionid
*/
private function requestCode2Session($code)
{
$appid = (string) ($this->config['appid'] ?? '');
$secret = (string) ($this->config['secret'] ?? '');
if ($appid === '' || $secret === '') {
throw new BusinessException(
config('code.err.server_busy'),
'未配置 WX_APPID / WX_SECRET,请在 .env 中填写后重试'
);
}
$param = [];
$param['appid'] = $appid;
$param['secret'] = $secret;
$param['js_code'] = $code;
$param['grant_type'] = 'authorization_code';
$api_base = (string) ($this->config['api_base'] ?? 'https://api.weixin.qq.com');
$url = rtrim($api_base, '/') . '/sns/jscode2session?' . http_build_query($param);
$body = $this->getUrl($url, intval($this->config['timeout'] ?? 5));
$data = json_decode($body, true);
if (!is_array($data)) {
throw new BusinessException(config('code.err.wx_api_error'), '微信接口返回无法解析');
}
if (!empty($data['errcode'])) {
$this->throwWxError(intval($data['errcode']), (string) ($data['errmsg'] ?? ''));
}
$openid = (string) ($data['openid'] ?? '');
if ($openid === '') {
// 微信偶尔在异常状态下返回 200 但没有 openid,不能当成登录成功
throw new BusinessException(config('code.err.wx_api_error'), '微信接口未返回 openid');
}
$result = [];
$result['openid'] = $openid;
$result['unionid'] = (string) ($data['unionid'] ?? '');
return $result;
}
/**
* 抛出微信侧错误
* throwWxError
* @param int $errcode 微信错误码
* @param string $errmsg 微信错误描述
* @return void
*/
private function throwWxError($errcode, $errmsg)
{
if (in_array($errcode, self::CODE_ERRCODES, true)) {
throw new BusinessException(
config('code.err.wx_code_invalid'),
'微信登录凭证无效,请重新进入'
);
}
// 网络错误归为「服务不可用」而不是「凭证无效」:后者会让前端引导用户重进
// 但重进也没用,问题不在用户
throw new BusinessException(
config('code.err.wx_api_error'),
'微信接口错误 ' . $errcode . ':' . $errmsg
);
}
/**
* 发起 GET 请求
* getUrl
* @param string $url 请求地址
* @param int $timeout 超时秒数
* @return string 响应体
*/
private function getUrl($url, $timeout)
{
if (!function_exists('curl_init')) {
throw new BusinessException(config('code.err.server_busy'), '缺少 curl 扩展,无法访问微信接口');
}
if ($timeout < 1) {
$timeout = 1;
}
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => $timeout,
CURLOPT_CONNECTTIMEOUT => $timeout,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2
]);
try {
$body = curl_exec($ch);
$err = curl_error($ch);
} finally {
curl_close($ch);
}
if ($body === false || $body === '') {
throw new BusinessException(config('code.err.wx_api_error'), '访问微信接口失败:' . $err);
}
return (string) $body;
}
/**
* 获取对外可展示的配置摘要(用于健康检查,不暴露 secret)
* getConfigSummary
* @return array
*/
public function getConfigSummary()
{
$mode = 'live';
if ($this->isMock()) {
$mode = 'mock';
}
$appid_state = '';
if (($this->config['appid'] ?? '') !== '') {
$appid_state = '已配置';
}
$data = [];
$data['mode'] = $mode;
$data['appid'] = $appid_state;
$data['timeout'] = intval($this->config['timeout'] ?? 5);
return $data;
}
}