Snippets

Vlad Silak AFP Preference Center

Created by Vlad Silak last modified
<script runat="server">
  /*
   * entry here should be done from the email using following notation:
   * <a href="%%=RedirectTo(CloudPagesURL(ID)=%%">Unsubscribe from these communications</a>
   */
  Platform.Load("Core", "1");
  var error = false, errorMessage = "", data;
  var proxy = new Script.Util.WSProxy();
  var PARAMS = {};
  PARAMS.contactKey = Attribute.GetValue("_subscriberkey");
  PARAMS.emailAddress = Attribute.GetValue("emailaddr");
  PARAMS.emailID = Attribute.GetValue("_emailid");
  PARAMS.dataSourceName = Attribute.GetValue("_DataSourceName");
  PARAMS.listID = Attribute.GetValue("listID");
  PARAMS.jobID = Attribute.GetValue("jobID");
  PARAMS.batchID = Attribute.GetValue("_JobSubscriberBatchID");
  PARAMS.subscriberID = Attribute.GetValue("subscriberID");
  PARAMS.emailName = Attribute.GetValue("emailname_");
  PARAMS.listName = Attribute.GetValue("_listname");
  PARAMS.unsubLogDEKey = "DATA_EXTENSION_KEY";

  /* the processing should only occur when there are email and contact ID's available */
  if (PARAMS.emailID.length > 0 && PARAMS.contactKey.length > 0) {

    try {
      /* get field name from publication list details */
      var props = ["Description"];
      var filter = {
        Property: "ID"
        , SimpleOperator: "equals"
        , Value: PARAMS.listID
      };
      data = proxy.retrieve("List", props, filter);
      if (data.Results.length > 0) {
        PARAMS.preferenceField = data.Results[0].Description;
        Variable.SetValue("@preferenceField", PARAMS.preferenceField);
      }

      /* get send event date */
      props = ["EventDate", "SubscriberKey", "EventType"];
      filter = {
        LeftOperand: {
          Property: "SendID"
          , SimpleOperator: "equals"
          , Value: PARAMS.jobID
        }
        , LogicalOperator: "AND"
        , RightOperand: {
          Property: "BatchID"
          , SimpleOperator: "equals"
          , Value: PARAMS.batchID
        }
        , AdditionalOperand: {
          Property: "SubscriberID"
          , SimpleOperator: "equals"
          , Value: PARAMS.subscriberID
        }
      };
      data = proxy.retrieve("SentEvent", props, filter);
      if (data.Results.length > 0) {
        PARAMS.sendDate = data.Results[0].EventDate;
        Variable.SetValue("@sendDate", PARAMS.sendDate);
      }

</script>
%%[  
  SET @contactKey = _subscriberkey
  SET @crmUpdated = true
  /* prepare unsubscribe event dates for the log */
  SET @eventDate = NOW()
  SET @localEventDate = SystemDateToLocalDate(@eventDate)
  SET @localSendDate = SystemDateToLocalDate(@sendDate)

  /* ensure contact is SF Contact */
  IF NOT (Substring(@contactKey, 1, 3) == "003" AND Substring(@preferenceField, Subtract(Length(@preferenceField),2))  == "__c") THEN
    /* ERROR - log that we can't update CRM */
    SET @crmUpdated = false
  ELSE
    /* get the Communication Preferences Object */
    SET @rs = RetrieveSalesforceObjects('Contact', 'AfP_Communication_Preference__c', 'Id', '=', @contactKey)
    IF (ROWCOUNT(@rs) > 0) THEN
      SET @cpID = FIELD(ROW(@rs, 1), 'AfP_Communication_Preference__c')
    ELSE 
      SET @rs = RetrieveSalesforceObjects('Communication_Preference__c', 'Id', 'Contact__c', '=', @contactKey, 'Business_Unit__c', '=', 'Act for Peace')
      IF (ROWCOUNT(@rs) > 0) THEN
        SET @cpID = FIELD(ROW(@rs, 1), 'Id')
      ELSE
        /* ERROR - log that we can't update CRM */
        SET @crmUpdated = false
      ENDIF
    ENDIF
  ENDIF

  /* check we have communication preference ID */
  IF NOT EMPTY(@cpID) THEN
    SET @updateRecord = UpdateSingleSalesforceObject (
      "Communication_Preference__c", @cpID
      , @preferenceField, "Yes"
    )
    IF @updateRecord < 1 THEN
      SET @crmUpdated = false
    ENDIF
  ENDIF

]%%
<script runat="server">
    } catch (e) {
      /* might need to log it in some way */
      errorMessage += e.message + " \n<br>\n<br> " + e.description;
      Variable.SetValue("@errorMessage", errorMessage);
    }

    /* pull out additional parameters from AMPscript context */
    PARAMS.crmUpdated = Variable.GetValue("@crmUpdated");
    PARAMS.eventDate = Variable.GetValue("@eventDate");
    PARAMS.localEventDate = Variable.GetValue("@localEventDate");
    PARAMS.localSendDate = Variable.GetValue("@localSendDate");

    /* log event and add record to the unsub log */
    try {
      var props = [
        { Name: "SubscriberID", Value: PARAMS.subscriberID }
        , { Name: "JobID", Value: PARAMS.jobID }
        , { Name: "ListID", Value: PARAMS.listID }
        , { Name: "BatchID", Value: PARAMS.batchID }
        , { Name: "Reason", Value: PARAMS.emailName }
      ];

      data = proxy.execute(props, "LogUnsubEvent");

      Variable.SetValue("@resultLength", data.Results.length);
      Variable.SetValue("@resultStatus", data.Results[0].StatusCode);

      /* retrieve request ID for the record if event processed successfully*/
      if (data.Results.length > 0 && data.Results[0].StatusCode == "OK") {
        PARAMS.logUnsubEventRequestID = data.RequestID;
      } else {
        if (data.Results.length > 0 && data.Results[0].StatusCode == "Error" && data.Results[0].ErrorCode == 401) {
          /* the subscriber is already unsubscribed */
          PARAMS.logUnsubEventRequestID = "Alredy Unsubscribed";
        } else {
          /* some error occurred on API layer - this one is managed */
          PARAMS.logUnsubEventRequestID = "API ERROR | " + data.RequestID;
          error = true;
        }
      }

      /* add record to the event log DE */
      var unsubRecord = {
        CustomerKey: PARAMS.unsubLogDEKey
        , Properties : [
          { Name: "Contact Key", Value: PARAMS.contactKey }
          , { Name: "Email Address", Value: PARAMS.emailAddress }
          , { Name: "Publication List", Value: PARAMS.listName }
          , { Name: "List ID", Value: PARAMS.listID }
          , { Name: "Batch ID", Value: PARAMS.batchID }
          , { Name: "Job ID", Value: PARAMS.jobID }
          , { Name: "Email ID", Value: PARAMS.emailID }
          , { Name: "Email Name", Value: PARAMS.emailName }
          , { Name: "Event Date", Value: PARAMS.eventDate }
          , { Name: "Local Event Date", Value: PARAMS.localEventDate }
          , { Name: "Send Date", Value: PARAMS.sendDate }
          , { Name: "Local Send Date", Value: PARAMS.localSendDate }
          , { Name: "CRM Updated", Value: PARAMS.crmUpdated }
          , { Name: "Preference Field", Value: PARAMS.preferenceField }
          , { Name: "LogUnsubEvent Request ID", Value: PARAMS.logUnsubEventRequestID }
        ]
      };
      data = proxy.createItem("DataExtensionObject", unsubRecord, null);

    } catch (e) {
      errorMessage += e.message + " \n<br>\n<br> " + e.description;
      Variable.SetValue("@errorMessage", errorMessage);
      /* flag that processing error occurred - this one is unmanaged */
      error = true;
    }
  } else {
    /* flag error - this is when contact key and email were not supplied */ 
    error = true;
  }

  /* set the flag for the content to display success/error message */
  Variable.SetValue("@error", (error) ? 1 : 0);
</script>

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.