Jan 27, 2023 4:06 PM - edited Jan 27, 2023 4:06 PM
Jan 30, 2023 2:14 PM
Could you guide me on using the communication preference api. crm()->communicationPreference() not working. What methods do we chain for this?.
Jan 30, 2023 3:18 PM
My class creates $this->api connection and this method handles subscribing an email address (using PHP). Hope this helps.
use HubSpot\Client\CommunicationPreferences\Model\PublicUpdateSubscriptionStatusRequest;
use HubSpot\Client\CommunicationPreferences\ApiException as HubSpotApiException;
public function subscribeByEmail(string $email, string $subscription_id, string $legal_basis, string $legal_basis_explanation): bool {
try {
$public_update_subscription_status_request = new PublicUpdateSubscriptionStatusRequest();
if (in_array($legal_basis, $public_update_subscription_status_request->getLegalBasisAllowableValues())) {
$public_update_subscription_status_request->setEmailAddress($email);
$public_update_subscription_status_request->setLegalBasis($legal_basis);
$public_update_subscription_status_request->setLegalBasisExplanation($legal_basis_explanation);
$public_update_subscription_status_request->setSubscriptionId($subscription_id);
$response = $this->api->communicationPreferences()->statusApi()->subscribe($public_update_subscription_status_request);
if ($response->getStatus() === 'SUBSCRIBED') {
$this->return['success'] = true;
$this->return['message'] = '';
} else {
$this->return['success'] = false;
$this->return['message'] = "Subscribe returned a status of " . $response->getStatus();
}
} else {
$this->return['success'] = false;
$this->return['message'] = "Legal basis ({$legal_basis}) is invalid.";
}
} catch (HubSpotApiException $e) {
if ($e->getCode() == 400) {
if (strpos($e->getMessage(), 'already subscribed') !== false) {
$this->return['success'] = true;
$this->return['message'] = "Email ({$email}) already subscribed to {$subscription_id}.";
} elseif (strpos($e->getMessage(), 'cannot be updated because they have unsubscribed') !== false) {
$this->return['success'] = false;
$this->return['message'] = "Cannot resubscribe ({$email}) to {$subscription_id}.";
} else {
throw new ApiException($e->getMessage(), $e->getCode(), $e->getResponseHeaders(), $e->getResponseBody(), $e);
}
} elseif ($e->getCode() == 404 && strpos($e->getMessage(), 'does not exist') !== false) {
$this->return['success'] = false;
$this->return['message'] = "Subscription ID {$subscription_id} does not exist.";
} else {
throw new ApiException($e->getMessage(), $e->getCode(), $e->getResponseHeaders(), $e->getResponseBody(), $e);
}
}
return $this->return['success'];
}
Jan 27, 2023 4:48 PM
Via the API? I think you have to use the Communication Preferences API for this. I don't think there is a way to do them together. Communication Preferences are linked to email address and not contact ID.