Skip to content

Instantly share code, notes, and snippets.

@pogla
Last active October 8, 2024 16:49
Show Gist options
  • Save pogla/fd4ec610e1a33d4221d569fed48d02aa to your computer and use it in GitHub Desktop.
Save pogla/fd4ec610e1a33d4221d569fed48d02aa to your computer and use it in GitHub Desktop.
Add Beehiiv Subscriber via API
<?php
/**
* This file subscribes a subscriber to Beehiiv via API.
* Documentation: https://developers.beehiiv.com/api-reference/subscriptions/create
*/
/**
* Change this to your publication ID.
*
* @return string
*/
function get_beehiiv_publication_id() {
return 'pub_***';
}
/**
* Change this to your API key.
*
* @return string
*/
function get_beehiiv_api() {
return '***';
}
/**
* Subscribe to Beehiiv via API.
*
* @param $data
* @return false|mixed
*/
function subscribe_beehiiv( $data ) {
$publication_id = get_beehiiv_publication_id();
$api_key = get_beehiiv_api();
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.beehiiv.com/v2/publications/$publication_id/subscriptions",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode( $data ),
CURLOPT_HTTPHEADER => [
"Accept: application/json",
"Authorization: Bearer $api_key",
"Content-Type: application/json"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
if ( $err ) {
return false;
}
curl_close($curl);
$response = json_decode( $response, true );
return $response['data']['id'];
}
/**
* Subscriber data.
*/
$email = '[email protected]';
$utm_campaign = 'Test Campaign';
$utm_source = 'Test Source';
$utm_medium = 'Test Medium';
$referring_site = 'test.com';
$first_name = 'Test';
$last_name = 'Test';
$custom_fields = [];
if ( $first_name ) {
$custom_fields[] = [
'name' => 'First Name',
'value' => $first_name,
];
}
if ( $last_name ) {
$custom_fields[] = [
'name' => 'Last Name',
'value' => $last_name,
];
}
$subscription_id = subscribe_beehiiv(
[
'email' => $email,
'utm_source' => $utm_source,
'utm_campaign' => $utm_campaign,
'referring_site' => $referring_site,
'custom_fields' => $custom_fields,
]
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment