This commit is contained in:
2026-09-15 10:26:34 +08:00
commit ecf36afa56
10493 changed files with 1404888 additions and 0 deletions
@@ -0,0 +1,610 @@
<?php
/**
* 2025 D1m Group
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0) that is available
* through the world-wide-web at this URL: http://www.opensource.org/licenses/OSL-3.0
*
* @copyright 2025 D1m Group
* @license http://www.opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
*/
namespace Stemcell\Commerce\Model;
use Magento\Authorization\Model\UserContextInterface;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Customer\Api\Data\CustomerInterfaceFactory;
use Magento\Customer\Model\CustomerFactory;
use Magento\Customer\Model\CustomerRegistry;
use Magento\Customer\Model\ResourceModel\Customer\CollectionFactory as CustomerCollectionFactory;
use Magento\Framework\Encryption\EncryptorInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Math\Random;
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
use Magento\Framework\UrlInterface;
use Magento\Framework\Webapi\Exception;
use Magento\Integration\Api\CustomerTokenServiceInterface;
use Magento\Store\Model\StoreManagerInterface;
use Psr\Log\LoggerInterface;
use Stemcell\Commerce\Api\CustomerManagementInterface;
use Stemcell\Commerce\Model\Wechat\Client;
use Stemcell\Commerce\Model\Wechat\WechatAvatarService;
/**
* 微信小程序用户管理实现类
*/
class CustomerManagement implements CustomerManagementInterface
{
private const CUSTOMER_EXPIRATION_CONFIG_PATH = 'webapi/jwtauth/customer_expiration';
/**
* CustomerManagement constructor.
*
* @param CustomerFactory $customerFactory
* @param CustomerRepositoryInterface $customerRepository
* @param CustomerInterfaceFactory $customerDataFactory
* @param Client $wechatClient
* @param Random $random
* @param CustomerTokenServiceInterface $customerTokenService
* @param EncryptorInterface $encryptor
* @param CustomerRegistry $customerRegistry
* @param LoggerInterface $logger
* @param CustomerCollectionFactory $customerCollectionFactory
* @param UserContextInterface $userContext
* @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
* @param \Magento\Framework\App\ResourceConnection $resourceConnection
*/
public function __construct(
protected CustomerFactory $customerFactory,
protected CustomerRepositoryInterface $customerRepository,
protected CustomerInterfaceFactory $customerDataFactory,
protected Client $wechatClient,
protected Random $random,
protected CustomerTokenServiceInterface $customerTokenService,
protected EncryptorInterface $encryptor,
protected CustomerRegistry $customerRegistry,
protected LoggerInterface $logger,
protected CustomerCollectionFactory $customerCollectionFactory,
protected UserContextInterface $userContext,
protected \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
protected \Magento\Framework\App\ResourceConnection $resourceConnection,
protected TimezoneInterface $timezone,
protected WechatAvatarService $wechatAvatarService,
protected StoreManagerInterface $storeManager,
protected UrlInterface $urlInterface
) {
// 使用PHP 7.4+构造函数属性提升,无需单独赋值
}
/**
* {@inheritdoc}
*/
public function getWechatOpenid($code)
{
try {
$this->logger->info('Wechat Integration: Attempting to get openid', ['code' => $code]);
// 获取微信session_key和openid
$sessionData = $this->wechatClient->getSessionKey($code);
if (!isset($sessionData['openid'])) {
$this->logger->error('Wechat Integration: Failed to get openid');
throw new LocalizedException(__('获取微信openid失败'));
}
$this->logger->info('Wechat Integration: Openid obtained successfully', ['openid' => $sessionData['openid']]);
$result = [
'openid' => $sessionData['openid']
];
} catch (\Exception $e) {
$this->logger->error('Wechat Integration: Exception when getting openid', ['exception' => $e->getMessage()]);
$result = [
'error' => "获取openid失败,请稍后重试",
];
}
return WebapiResponse::json($result);
}
/**
* {@inheritdoc}
*/
public function loginByMobile($code, $openid)
{
try {
$this->logger->info('Wechat Integration: Attempting to create user by WeChat', ['openid' => $openid]);
// 1. 使用微信API获取手机号
$phoneNumber = $this->wechatClient->getPhoneNumberByApi($code);
$this->logger->info('Wechat Integration: Phone number obtained', ['phone_number_masked' => substr($phoneNumber, 0, 3) . '****' . substr($phoneNumber, -4)]);
// 2. 检查手机号是否已存在
$existingCustomer = $this->getCustomerByMobile($phoneNumber);
if ($existingCustomer) {
// 如果用户已存在,更新其openid
$this->logger->info('Wechat Integration: Customer already exists, updating openid', ['customer_id' => $existingCustomer->getId()]);
$existingCustomer->setCustomAttribute('wechat_openid', $openid);
$customer = $this->customerRepository->save($existingCustomer);
} else {
// 3. 创建新用户
$this->logger->info('Wechat Integration: Creating new customer', ['phone_number_masked' => substr($phoneNumber, 0, 3) . '****' . substr($phoneNumber, -4)]);
$customer = $this->customerDataFactory->create();
$customer->setWebsiteId(1); // 默认网站ID
$customer->setStoreId(1); // 默认店铺ID
$customer->setFirstname('wx_' . $phoneNumber);
$customer->setLastname('');
// 生成临时邮箱
$tempEmail = $this->generateTempEmail($phoneNumber);
$customer->setEmail($tempEmail);
// 设置手机号
$customer->setCustomAttribute('mobile', $phoneNumber);
// 设置微信openid
$this->logger->info('Wechat Integration: Setting wechat_openid for new customer', ['openid' => $openid]);
$customer->setCustomAttribute('wechat_openid', $openid);
// 设置随机密码
$password = $this->random->getRandomString(10);
// 保存用户
$customer = $this->customerRepository->save($customer);
// 使用CustomerRepository的setPasswordHash方法设置密码
$customerSecure = $this->customerRegistry->retrieveSecureData($customer->getId());
$hashedPassword = $this->encryptor->getHash($password, true);
$customerSecure->setPasswordHash($hashedPassword);
}
$result = $this->generateCustomerToken($customer);
$this->logger->info('Wechat Integration: Login successful, token generated', ['customer_id' => $customer->getId(), 'token' => $result]);
} catch (\Exception $e) {
$this->logger->error('Wechat Integration: Exception creating user by WeChat', ['exception' => $e->getMessage()]);
$result = [
'error' => $e->getMessage(),
];
}
return WebapiResponse::json($result);
}
/**
* {@inheritdoc}
*/
public function updateCustomerInfo($name, $email, $mobile, $company, $wechatAvatar = null)
{
try {
// 1. 加载用户
$customerId = $this->userContext->getUserId();
$customer = $this->customerRepository->getById($customerId);
// 2. 更新用户信息
if (!empty($name)) {
$customer->setFirstname($name);
}
if (!empty($email)) {
// 检查邮箱是否已被使用
try {
$existingCustomer = $this->customerRepository->get($email);
$existingCustomerId = $existingCustomer->getId();
if (!empty($existingCustomerId) && $existingCustomerId != $customerId) {
throw new LocalizedException(__('该邮箱已被使用'));
}
} catch (\Exception $e) {
// 邮箱未被使用,可以设置
}
$customer->setEmail($email);
}
if (!empty($mobile)) {
// 检查手机号是否已被使用
// 手机号不可修改,此逻辑可根据需求调整
/**
$existingCustomer = $this->getCustomerByMobile($mobile);
if ($existingCustomer && $existingCustomer->getId() != $customerId) {
throw new LocalizedException(__('该手机号已被使用'));
}
$customer->setCustomAttribute('mobile', $mobile);**/
}
if (!empty($company)) {
// 设置公司属性
$customer->setCustomAttribute('company', $company);
}
// 处理微信头像
$this->processWechatAvatar($customer, $wechatAvatar, $this->getCustomerAttribute($customer, 'wechat_openid'));
// 3. 保存更新
$customer = $this->customerRepository->save($customer);
// 使用 Magento2 时区处理类格式化更新时间
$formattedUpdatedAt = $this->timezone->formatDateTime(
$customer->getUpdatedAt(),
\IntlDateFormatter::MEDIUM,
\IntlDateFormatter::MEDIUM
);
$result = [
'customer_id' => $customer->getId(),
'customer_updated' => $formattedUpdatedAt,
];
} catch (\Exception $e) {
$result = ['error' => "更新用户信息失败,请稍后重试, " . $e->getMessage()];
}
return WebapiResponse::json($result);
}
/**
* {@inheritdoc}
*/
public function wechatLogin($code)
{
try {
$this->logger->info('Wechat Integration: WeChat login attempt', ['code' => $code]);
// 1. 获取微信session_key和openid
$sessionData = $this->wechatClient->getSessionKey($code);
if (!isset($sessionData['openid'])) {
$this->logger->error('Wechat Integration: Failed to get openid during login');
throw new LocalizedException(__('获取微信openid失败'));
}
$openid = $sessionData['openid'];
$this->logger->info('Wechat Integration: Openid obtained for login', ['openid' => $openid]);
// 2. 检查是否有绑定该openid的用户
$customer = $this->getCustomerByWechatOpenid($openid);
if ($customer) {
$this->logger->info('Wechat Integration: Customer found with openid', ['customer_id' => $customer->getId()]);
// 已存在用户,生成access token
$result = $this->generateCustomerToken($customer);
$this->logger->info('Wechat Integration: Login successful, token generated', ['customer_id' => $customer->getId(), 'token' => $result]);
} else {
// 3. 新用户,返回需要绑定手机号的提示
$this->logger->info('Wechat Integration: New user detected, needs phone binding', ['openid' => $openid]);
$result = [
'error' => '请先绑定手机号',
];
}
} catch (\Exception $e) {
$this->logger->error('Wechat Integration: Exception during WeChat login', ['exception' => $e->getMessage()]);
$result = [
'error' => $e->getMessage(),
];
}
return WebapiResponse::json($result);
}
/**
* 根据手机号获取用户
*
* @param string $mobile
* @return CustomerInterface|null
*/
protected function getCustomerByMobile($mobile)
{
try {
$this->logger->info('Wechat Integration: Attempting to find customer by mobile', ['mobile' => $mobile]);
// 使用集合方式查找用户
$customerCollection = $this->customerCollectionFactory->create();
$customerCollection->addAttributeToSelect('*')
->addAttributeToFilter('mobile', $mobile)
->addAttributeToFilter('website_id', 1)
->setPageSize(1);
$customer = $customerCollection->getFirstItem();
if ($customer->getId()) {
$this->logger->info('Wechat Integration: Customer found by mobile', ['customer_id' => $customer->getId(), 'mobile' => $mobile]);
return $this->customerRepository->getById($customer->getId());
} else {
$this->logger->info('Wechat Integration: No customer found with mobile', ['mobile' => $mobile]);
}
} catch (\Exception $e) {
$this->logger->error('Wechat Integration: Error finding customer by mobile', ['mobile' => $mobile, 'exception' => $e->getMessage()]);
}
return null;
}
/**
* 根据微信openid获取用户
*
* @param string $openid
* @return CustomerInterface|null
*/
protected function getCustomerByWechatOpenid($openid)
{
try {
$this->logger->info('Wechat Integration: Attempting to find customer by openid', ['openid' => $openid]);
// 使用集合方式查找用户
$customerCollection = $this->customerCollectionFactory->create();
$customerCollection->addAttributeToSelect('*')
->addAttributeToFilter('wechat_openid', $openid)
->addAttributeToFilter('website_id', 1)
->setPageSize(1);
$customer = $customerCollection->getFirstItem();
if ($customer->getId()) {
$this->logger->info('Wechat Integration: Customer found by openid', ['customer_id' => $customer->getId(), 'openid' => $openid]);
return $this->customerRepository->getById($customer->getId());
} else {
$this->logger->info('Wechat Integration: No customer found with openid', ['openid' => $openid]);
}
} catch (\Exception $e) {
$this->logger->error('Wechat Integration: Error finding customer by openid', ['openid' => $openid, 'exception' => $e->getMessage()]);
}
return null;
}
/**
* 生成临时邮箱
*
* @param string $phoneNumber
* @return string
*/
protected function generateTempEmail($phoneNumber)
{
$randomString = $this->random->getRandomString(6);
return 'wx_' . $phoneNumber . '_' . $randomString . '@stemcell.cn';
}
/**
* 生成用户访问令牌
*
* @param CustomerInterface $customer
* @return array
* @throws \Exception
*/
protected function generateCustomerToken(CustomerInterface $customer)
{
try {
$this->logger->info('Wechat Integration: Attempting to generate token for customer', ['customer_id' => $customer->getId()]);
// 获取客户实体以访问密码哈希
$customerSecure = $this->customerRegistry->retrieveSecureData($customer->getId());
$originalPasswordHash = $customerSecure->getPasswordHash();
// 生成临时密码
$tempPassword = $this->random->getRandomString(20);
try {
// 设置临时密码
$customerSecure->setPasswordHash($this->encryptor->getHash($tempPassword, true));
// 使用临时密码生成令牌
$token = $this->customerTokenService->createCustomerAccessToken(
$customer->getEmail(),
$tempPassword
);
$this->logger->info('Wechat Integration: Token generated successfully', ['customer_id' => $customer->getId()]);
$expiresIn = $this->scopeConfig->getValue(self::CUSTOMER_EXPIRATION_CONFIG_PATH, \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
return [
'token_type' => 'Bearer',
'token' => $token,
'expires_in' => (int)$expiresIn * 60
];
} catch (\Exception $e) {
$this->logger->error('Wechat Integration: Error generating token', [
'customer_id' => $customer->getId(),
'error' => $e->getMessage()
]);
throw $e;
} finally {
// 恢复原始密码哈希,确保用户密码不变
$customerSecure->setPasswordHash($originalPasswordHash);
$this->logger->info('Wechat Integration: Restored original password hash', ['customer_id' => $customer->getId()]);
}
} catch (\Exception $e) {
$this->logger->error('Wechat Integration: Failed to generate customer token', ['error' => $e->getMessage()]);
throw new \Exception('Failed to generate customer token: ' . $e->getMessage(), $e->getCode(), $e);
}
}
/**
* 用户登出
*
* @return bool
* @throws Exception
*/
public function logout()
{
try {
$this->logger->info('Wechat Integration: User logout attempt');
// 获取当前登录的用户信息
$customerId = $this->getCurrentCustomerId();
$this->logger->info('Wechat Integration: User logout processing', ['customer_id' => $customerId]);
// 记录用户登出行为到数据库
$this->customerTokenService->revokeCustomerAccessToken($customerId);
$this->logger->info('Wechat Integration: User logout successful', ['customer_id' => $customerId]);
$result = ['logout' => 'success'];
} catch (\Exception $e) {
$this->logger->error('Wechat Integration: Exception during user logout', ['exception' => $e->getMessage()]);
$result = ['error' => 'Logout failed: ' . $e->getMessage()];
}
return WebapiResponse::json($result);
}
/**
* {@inheritdoc}
*/
public function getCustomerInfo()
{
try {
$this->logger->info('Wechat Integration: Getting customer info');
// 获取当前登录的用户ID
$customerId = $this->userContext->getUserId();
$this->logger->info('Wechat Integration: Processing customer info request', ['customer_id' => $customerId]);
// 获取用户信息
$customer = $this->customerRepository->getById($customerId);
// 构建返回数据
$mobile = $this->getCustomerAttribute($customer, 'mobile');
$result = [
'name' => str_contains($customer->getFirstname(), 'wx_' . $mobile) ? '' : $customer->getFirstname(),
'email' => str_contains($customer->getEmail(), 'wx_' . $mobile) ? '' : $customer->getEmail(),
'company' => $this->getCustomerAttribute($customer, 'company'),
'mobile' => $mobile,
'wechatAvatar' => $this->getAbsoluteAvatarUrl($this->getCustomerAttribute($customer, 'wechat_avatar'))
];
$this->logger->info('Wechat Integration: Customer info retrieved successfully', ['customer_id' => $customerId]);
} catch (\Exception $e) {
$this->logger->error('Wechat Integration: Exception getting customer info', ['exception' => $e->getMessage()]);
$result = ['error' => 'Failed to get customer info: ' . $e->getMessage()];
}
return WebapiResponse::json($result);
}
/**
* 获取用户自定义属性值
*
* @param CustomerInterface $customer
* @param string $attributeCode
* @return string|null
*/
protected function getCustomerAttribute(CustomerInterface $customer, string $attributeCode)
{
try {
return $customer->getCustomAttribute($attributeCode)?->getValue();
} catch (\Exception $e) {
$this->logger->error('Wechat Integration: Error getting customer attribute', ['attribute' => $attributeCode, 'exception' => $e->getMessage()]);
return null;
}
}
/**
* 获取头像的绝对URL
*
* @param string|null $relativePath 相对路径
* @return string|null 返回绝对URL,如果输入为空则返回null
*/
private function getAbsoluteAvatarUrl(?string $relativePath): ?string
{
if (empty($relativePath)) {
return null;
}
try {
// 获取媒体目录的绝对URL
$mediaUrl = $this->urlInterface->getBaseUrl(['_type' => UrlInterface::URL_TYPE_MEDIA]);
// 拼接完整的绝对URL
$absoluteUrl = rtrim($mediaUrl, '/') . '/' . ltrim($relativePath, '/');
$this->logger->info('Wechat Integration: Generated absolute avatar URL', [
'relative_path' => $relativePath,
'absolute_url' => $absoluteUrl
]);
return $absoluteUrl . '?r=' . time();
} catch (\Exception $e) {
$this->logger->error('Wechat Integration: Error generating absolute avatar URL', [
'relative_path' => $relativePath,
'exception' => $e->getMessage()
]);
return null;
}
}
/**
* 处理微信头像
*
* @param CustomerInterface $customer 用户对象
* @param string|null $wechatAvatar 微信头像URL或base64数据
* @param string $openid 用户openid
* @return void
*/
private function processWechatAvatar(CustomerInterface $customer, ?string $wechatAvatar, string $openid): void
{
// 如果提供了有效的头像数据,则更新用户头像
if (!empty($wechatAvatar)) {
$this->logger->info('Wechat Integration: Processing wechat avatar', [
'customer_id' => $customer->getId(),
'data_type' => $this->isBase64Data($wechatAvatar) ? 'base64' : 'url'
]);
// 判断是URL还是base64数据
if ($this->isBase64Data($wechatAvatar)) {
// 处理base64数据
$localAvatarUrl = $this->wechatAvatarService->saveBase64Avatar($wechatAvatar, $openid);
} else {
// 处理URL
$localAvatarUrl = $this->wechatAvatarService->downloadAndSaveAvatar($wechatAvatar, $openid);
}
if ($localAvatarUrl) {
$customer->setCustomAttribute('wechat_avatar', $localAvatarUrl);
$this->logger->info('Wechat Integration: Wechat avatar saved', [
'customer_id' => $customer->getId(),
'local_url' => $localAvatarUrl
]);
} else {
$this->logger->warning('Wechat Integration: Failed to save wechat avatar', [
'customer_id' => $customer->getId(),
'data_type' => $this->isBase64Data($wechatAvatar) ? 'base64' : 'url'
]);
}
}
}
/**
* 判断是否为base64数据
*
* @param string $data
* @return bool
*/
private function isBase64Data(string $data): bool
{
// 检查是否包含data:前缀(数据URL格式)
if (strpos($data, 'data:') === 0) {
return true;
}
// 检查是否为有效的base64编码
// base64编码通常只包含字母、数字、+、/、=字符
$base64Pattern = '/^[A-Za-z0-9+\/]*={0,2}$/';
if (preg_match($base64Pattern, $data)) {
// 进一步验证解码是否成功
$decoded = base64_decode($data, true);
return $decoded !== false;
}
return false;
}
/**
* 获取当前登录用户的ID
*
* @return int
* @throws LocalizedException
*/
protected function getCurrentCustomerId()
{
try {
$this->logger->info('Wechat Integration: Getting current customer ID');
$customerId = $this->userContext->getUserId();
$this->logger->info('Wechat Integration: Current customer ID retrieved', ['customer_id' => $customerId]);
return $customerId;
} catch (\Exception $e) {
$this->logger->error('Wechat Integration: Exception getting current customer ID', ['exception' => $e->getMessage()]);
throw new LocalizedException(__('获取当前用户ID失败'));
}
}
}
@@ -0,0 +1,35 @@
<?php
/**
* Web API 响应处理类
* 提供静态方法用于JSON格式输出和终止脚本
*/
namespace Stemcell\Commerce\Model;
class WebapiResponse
{
/**
* 输出JSON格式的数据并终止脚本
*
* @param array $data 要输出的数据
* @return mixed
*/
public static function json(array $data)
{
// 设置HTTP响应头为JSON格式
header('Content-Type: application/json; charset=utf-8');
$result = [];
if (isset($data['error'])) {
$result['status'] = false;
$result['message'] = $data['error'];
} else {
$result['status'] = true;
$result['data'] = $data;
}
// 输出JSON格式化的数据
echo json_encode($result);
// 终止脚本执行
exit;
}
}
@@ -0,0 +1,241 @@
<?php
/**
* 2025 D1m Group
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0) that is available
* through the world-wide-web at this URL: http://www.opensource.org/licenses/OSL-3.0
*
* @copyright 2025 D1m Group
* @license http://www.opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
*/
namespace Stemcell\Commerce\Model\Wechat;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\HTTP\Client\Curl;
use Psr\Log\LoggerInterface;
/**
* 微信小程序API客户端
*/
class Client
{
/**
* Client constructor.
*
* @param Config $config
* @param Curl $curl
* @param LoggerInterface $logger
*/
public function __construct(
protected Config $config,
protected Curl $curl,
protected LoggerInterface $logger
) {
// 使用PHP 7.4+构造函数属性提升,无需单独赋值
}
/**
* 获取微信小程序session_key和openid
*
* @param string $code 微信登录临时凭证
* @return array
* @throws LocalizedException
*/
public function getSessionKey($code)
{
$this->logger->info('Wechat API: Requesting session key', ['code' => $code]);
$url = $this->config->getLoginUrl() . '?appid=' . $this->config->getAppId()
. '&secret=' . $this->config->getAppSecret()
. '&js_code=' . $code
. '&grant_type=authorization_code';
$this->curl->get($url);
$response = $this->curl->getBody();
$result = json_decode($response, true);
$this->logger->info('Wechat API: Session key response', ['url' => $url,'response' => $result]);
if (isset($result['errcode'])) {
$this->logger->error('Wechat API: Failed to get session key', ['error' => $result]);
throw new LocalizedException(__('获取微信session_key失败: %1', $result['errmsg']));
}
return $result;
}
/**
* 解密微信小程序用户数据
*
* @param string $encryptedData 加密数据
* @param string $iv 初始向量
* @param string $sessionKey 会话密钥
* @return array
* @throws LocalizedException
*/
public function decryptData($encryptedData, $iv, $sessionKey)
{
$this->logger->info('Wechat API: Attempting to decrypt data');
if (strlen($sessionKey) != 24) {
$this->logger->error('Wechat API: Session key length error');
throw new LocalizedException(__('会话密钥长度错误'));
}
$aesKey = base64_decode($sessionKey);
if (strlen($iv) != 24) {
$this->logger->error('Wechat API: IV length error');
throw new LocalizedException(__('初始向量长度错误'));
}
$aesIV = base64_decode($iv);
$aesCipher = base64_decode($encryptedData);
$result = openssl_decrypt(
$aesCipher,
'AES-128-CBC',
$aesKey,
OPENSSL_RAW_DATA,
$aesIV
);
if (!$result) {
$this->logger->error('Wechat API: Data decryption failed');
throw new LocalizedException(__('数据解密失败'));
}
$dataObj = json_decode($result, true);
if (!$dataObj) {
$this->logger->error('Wechat API: Decrypted data format error');
throw new LocalizedException(__('解密数据格式错误'));
}
if ($dataObj['watermark']['appid'] != $this->config->getAppId()) {
$this->logger->error('Wechat API: Data source error', ['expected' => $this->config->getAppId(), 'actual' => $dataObj['watermark']['appid']]);
throw new LocalizedException(__('数据来源错误'));
}
$this->logger->info('Wechat API: Data decrypted successfully');
return $dataObj;
}
/**
* 解析微信小程序手机号(本地解密方式)
*
* @param string $encryptedData 加密的手机号数据
* @param string $iv 初始向量
* @param string $code 微信登录临时凭证
* @return string
* @throws LocalizedException
*/
public function getPhoneNumberByDecrypt($encryptedData, $iv, $code)
{
$this->logger->info('Wechat API: Requesting phone number via local decryption', ['code' => $code]);
// 获取session_key
$sessionData = $this->getSessionKey($code);
if (!isset($sessionData['session_key'])) {
$this->logger->error('Wechat API: Failed to get session key');
throw new LocalizedException(__('获取会话密钥失败'));
}
// 解密手机号
$decryptedData = $this->decryptData($encryptedData, $iv, $sessionData['session_key']);
if (!isset($decryptedData['phoneNumber'])) {
$this->logger->error('Wechat API: Failed to parse phone number');
throw new LocalizedException(__('解析手机号失败'));
}
$this->logger->info('Wechat API: Phone number obtained via local decryption');
return $decryptedData['phoneNumber'];
}
/**
* 通过微信API获取用户手机号
*
* @param string $code 手机号获取凭证
* @return string
* @throws LocalizedException
*/
public function getPhoneNumberByApi($code)
{
try {
$this->logger->info('Wechat API: Requesting phone number via API', ['code' => $code]);
// 获取access_token
$accessToken = $this->getAccessToken();
// 构建请求URL
$url = $this->config->getPhoneNumberUrl() . '?access_token=' . $accessToken;
// 构建请求数据
$requestData = [
'code' => $code
];
// 发送POST请求
$this->curl->addHeader('Content-Type', 'application/json');
$this->curl->post($url, json_encode($requestData));
// 获取响应
$response = $this->curl->getBody();
$result = json_decode($response, true);
$this->logger->info('Wechat API: Phone number API response', ['response' => $result]);
// 检查错误
if (isset($result['errcode']) && $result['errcode'] != 0) {
$this->logger->error('Wechat API: Failed to get phone number', ['error' => $result]);
throw new LocalizedException(__('获取手机号失败: %1', $result['errmsg']));
}
// 检查返回数据
if (!isset($result['phone_info']['phoneNumber'])) {
$this->logger->error('Wechat API: Phone number data missing in response');
throw new LocalizedException(__('手机号数据获取失败'));
}
$this->logger->info('Wechat API: Phone number obtained via API');
return $result['phone_info']['phoneNumber'];
} catch (\Exception $e) {
$this->logger->error('Wechat API: Error when getting phone number', ['exception' => $e->getMessage()]);
throw new LocalizedException(__('获取手机号时发生错误: %1', $e->getMessage()));
}
}
/**
* 获取微信access_token
*
* @return string
* @throws LocalizedException
*/
private function getAccessToken()
{
$this->logger->info('Wechat API: Requesting access token');
$url = $this->config->getApiUrl() . '/cgi-bin/token?grant_type=client_credential'
. '&appid=' . $this->config->getAppId()
. '&secret=' . $this->config->getAppSecret();
$this->curl->get($url);
$response = $this->curl->getBody();
$result = json_decode($response, true);
$this->logger->info('Wechat API: Access token response', ['response' => $result]);
if (isset($result['errcode'])) {
$this->logger->error('Wechat API: Failed to get access token', ['error' => $result]);
throw new LocalizedException(__('获取access_token失败: %1', $result['errmsg']));
}
if (!isset($result['access_token'])) {
$this->logger->error('Wechat API: Access token missing in response');
throw new LocalizedException(__('access_token获取失败'));
}
$this->logger->info('Wechat API: Access token obtained successfully');
return $result['access_token'];
}
}
@@ -0,0 +1,270 @@
<?php
/**
* 2025 D1m Group
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0) that is available
* through the world-wide-web at this URL: http://www.opensource.org/licenses/OSL-3.0
*
* @copyright 2025 D1m Group
* @license http://www.opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
*/
namespace Stemcell\Commerce\Model\Wechat;
use Magento\Cms\Model\Template\FilterProvider;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\ObjectManager;
use Magento\Store\Model\ScopeInterface;
use Psr\Log\LoggerInterface;
/**
* 微信小程序配置类
*/
class Config
{
const XML_PATH_WECHAT_APP_ID = 'commerce/wechat/app_id';
const XML_PATH_WECHAT_APP_SECRET = 'commerce/wechat/app_secret';
const XML_PATH_WECHAT_API_URL = 'commerce/wechat/api_url';
const XML_PATH_WECHAT_SWITCH = 'commerce/wechat/switch';
const XML_PATH_WECHAT_BANNER = 'commerce/wechat/banner';
const XML_PATH_WECHAT_UTILITY_TOOLS = 'commerce/wechat/utility-tools';
const XML_PATH_WECHAT_CONTACT_US = 'commerce/wechat/contact-us';
const XML_PATH_WECHAT_TECHNICAL_RESOURCE_MENU = 'commerce/wechat/technical-resource-menu';
const XML_PATH_WECHAT_MARKETING_POSTS = 'commerce/wechat/marketing-posts';
const XML_PATH_WECHAT_MARKETING_NEW_PRODUCT = 'commerce/wechat/new-product';
/**
* Config constructor.
*
* @param ScopeConfigInterface $scopeConfig
*/
public function __construct(
protected ScopeConfigInterface $scopeConfig,
protected FilterProvider $filterProvider,
) {
// 使用PHP 7.4+构造函数属性提升,无需单独赋值
}
/**
* 获取微信小程序AppID
*
* @param int|null $storeId
* @return string
*/
public function getAppId($storeId = null)
{
return $this->scopeConfig->getValue(
self::XML_PATH_WECHAT_APP_ID,
ScopeInterface::SCOPE_STORE,
$storeId
);
}
/**
* 获取微信小程序AppSecret
*
* @param int|null $storeId
* @return string
*/
public function getAppSecret($storeId = null)
{
return $this->scopeConfig->getValue(
self::XML_PATH_WECHAT_APP_SECRET,
ScopeInterface::SCOPE_STORE,
$storeId
);
}
/**
* 获取微信API地址
*
* @param int|null $storeId
* @return string
*/
public function getApiUrl($storeId = null)
{
return $this->scopeConfig->getValue(
self::XML_PATH_WECHAT_API_URL,
ScopeInterface::SCOPE_STORE,
$storeId
);
}
/**
* 获取微信登录URL
*
* @return string
*/
public function getLoginUrl()
{
return $this->getApiUrl() . '/sns/jscode2session';
}
/**
* 获取微信手机号解密URL
*
* @return string
*/
public function getPhoneNumberUrl()
{
return $this->getApiUrl() . '/wxa/business/getuserphonenumber';
}
/**
* 小程序首页banner、搜索、产品中心、技术资源等是否在小程序首页展示的一些配置
* @return string
*/
public function getWechatConfig()
{
$banner = $this->scopeConfig->getValue(
self::XML_PATH_WECHAT_BANNER,
ScopeInterface::SCOPE_STORE
);
$banner = json_decode($banner, true);
if (!is_array($banner)) {
$banner = [];
}
$config = [
'banner' => $banner,
'entrance' => (int)$this->scopeConfig->getValue(
self::XML_PATH_WECHAT_SWITCH,
ScopeInterface::SCOPE_STORE
),
];
return json_encode($config);
}
/**
* 实用工具页面配置
* @return string
*/
public function getUtilityTools()
{
$config = $this->scopeConfig->getValue(
self::XML_PATH_WECHAT_UTILITY_TOOLS,
ScopeInterface::SCOPE_STORE
);
if (!$config) {
$config = [];
} else {
try {
$config = $this->filterProvider->getPageFilter()->filter($config);
$config = json_decode($config, true);
} catch (\Exception $e) {
$config = [];
}
}
$config = is_array($config) ? $config : [];
return json_encode($config);
}
/**
* 联系我们页面
* @return string
*/
public function getContactUs()
{
$config = $this->scopeConfig->getValue(
self::XML_PATH_WECHAT_CONTACT_US,
ScopeInterface::SCOPE_STORE
);
if (!$config) {
$config = [];
} else {
try {
$config = $this->filterProvider->getPageFilter()->filter($config);
$config = json_decode($config, true);
} catch (\Exception $e) {
$config = [];
}
}
$config = is_array($config) ? $config : [];
if (isset($config['vendors']['data'])) {
$config['vendors']['provinces'] = array_keys((array)$config['vendors']['data']);
}
return json_encode($config);
}
/**
* 技术资源菜单配置
* @return string
*/
public function getTechnicalResourceMenu()
{
$config = $this->scopeConfig->getValue(
self::XML_PATH_WECHAT_TECHNICAL_RESOURCE_MENU,
ScopeInterface::SCOPE_STORE
);
if (!$config) {
$config = [];
} else {
try {
$config = $this->filterProvider->getPageFilter()->filter($config);
$config = json_decode($config, true);
} catch (\Exception $e) {
$config = [];
}
}
$config = is_array($config) ? $config : [];
return json_encode($config);
}
/**
* 技术资源菜单配置
* @return string
*/
public function getMarketingPosts()
{
$config = $this->scopeConfig->getValue(
self::XML_PATH_WECHAT_MARKETING_POSTS,
ScopeInterface::SCOPE_STORE
);
if (!$config) {
$config = [];
} else {
try {
$config = $this->filterProvider->getPageFilter()->filter($config);
$config = json_decode($config, true);
} catch (\Exception $e) {
$config = [];
}
}
$config = is_array($config) ? $config : [];
return json_encode($config);
}
/**
* 新品配置
* @return string
*/
public function getNewProduct()
{
$config = $this->scopeConfig->getValue(
self::XML_PATH_WECHAT_MARKETING_NEW_PRODUCT,
ScopeInterface::SCOPE_STORE
);
if (!$config) {
$config = [];
} else {
try {
$config = $this->filterProvider->getPageFilter()->filter($config);
$config = json_decode($config, true);
} catch (\Exception $e) {
$config = [];
}
}
$config = is_array($config) ? $config : [];
return json_encode($config);
}
}
@@ -0,0 +1,572 @@
<?php
/**
* 2025 D1m Group
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0) that is available
* through the world-wide-web at this URL: http://www.opensource.org/licenses/OSL-3.0
*
* @copyright 2025 D1m Group
* @license http://www.opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
*/
namespace Stemcell\Commerce\Model\Wechat;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Filesystem;
use Magento\Framework\Filesystem\Io\File;
use Magento\Framework\HTTP\Client\Curl;
use Magento\Store\Model\StoreManagerInterface;
use Psr\Log\LoggerInterface;
/**
* 微信头像服务类
*/
class WechatAvatarService
{
private const AVATAR_DIR = 'profile/wechat_avatar';
private const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB
private const REQUEST_TIMEOUT = 30; // 30秒超时
/**
* WechatAvatarService constructor.
*
* @param Filesystem $filesystem
* @param File $ioFile
* @param Curl $curl
* @param StoreManagerInterface $storeManager
* @param LoggerInterface $logger
*/
public function __construct(
private Filesystem $filesystem,
private File $ioFile,
private Curl $curl,
private StoreManagerInterface $storeManager,
private LoggerInterface $logger
) {
// 使用PHP 7.4+构造函数属性提升,无需单独赋值
}
/**
* 下载并保存微信头像
*
* @param string $avatarUrl 微信头像URL
* @param string $openid 用户openid
* @return string|null 返回本地头像路径,失败返回null
*/
public function downloadAndSaveAvatar(string $avatarUrl, string $openid): ?string
{
try {
// 1. 输入验证
if (empty($avatarUrl) || empty($openid)) {
$this->logger->warning('WechatAvatarService: Empty avatar URL or openid', [
'avatar_url' => $avatarUrl,
'openid' => $openid
]);
return null;
}
// 2. URL白名单验证
if (!$this->validateAvatarUrl($avatarUrl)) {
$this->logger->error('WechatAvatarService: Invalid avatar URL', [
'url' => $avatarUrl,
'openid' => $openid
]);
return null;
}
// 3. 检查文件大小(通过HEAD请求)
if (!$this->validateFileSize($avatarUrl)) {
$this->logger->error('WechatAvatarService: File too large', [
'url' => $avatarUrl,
'openid' => $openid
]);
return null;
}
// 4. 下载文件
$imageData = $this->downloadWithTimeout($avatarUrl);
if (empty($imageData)) {
$this->logger->error('WechatAvatarService: Failed to download avatar', [
'avatar_url' => $avatarUrl,
'openid' => $openid
]);
return null;
}
// 5. 检测和验证文件格式
$fileExtension = $this->detectImageFormat($imageData, $avatarUrl);
if (!$fileExtension) {
$this->logger->error('WechatAvatarService: Unsupported image format', [
'avatar_url' => $avatarUrl,
'openid' => $openid
]);
return null;
}
// 6. 验证文件内容
if (!$this->validateImageContent($imageData, $fileExtension)) {
$this->logger->error('WechatAvatarService: Invalid image content', [
'avatar_url' => $avatarUrl,
'openid' => $openid,
'extension' => $fileExtension
]);
return null;
}
// 7. 保存文件
$fileName = md5($openid) . '.' . $fileExtension;
$fullPath = self::AVATAR_DIR . '/' . $fileName;
$mediaDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
$mediaDirectory->create(self::AVATAR_DIR);
$mediaDirectory->writeFile($fullPath, $imageData);
$this->logger->info('WechatAvatarService: Avatar saved successfully', [
'openid' => $openid,
'local_path' => $fullPath,
'file_extension' => $fileExtension
]);
return $fullPath;
} catch (\Exception $e) {
$this->logger->error('WechatAvatarService: Exception while downloading avatar', [
'avatar_url' => $avatarUrl,
'openid' => $openid,
'exception' => $e->getMessage()
]);
return null;
}
}
/**
* 验证头像URL是否在白名单中
*
* @param string $url
* @return bool
*/
private function validateAvatarUrl(string $url): bool
{
// 只允许微信CDN域名
$allowedDomains = [
'thirdwx.qlogo.cn',
'wx.qlogo.cn',
'mmbiz.qpic.cn'
];
$parsedUrl = parse_url($url);
if (!isset($parsedUrl['host'])) {
return false;
}
foreach ($allowedDomains as $domain) {
if (str_ends_with($parsedUrl['host'], $domain)) {
return true;
}
}
return false;
}
/**
* 验证文件大小
*
* @param string $url
* @return bool
*/
private function validateFileSize(string $url): bool
{
try {
// 使用HEAD请求获取文件大小
$headers = get_headers($url, 1);
if (isset($headers['Content-Length'])) {
$fileSize = (int)$headers['Content-Length'];
if ($fileSize > self::MAX_FILE_SIZE) {
$this->logger->warning('WechatAvatarService: File too large', [
'url' => $url,
'size' => $fileSize,
'max_size' => self::MAX_FILE_SIZE
]);
return false;
}
}
return true;
} catch (\Exception $e) {
$this->logger->warning('WechatAvatarService: Failed to validate file size', [
'url' => $url,
'exception' => $e->getMessage()
]);
return true; // 如果无法验证大小,允许下载但会在后续步骤中检查
}
}
/**
* 带超时的文件下载
*
* @param string $url
* @return string
* @throws \Exception
*/
private function downloadWithTimeout(string $url): string
{
$this->curl->setTimeout(self::REQUEST_TIMEOUT);
$this->curl->setOption(CURLOPT_FOLLOWLOCATION, false); // 禁止重定向
$this->curl->setOption(CURLOPT_MAXREDIRS, 0);
$this->curl->setOption(CURLOPT_SSL_VERIFYPEER, true);
$this->curl->setOption(CURLOPT_SSL_VERIFYHOST, 2);
$this->curl->get($url);
if ($this->curl->getStatus() !== 200) {
throw new \Exception('Download failed with status: ' . $this->curl->getStatus());
}
return $this->curl->getBody();
}
/**
* 验证图片内容
*
* @param string $imageData
* @param string $extension
* @return bool
*/
private function validateImageContent(string $imageData, string $extension): bool
{
// 检查文件大小
if (strlen($imageData) > self::MAX_FILE_SIZE) {
$this->logger->warning('WechatAvatarService: Downloaded file too large', [
'size' => strlen($imageData),
'max_size' => self::MAX_FILE_SIZE
]);
return false;
}
// 对于SVG文件,进行额外的安全检查
if ($extension === 'svg') {
return $this->validateSvgContent($imageData);
}
return true;
}
/**
* 验证SVG文件内容
*
* @param string $svgData
* @return bool
*/
private function validateSvgContent(string $svgData): bool
{
// 检查是否包含危险标签
$dangerousTags = ['script', 'object', 'embed', 'iframe'];
foreach ($dangerousTags as $tag) {
if (stripos($svgData, "<$tag") !== false) {
$this->logger->warning('WechatAvatarService: SVG contains dangerous tag', ['tag' => $tag]);
return false;
}
}
// 检查是否包含JavaScript事件
$dangerousEvents = ['onload', 'onclick', 'onerror', 'onmouseover', 'onfocus'];
foreach ($dangerousEvents as $event) {
if (stripos($svgData, $event) !== false) {
$this->logger->warning('WechatAvatarService: SVG contains dangerous event', ['event' => $event]);
return false;
}
}
return true;
}
/**
* 检测图片格式并返回文件后缀
*
* @param string $imageData 图片数据
* @param string $avatarUrl 头像URL
* @return string|null 返回文件后缀,失败返回null
*/
private function detectImageFormat(string $imageData, string $avatarUrl): ?string
{
// 支持的图片格式
$supportedFormats = [
'jpeg' => ["\xFF\xD8\xFF"],
'jpg' => ["\xFF\xD8\xFF"],
'png' => ["\x89\x50\x4E\x47"],
'gif' => ["GIF87a", "GIF89a"],
'webp' => ["RIFF"],
'bmp' => ["BM"],
'svg' => ["<?xml", "<svg"]
];
// 首先尝试从URL中获取文件后缀
$urlExtension = $this->getExtensionFromUrl($avatarUrl);
if ($urlExtension && array_key_exists(strtolower($urlExtension), $supportedFormats)) {
$this->logger->info('WechatAvatarService: Detected format from URL', [
'extension' => $urlExtension,
'url' => $avatarUrl
]);
return strtolower($urlExtension);
}
// 通过文件头检测图片格式
foreach ($supportedFormats as $extension => $signatures) {
foreach ($signatures as $signature) {
if (strpos($imageData, $signature) === 0) {
$this->logger->info('WechatAvatarService: Detected format from file header', [
'extension' => $extension,
'signature' => bin2hex($signature)
]);
return $extension;
}
}
}
// 特殊处理SVG格式(可能没有XML声明)
if (strpos($imageData, '<svg') !== false) {
$this->logger->info('WechatAvatarService: Detected SVG format from content');
return 'svg';
}
$this->logger->warning('WechatAvatarService: Unknown image format', [
'url' => $avatarUrl,
'data_length' => strlen($imageData),
'first_bytes' => bin2hex(substr($imageData, 0, 16))
]);
return null;
}
/**
* 从URL中提取文件后缀
*
* @param string $url
* @return string|null
*/
private function getExtensionFromUrl(string $url): ?string
{
$parsedUrl = parse_url($url);
if (!isset($parsedUrl['path'])) {
return null;
}
$path = $parsedUrl['path'];
$extension = pathinfo($path, PATHINFO_EXTENSION);
if (empty($extension)) {
return null;
}
// 清理扩展名(移除查询参数等)
$extension = strtolower(trim($extension, '.'));
return $extension;
}
/**
* 删除头像文件
*
* @param string $openid 用户openid
* @return bool
*/
public function deleteAvatar(string $openid): bool
{
try {
$mediaDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
$avatarDir = self::AVATAR_DIR;
// 支持的图片格式
$supportedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'svg'];
// 尝试删除所有可能的文件格式
$deleted = false;
foreach ($supportedExtensions as $extension) {
$fileName = md5($openid) . '.' . $extension;
$fullPath = $avatarDir . '/' . $fileName;
if ($mediaDirectory->isExist($fullPath)) {
$mediaDirectory->delete($fullPath);
$this->logger->info('WechatAvatarService: Avatar deleted successfully', [
'openid' => $openid,
'file_path' => $fullPath,
'extension' => $extension
]);
$deleted = true;
}
}
return $deleted;
} catch (\Exception $e) {
$this->logger->error('WechatAvatarService: Exception while deleting avatar', [
'openid' => $openid,
'exception' => $e->getMessage()
]);
return false;
}
}
/**
* 保存base64图片数据
*
* @param string $base64Data base64编码的图片数据
* @param string $openid 用户openid
* @return string|null 返回本地头像路径,失败返回null
*/
public function saveBase64Avatar(string $base64Data, string $openid): ?string
{
try {
// 1. 输入验证
if (empty($base64Data) || empty($openid)) {
$this->logger->warning('WechatAvatarService: Empty base64 data or openid', [
'openid' => $openid,
'data_length' => strlen($base64Data)
]);
return null;
}
// 2. 解析base64数据
$imageData = $this->parseBase64Data($base64Data);
if (!$imageData) {
$this->logger->error('WechatAvatarService: Invalid base64 data', [
'openid' => $openid
]);
return null;
}
// 3. 检查文件大小
if (strlen($imageData) > self::MAX_FILE_SIZE) {
$this->logger->error('WechatAvatarService: Base64 image too large', [
'openid' => $openid,
'size' => strlen($imageData),
'max_size' => self::MAX_FILE_SIZE
]);
return null;
}
// 4. 检测图片格式
$fileExtension = $this->detectImageFormatFromData($imageData);
if (!$fileExtension) {
$this->logger->error('WechatAvatarService: Unsupported image format from base64', [
'openid' => $openid
]);
return null;
}
// 5. 验证图片内容
if (!$this->validateImageContent($imageData, $fileExtension)) {
$this->logger->error('WechatAvatarService: Invalid image content from base64', [
'openid' => $openid,
'extension' => $fileExtension
]);
return null;
}
// 6. 保存文件
$fileName = md5($openid) . '.' . $fileExtension;
$fullPath = self::AVATAR_DIR . '/' . $fileName;
$mediaDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
$mediaDirectory->create(self::AVATAR_DIR);
$mediaDirectory->writeFile($fullPath, $imageData);
$this->logger->info('WechatAvatarService: Base64 avatar saved successfully', [
'openid' => $openid,
'local_path' => $fullPath,
'file_extension' => $fileExtension,
'file_size' => strlen($imageData)
]);
return $fullPath;
} catch (\Exception $e) {
$this->logger->error('WechatAvatarService: Exception while saving base64 avatar', [
'openid' => $openid,
'exception' => $e->getMessage()
]);
return null;
}
}
/**
* 解析base64数据
*
* @param string $base64Data
* @return string|null
*/
private function parseBase64Data(string $base64Data): ?string
{
try {
// 移除可能的数据URL前缀
if (strpos($base64Data, 'data:') === 0) {
$parts = explode(',', $base64Data, 2);
if (count($parts) !== 2) {
return null;
}
$base64Data = $parts[1];
}
// 解码base64数据
$decodedData = base64_decode($base64Data, true);
if ($decodedData === false) {
$this->logger->warning('WechatAvatarService: Invalid base64 encoding');
return null;
}
return $decodedData;
} catch (\Exception $e) {
$this->logger->error('WechatAvatarService: Exception parsing base64 data', [
'exception' => $e->getMessage()
]);
return null;
}
}
/**
* 从图片数据检测格式
*
* @param string $imageData
* @return string|null
*/
private function detectImageFormatFromData(string $imageData): ?string
{
// 支持的图片格式
$supportedFormats = [
'jpeg' => ["\xFF\xD8\xFF"],
'jpg' => ["\xFF\xD8\xFF"],
'png' => ["\x89\x50\x4E\x47"],
'gif' => ["GIF87a", "GIF89a"],
'webp' => ["RIFF"],
'bmp' => ["BM"],
'svg' => ["<?xml", "<svg"]
];
// 通过文件头检测图片格式
foreach ($supportedFormats as $extension => $signatures) {
foreach ($signatures as $signature) {
if (strpos($imageData, $signature) === 0) {
$this->logger->info('WechatAvatarService: Detected format from data', [
'extension' => $extension,
'signature' => bin2hex($signature)
]);
return $extension;
}
}
}
// 特殊处理SVG格式(可能没有XML声明)
if (strpos($imageData, '<svg') !== false) {
$this->logger->info('WechatAvatarService: Detected SVG format from data');
return 'svg';
}
$this->logger->warning('WechatAvatarService: Unknown image format from data', [
'data_length' => strlen($imageData),
'first_bytes' => bin2hex(substr($imageData, 0, 16))
]);
return null;
}
}