webman/app/Utils/API/Facebook.php

100 lines
3.0 KiB
PHP

<?php
namespace App\Utils\API;
use app\model\Facebookconf;
use app\model\Recommend;
use FacebookAds\Api;
use FacebookAds\Logger\CurlLogger;
use FacebookAds\Object\ServerSide\CustomData;
use FacebookAds\Object\ServerSide\Event;
use FacebookAds\Object\ServerSide\EventRequest;
use FacebookAds\Object\ServerSide\UserData;
use Exception;
/**
* Facebook API 事件处理
*/
class Facebook
{
/**
* 初始化 Facebook API
* @param string $access_token
*/
private static function initFacebookApi(string $access_token): void
{
Api::init(null, null, $access_token);
Api::instance()->setLogger(new CurlLogger());
}
/**
* 发送 Facebook 事件
* @param string $event_name 事件名称 (PageView / CompleteRegistration)
* @param string $access_token
* @param string $pixel_id
*/
private static function sendEvent(string $event_name, string $access_token, string $pixel_id): void
{
try {
self::initFacebookApi($access_token);
$event = (new Event())
->setEventName($event_name)
->setEventTime(time())
->setUserData(new UserData()) // 可以扩展用户数据
->setCustomData(new CustomData()) // 可以扩展自定义数据
->setActionSource("website");
(new EventRequest($pixel_id))
->setEvents([$event])
->execute();
} catch (Exception $e) {
error_log("Facebook API Error: " . $e->getMessage());
}
}
/**
* 触发 PageView 事件
* @param string $access_token
* @param string $pixel_id
*/
public static function PageView(string $access_token, string $pixel_id): void
{
self::sendEvent("PageView", $access_token, $pixel_id);
}
/**
* 触发 CompleteRegistration 事件
* @param string $access_token
* @param string $pixel_id
*/
public static function CompleteRegistration(string $access_token, string $pixel_id): void
{
self::sendEvent("CompleteRegistration", $access_token, $pixel_id);
}
/**
* 处理 Facebook 事件
* @param int $type 事件类型 (1 = PageView, 2 = CompleteRegistration)
* @param string $invite_code 邀请码
*/
public static function handleEvent(int $type, string $invite_code): void
{
$recommend = Recommend::where('invite_code', $invite_code)->first();
if ($recommend) {
$facebookConf = Facebookconf::where('promotionid', $recommend->id)->first();
if ($facebookConf) {
$access_token = $facebookConf->access_token;
$pixel_id = $facebookConf->pixel_id;
match ($type) {
1 => self::PageView($access_token, $pixel_id),
2 => self::CompleteRegistration($access_token, $pixel_id),
default => error_log("Invalid event type: " . $type),
};
}
}
}
}