Files
zyt/server/app/api/controller/QywxPromotionPublicController.php
T
2026-08-05 14:37:29 +08:00

110 lines
4.3 KiB
PHP

<?php
declare(strict_types=1);
namespace app\api\controller;
use app\common\service\qywx\QywxPromotionOpenWorkService;
use app\common\service\qywx\QywxPromotionRedirectService;
use think\facade\Log;
/** 企业微信推广公开端点:服务商回调、授权回跳、JS 与随机跳转。 */
class QywxPromotionPublicController extends BaseApiController
{
/** 公开安装代码、随机跳转与企业微信服务商回调均不依赖前台用户登录。 */
public array $notNeedLogin = ['script', 'redirect', 'providerCallback', 'authCallback'];
public function script(string $key)
{
if (!QywxPromotionRedirectService::poolExists($key)) {
return response('/* promotion pool not found */', 404, ['Content-Type' => 'application/javascript; charset=utf-8']);
}
$goUrl = rtrim($this->request->domain(), '/') . '/api/qywx-promotion/go/' . $key;
$jsonKey = json_encode($key, JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
$jsonGo = json_encode($goUrl, JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
$javascript = <<<JS
(function(w,d){
'use strict';
var key={$jsonKey}, go={$jsonGo};
function openPromotion(){
var source=w.location.href;
w.location.assign(go+'?from='+encodeURIComponent(source));
}
d.addEventListener('click',function(event){
var node=event.target&&event.target.closest?event.target.closest('[data-wecom-promotion="'+key+'"],.wecom-promotion-link[data-pool="'+key+'"]'):null;
if(!node){return;}
event.preventDefault();
event.stopPropagation();
openPromotion();
},true);
w.WecomPromotion=w.WecomPromotion||{};
w.WecomPromotion[key]={open:openPromotion};
})(window,document);
JS;
return response($javascript, 200, [
'Content-Type' => 'application/javascript; charset=utf-8',
'Cache-Control' => 'public, max-age=60',
'X-Content-Type-Options' => 'nosniff',
]);
}
public function redirect(string $key)
{
$picked = QywxPromotionRedirectService::pick($key, [
'source_url' => (string) $this->request->get('from', ''),
'referer' => (string) $this->request->header('referer', ''),
'user_agent' => (string) $this->request->header('user-agent', ''),
'ip' => (string) $this->request->ip(),
]);
if (!$picked) {
return response('当前暂无可用的企业微信推广链接,请稍后再试。', 503, [
'Content-Type' => 'text/plain; charset=utf-8',
'Cache-Control' => 'no-store',
]);
}
return redirect($picked['url'], 302)->header([
'Cache-Control' => 'no-store',
'Referrer-Policy' => 'no-referrer',
]);
}
public function providerCallback()
{
try {
$psr = QywxPromotionOpenWorkService::serveProviderCallback();
$body = $psr->getBody();
$body->rewind();
$headers = [];
if ($psr->getHeaderLine('Content-Type') !== '') {
$headers['Content-Type'] = $psr->getHeaderLine('Content-Type');
}
return response($body->getContents(), $psr->getStatusCode(), $headers);
} catch (\Throwable $e) {
Log::error('企微推广服务商回调失败:' . $e->getMessage(), ['exception' => $e]);
return response('error', 500, ['Content-Type' => 'text/plain; charset=utf-8']);
}
}
public function authCallback()
{
$fallback = rtrim($this->request->domain(), '/') . '/admin/first_visit/wecom_promotion';
$returnUrl = QywxPromotionOpenWorkService::configuredAdminReturnUrl($fallback);
try {
$result = QywxPromotionOpenWorkService::consumeAuthorizationCallback(
trim((string) $this->request->get('auth_code', '')),
trim((string) $this->request->get('state', ''))
);
$query = ['wecom_auth' => 'success', 'account_id' => (int) $result['id']];
} catch (\Throwable $e) {
Log::error('企微推广授权回跳失败:' . $e->getMessage(), ['exception' => $e]);
$query = ['wecom_auth' => 'failed', 'message' => mb_substr($e->getMessage(), 0, 160)];
}
return redirect($returnUrl . (str_contains($returnUrl, '?') ? '&' : '?') . http_build_query($query), 302);
}
}