-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminimal-conversions.php
More file actions
401 lines (349 loc) · 15.8 KB
/
minimal-conversions.php
File metadata and controls
401 lines (349 loc) · 15.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
<?php
/**
* Plugin Name: Minimal Meta (Facebook) CAPI Conversion (No Pixel)
* Description: Captures fbclid from Meta ads, stores it as a first-party cookie, and sends a single server-side conversion via Meta Conversions API when triggered by a shortcode.
* Version: 0.1.0
* Author: You
*/
if (!defined('ABSPATH')) exit;
class Minimal_Meta_CAPI_No_Pixel {
const OPT_KEY = 'mmcapi_settings';
const COOKIE_KEY = 'mmcapi_fbclid';
const COOKIE_KEY_SOURCE = 'mmcapi_utm_source';
const COOKIE_KEY_MEDIUM = 'mmcapi_utm_medium';
const COOKIE_KEY_CAMPAIGN = 'mmcapi_utm_campaign';
const COOKIE_DAYS = 7;
public function __construct() {
add_action('init', [$this, 'capture_fbclid'], 1);
add_action('admin_menu', [$this, 'admin_menu']);
add_action('admin_init', [$this, 'register_settings']);
add_shortcode('meta_capi_conversion', [$this, 'shortcode_fire_conversion']);
add_action('woocommerce_thankyou', [$this, 'woocommerce_thankyou'], 10);
}
public function capture_fbclid() {
if (is_admin()) return;
if (!empty($_GET['fbclid'])) {
$fbclid = sanitize_text_field(wp_unslash($_GET['fbclid']));
$utm_source = isset($_GET['utm_source']) ? sanitize_text_field(wp_unslash($_GET['utm_source'])) : '';
$utm_medium = isset($_GET['utm_medium']) ? sanitize_text_field(wp_unslash($_GET['utm_medium'])) : '';
$utm_campaign = isset($_GET['utm_campaign']) ? sanitize_text_field(wp_unslash($_GET['utm_campaign'])) : '';
// Store only what we need, as a first-party cookie.
$expire = time() + (self::COOKIE_DAYS * DAY_IN_SECONDS);
// Secure/HTTPOnly where possible.
$secure = is_ssl();
setcookie(self::COOKIE_KEY, $fbclid, $expire, COOKIEPATH ?: '/', '', $secure, true);
if (!empty($utm_source)) {
setcookie(self::COOKIE_KEY_SOURCE, $utm_source, $expire, COOKIEPATH ?: '/', '', $secure, true);
$_COOKIE[self::COOKIE_KEY_SOURCE] = $utm_source;
}
if (!empty($utm_medium)) {
setcookie(self::COOKIE_KEY_MEDIUM, $utm_medium, $expire, COOKIEPATH ?: '/', '', $secure, true);
$_COOKIE[self::COOKIE_KEY_MEDIUM] = $utm_medium;
}
if (!empty($utm_campaign)) {
setcookie(self::COOKIE_KEY_CAMPAIGN, $utm_campaign, $expire, COOKIEPATH ?: '/', '', $secure, true);
$_COOKIE[self::COOKIE_KEY_CAMPAIGN] = $utm_campaign;
}
// Keep PHP superglobal in sync for this request.
$_COOKIE[self::COOKIE_KEY] = $fbclid;
$this->debug_log('Captured fbclid from URL: ' . $fbclid . ' | URL: ' . (isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : 'unknown'));
if (!empty($utm_source)) {
$this->debug_log('Captured utm_source from URL: ' . $utm_source);
}
if (!empty($utm_medium)) {
$this->debug_log('Captured utm_medium from URL: ' . $utm_medium);
}
if (!empty($utm_campaign)) {
$this->debug_log('Captured utm_campaign from URL: ' . $utm_campaign);
}
}
}
public function admin_menu() {
add_options_page(
'Minimal Meta Conversions',
'Minimal Meta Conversions',
'manage_options',
'minimal-meta-capi',
[$this, 'settings_page']
);
}
public function register_settings() {
register_setting('mmcapi_group', self::OPT_KEY, [$this, 'sanitize_settings']);
add_settings_section('mmcapi_main', 'Settings', function () {
echo '<p>Configure your Meta Pixel ID and a Conversions API access token.</p>';
}, 'minimal-meta-capi');
$fields = [
'pixel_id' => 'Pixel ID',
'access_token' => 'Access Token',
'test_event_code' => 'Test Event Code (optional)',
];
foreach ($fields as $key => $label) {
add_settings_field(
$key,
esc_html($label),
function () use ($key) {
$opts = get_option(self::OPT_KEY, []);
$val = isset($opts[$key]) ? $opts[$key] : '';
printf(
'<input type="text" name="%s[%s]" value="%s" class="regular-text" />',
esc_attr(self::OPT_KEY),
esc_attr($key),
esc_attr($val)
);
if ($key === 'test_event_code') {
echo '<p class="description">For testing only. Generate code in Meta Events Manager > Test Events. Leave blank for production.</p>';
}
},
'minimal-meta-capi',
'mmcapi_main'
);
}
// Event name dropdown with standard Meta event names
add_settings_field(
'event_name',
esc_html('Event Name'),
function () {
$opts = get_option(self::OPT_KEY, []);
$val = isset($opts['event_name']) ? $opts['event_name'] : 'Purchase';
$standard_events = [
'Lead' => 'Lead',
'Purchase' => 'Purchase',
'CompleteRegistration' => 'Complete Registration',
'Contact' => 'Contact',
'SubmitApplication' => 'Submit Application',
'AddToCart' => 'Add to Cart',
'InitiateCheckout' => 'Initiate Checkout',
'AddPaymentInfo' => 'Add Payment Info',
'Subscribe' => 'Subscribe',
'StartTrial' => 'Start Trial',
'ViewContent' => 'View Content',
'Search' => 'Search',
'AddToWishlist' => 'Add to Wishlist',
'Schedule' => 'Schedule',
];
printf('<select name="%s[event_name]" class="regular-text">', esc_attr(self::OPT_KEY));
foreach ($standard_events as $event_value => $event_label) {
printf(
'<option value="%s" %s>%s</option>',
esc_attr($event_value),
selected($val, $event_value, false),
esc_html($event_label)
);
}
echo '</select>';
echo '<p class="description">Select the standard Meta event to track.</p>';
},
'minimal-meta-capi',
'mmcapi_main'
);
// WooCommerce integration checkbox
add_settings_field(
'woocommerce_enabled',
esc_html('WooCommerce Integration'),
function () {
$opts = get_option(self::OPT_KEY, []);
$checked = !empty($opts['woocommerce_enabled']);
printf(
'<label><input type="checkbox" name="%s[woocommerce_enabled]" value="1" %s /> Enable on WooCommerce thank you page</label>',
esc_attr(self::OPT_KEY),
checked($checked, true, false)
);
echo '<p class="description">Automatically fire conversion events on order completion.</p>';
},
'minimal-meta-capi',
'mmcapi_main'
);
// Include user data checkbox
add_settings_field(
'include_user_data',
esc_html('Include User Data'),
function () {
$opts = get_option(self::OPT_KEY, []);
$checked = !empty($opts['include_user_data']);
printf(
'<label><input type="checkbox" name="%s[include_user_data]" value="1" %s /> Send IP address and user agent to Meta</label>',
esc_attr(self::OPT_KEY),
checked($checked, true, false)
);
echo '<p class="description">Improves event matching but shares more user data. Uncheck for minimal tracking.</p>';
},
'minimal-meta-capi',
'mmcapi_main'
);
// Debug logging checkbox
add_settings_field(
'debug_logging',
esc_html('Debug Logging'),
function () {
$opts = get_option(self::OPT_KEY, []);
$checked = !empty($opts['debug_logging']);
printf(
'<label><input type="checkbox" name="%s[debug_logging]" value="1" %s /> Enable debug logging</label>',
esc_attr(self::OPT_KEY),
checked($checked, true, false)
);
echo '<p class="description">Log fbclid captures and API calls to <code>wp-content/minimal-conversions.log</code>.</p>';
},
'minimal-meta-capi',
'mmcapi_main'
);
}
public function sanitize_settings($in) {
return [
'pixel_id' => isset($in['pixel_id']) ? preg_replace('/\D+/', '', $in['pixel_id']) : '',
'access_token' => isset($in['access_token']) ? sanitize_text_field($in['access_token']) : '',
'event_name' => isset($in['event_name']) ? sanitize_text_field($in['event_name']) : 'Purchase',
'test_event_code' => isset($in['test_event_code']) ? sanitize_text_field($in['test_event_code']) : '',
'woocommerce_enabled' => !empty($in['woocommerce_enabled']) ? 1 : 0,
'include_user_data' => !empty($in['include_user_data']) ? 1 : 0,
'debug_logging' => !empty($in['debug_logging']) ? 1 : 0,
];
}
public static function is_woocommerce_enabled() {
$opts = get_option(self::OPT_KEY, []);
return !empty($opts['woocommerce_enabled']);
}
private function debug_log($message) {
$opts = get_option(self::OPT_KEY, []);
if (!empty($opts['debug_logging'])) {
$log_file = WP_CONTENT_DIR . '/minimal-conversions.log';
$timestamp = current_time('Y-m-d H:i:s');
$log_entry = sprintf("[%s] %s\n", $timestamp, $message);
error_log($log_entry, 3, $log_file);
}
}
public function settings_page() {
if (!current_user_can('manage_options')) return;
echo '<div class="wrap"><h1>Minimal Meta Conversions</h1>';
echo '<p class="description" style="max-width: 800px; margin-bottom: 20px;">';
echo 'This plugin provides privacy-focused, server-side conversion tracking for Meta (Facebook) ads without requiring the Meta Pixel. ';
echo 'When visitors click a Meta ad, the <code>fbclid</code> parameter is captured and stored as a first-party cookie. ';
echo 'When they reach the conversion page (containing the shortcode), a server-side event is sent to Meta\'s Conversions API, ';
echo 'allowing Meta to attribute the conversion while minimizing client-side tracking and improving compatibility with ad blockers.';
echo '</p>';
echo '<p class="description">For documentation see <a href="https://github.com/vitalseeds/minimal-conversions#">readme</a>.</p>';
echo '<form method="post" action="options.php">';
settings_fields('mmcapi_group');
do_settings_sections('minimal-meta-capi');
submit_button();
echo '</form>';
echo '<hr />';
echo '<p><strong>Usage:</strong> Add shortcode <code>[meta_capi_conversion]</code> to your conversion/thank-you page.</p>';
echo '<p>This plugin stores <code>fbclid</code> in a first-party cookie and sends one server-side event when the shortcode renders.</p>';
echo '</div>';
}
public function shortcode_fire_conversion($atts) {
// Prevent accidental firing in admin/editor previews.
if (is_admin()) return '';
// Parse shortcode attributes
$atts = shortcode_atts(['order_id' => 0], $atts);
$order_id = absint($atts['order_id']);
$opts = get_option(self::OPT_KEY, []);
$pixel_id = isset($opts['pixel_id']) ? $opts['pixel_id'] : '';
$token = isset($opts['access_token']) ? $opts['access_token'] : '';
$event = !empty($opts['event_name']) ? $opts['event_name'] : 'Purchase';
$testcode = !empty($opts['test_event_code']) ? $opts['test_event_code'] : '';
if (empty($pixel_id) || empty($token)) return '';
// Ensure we only fire once per browser session for this page load.
// (Very simple guard; customize if you need stronger dedupe.)
$once_key = 'mmcapi_fired_' . md5($event . '|' . (isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : ''));
if (!empty($_COOKIE[$once_key])) return '';
$fbclid = isset($_COOKIE[self::COOKIE_KEY]) ? sanitize_text_field(wp_unslash($_COOKIE[self::COOKIE_KEY])) : '';
if (empty($fbclid)) return ''; // Minimal: only report conversions that came from Meta click-through.
$fbc = $this->make_fbc_from_fbclid($fbclid);
$url = (is_ssl() ? 'https://' : 'http://') . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '') . (isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '');
// Build user_data - always include fbc, optionally include IP and user agent
$user_data = ['fbc' => $fbc];
if (!empty($opts['include_user_data'])) {
$user_data['client_ip_address'] = $this->get_client_ip();
$user_data['client_user_agent'] = isset($_SERVER['HTTP_USER_AGENT']) ? substr(sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'])), 0, 1000) : '';
}
// Build event data
$event_data = [
'event_name' => $event,
'event_time' => time(),
'action_source' => 'website',
'event_source_url' => $url,
'user_data' => array_filter($user_data),
];
// Add custom_data for Purchase events with WooCommerce order data
if ($order_id > 0 && function_exists('wc_get_order')) {
$order = wc_get_order($order_id);
if ($order) {
$event_data['custom_data'] = [
'currency' => $order->get_currency(),
'value' => floatval($order->get_total()),
];
}
}
$payload = [
'data' => [$event_data],
];
if (!empty($testcode)) $payload['test_event_code'] = $testcode;
$endpoint = sprintf('https://graph.facebook.com/v19.0/%s/events?access_token=%s', rawurlencode($pixel_id), rawurlencode($token));
$this->debug_log('Firing conversion event: ' . $event . ' | fbclid: ' . $fbclid . ' | URL: ' . $url);
$this->debug_log('API Payload: ' . wp_json_encode($payload));
$resp = wp_remote_post($endpoint, [
'timeout' => 5,
'headers' => ['Content-Type' => 'application/json'],
'body' => wp_json_encode($payload),
]);
if (is_wp_error($resp)) {
$this->debug_log('API Error: ' . $resp->get_error_message());
} else {
$response_code = wp_remote_retrieve_response_code($resp);
$response_body = wp_remote_retrieve_body($resp);
$this->debug_log('API Response [' . $response_code . ']: ' . $response_body);
}
// Set "fired" cookie for 1 hour to reduce accidental re-fires.
$expire = time() + HOUR_IN_SECONDS;
$secure = is_ssl();
setcookie($once_key, '1', $expire, COOKIEPATH ?: '/', '', $secure, true);
// Set the WC order attribution UTM parameters
if ($order_id > 0 && function_exists('wc_get_order')) {
$order = wc_get_order($order_id);
if ($order) {
$updated = false;
if (isset($_COOKIE[self::COOKIE_KEY_SOURCE])) {
$utm_source = sanitize_text_field(wp_unslash($_COOKIE[self::COOKIE_KEY_SOURCE]));
$order->update_meta_data('_wc_order_attribution_utm_source', $utm_source);
$this->debug_log('Set order #' . $order_id . ' utm_source to: ' . $utm_source);
$updated = true;
}
if (isset($_COOKIE[self::COOKIE_KEY_MEDIUM])) {
$utm_medium = sanitize_text_field(wp_unslash($_COOKIE[self::COOKIE_KEY_MEDIUM]));
$order->update_meta_data('_wc_order_attribution_utm_medium', $utm_medium);
$this->debug_log('Set order #' . $order_id . ' utm_medium to: ' . $utm_medium);
$updated = true;
}
if (isset($_COOKIE[self::COOKIE_KEY_CAMPAIGN])) {
$utm_campaign = sanitize_text_field(wp_unslash($_COOKIE[self::COOKIE_KEY_CAMPAIGN]));
$order->update_meta_data('_wc_order_attribution_utm_campaign', $utm_campaign);
$this->debug_log('Set order #' . $order_id . ' utm_campaign to: ' . $utm_campaign);
$updated = true;
}
if ($updated) {
$order->save();
}
}
}
// Silent by default; return empty to not affect page output.
return '';
}
public function woocommerce_thankyou($order_id) {
// Only fire if WooCommerce integration is enabled
if (self::is_woocommerce_enabled()) {
echo do_shortcode('[meta_capi_conversion order_id="' . absint($order_id) . '"]');
}
}
private function make_fbc_from_fbclid($fbclid) {
// Meta format commonly used: "fb.1.<timestamp>.<fbclid>"
return 'fb.1.' . time() . '.' . $fbclid;
}
private function get_client_ip() {
// Minimal + reasonably safe: prefer REMOTE_ADDR.
// (If you're behind a trusted proxy/CDN, adapt this carefully.)
return isset($_SERVER['REMOTE_ADDR']) ? sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR'])) : '';
}
}
new Minimal_Meta_CAPI_No_Pixel();