Last active
August 10, 2024 10:56
-
-
Save goranefbl/860f5422ea8e1d9427b35b8a9ef477e7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
add_action('wpgens_raf_new_user_referral_id', 'process_new_user_referral', 10, 2); | |
function process_new_user_referral($referral_id, $user_id) { | |
// Get user data | |
$user = get_userdata($user_id); | |
$email = $user->user_email; | |
// Send to Klaviyo | |
send_to_klaviyo($email, $referral_id); | |
} | |
function send_to_klaviyo($email, $referral_id) { | |
// Klaviyo API endpoint for retrieving profile | |
$url = 'https://a.klaviyo.com/api/profiles/'; | |
// Your Klaviyo private API key | |
$api_key = 'YOUR_API_KEY'; | |
// Step 1: Retrieve Klaviyo Profile ID | |
$response = wp_remote_get($url . "?filter=equals(email,\"" . urlencode($email) . "\")", [ | |
'headers' => [ | |
'Authorization' => 'Klaviyo-API-Key ' . $api_key, | |
'Accept' => 'application/json', | |
'Revision' => '2024-02-15' | |
] | |
]); | |
if (is_wp_error($response)) { | |
error_log('Failed to retrieve Klaviyo profile: ' . $response->get_error_message()); | |
return; | |
} | |
$body = json_decode(wp_remote_retrieve_body($response), true); | |
if (empty($body['data'][0]['id'])) { | |
error_log('Klaviyo profile not found for email: ' . $email); | |
return; | |
} | |
$klaviyo_user_id = $body['data'][0]['id']; | |
// Step 2: Update Klaviyo Profile with Referral ID | |
$update_body = json_encode([ | |
'data' => [ | |
'type' => 'profile', | |
'id' => $klaviyo_user_id, | |
'attributes' => [ | |
'properties' => [ | |
'raferral_code' => $referral_id | |
] | |
] | |
] | |
]); | |
$update_response = wp_remote_request($url . $klaviyo_user_id . '/', [ | |
'method' => 'PATCH', | |
'headers' => [ | |
'Authorization' => 'Klaviyo-API-Key ' . $api_key, | |
'Content-Type' => 'application/json', | |
'Accept' => 'application/json', | |
'Revision' => '2024-02-15' | |
], | |
'body' => $update_body | |
]); | |
if (is_wp_error($update_response)) { | |
error_log('Failed to update Klaviyo profile: ' . $update_response->get_error_message()); | |
} else { | |
$update_body = wp_remote_retrieve_body($update_response); | |
$update_data = json_decode($update_body, true); | |
if (isset($update_data['errors'])) { | |
error_log('Klaviyo API error: ' . print_r($update_data['errors'], true)); | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment