Guide on how to set up / personalize the unsubscribe functionality

Customization of the unsupscribe function is represented in the following php codes:

Functions:

<?php
function BPMAuth(){
    $url = 'https://bpmonline.com/ServiceModel/AuthService.svc/Login';//someBPMURL
    $requestData["UserName"] = "";
    $requestData["UserPassword"] = "";    
    $jcres = json_encode($requestData);    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_COOKIEJAR,'cookie.txt');
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jcres);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($jcres))
    );
    $result = curl_exec($ch);
    curl_close($ch);
}
function BPMQuery($json,$operation) {
    //Operations: 1-Add Data; 2 - Update Data; 3 - batch Data; 4 - SelectQuery
    switch ($operation) {
    case 1:
        $queryOperation='InsertQuery';
        break;
    case 2:
        $queryOperation='UpdateQuery';
        break;
    case 3:
        $queryOperation='BatchQuery';
        break;
    case 4:
        $queryOperation='SelectQuery';
        break;
}
    $url = 'https://bpmonline.com/0/DataService/json/SyncReply/'.$queryOperation;
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
    curl_setopt($ch, CURLOPT_COOKIEJAR,'cookie.txt');
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0); 
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($json))
    );
    return curl_exec($ch);
    curl_close($ch);
} // Sends Update Query to BPM
function BuildIdFilter(array $array){
    $i=0;
    $filter='';
    foreach ($array as $item)
        {
            if ($i!=0) $filter.=',';
            $filter.='
            "CustomFilters'.$i.'":{
            "filterType":1,
            "comparisonType":3,
            "isEnabled":true,
            "trimDateTimeParameterToDate":false,
            "leftExpression":{
    		   "expressionType":0,
    		   "columnPath":"Id"
    			},
            "rightExpression":{
               "expressionType":2,
               "parameter":{
                  "dataValueType":0,
                  "value":"'.$item.'"
               }
            }
         }';
        $i++;  
 
        }
    return $filter;
} // Build Json Array Filter
function BuildSubscribeJson($filter,$bool){
    //$filter is filter to be applied in Json
    //$bool - to set true (Subscribed) or false(unsubscribed) for subscription
    if($bool==true) {$subsvalue='1a5cd9b8-b999-4b65-b8a8-bd3168792128';}
    else {$subsvalue='c8947f80-a374-412a-bbc8-ea9068a8b78e';}
    return '{
                           "rootSchemaName":"BulkEmailSubscription",
                           "operationType":2,
                           "filters":{
                              "items":{
                                 '.$filter.'
                              },
                              "logicalOperation":1,
                              "isEnabled":true,
                              "filterType":6
                           },
                           "columnValues":{
                              "items":{
                                 "BulkEmailSubsStatus":{
                                    "expressionType":2,
                                    "parameter":{
                                       "dataValueType":10,
                                       "value":"'.$subsvalue.'"
                                    }
                                 }
                              }
                           },
                           "isForceUpdate":false
                        }';
 
}
function JsonAddNewSubscriber($contactId,array $bulkemailtype,$bool_subsctiption){
    //$contactId Id of contuct to be subscribed
    //$bulkemailtype is id of bulk email to be subscribed
    //$bool_subsctiption - to set true (Subscribed) or false(unsubscribed) for subscription
    if($bool_subsctiption==true) {$subsvalue='1a5cd9b8-b999-4b65-b8a8-bd3168792128';}
    else {$subsvalue='c8947f80-a374-412a-bbc8-ea9068a8b78e';}
    $i=0;
    $insertItems='';
 
 
    foreach ($bulkemailtype as $value) {
        if ($i!=0) $insertItems.=',';
        $insertItems.='{
            "__type": "Terrasoft.Nui.ServiceModel.DataContract.InsertQuery",
 
           "rootSchemaName":"BulkEmailSubscription",
           "operationType":1,
           "columnValues":{
              "items":{
                 "Contact":{
                    "expressionType":2,
                    "parameter":{
                       "dataValueType":10,
                       "value":"'.$contactId.'"
                    }
                 },
                 "BulkEmailType":{
                    "expressionType":2,
                    "parameter":{
                       "dataValueType":10,
                       "value":"'.$value.'"
                    }
                 },
                 "BulkEmailSubsStatus":{
                    "expressionType":2,
                    "parameter":{
                       "dataValueType":10,
                       "value":"'.$subsvalue.'"
                    }
                 }
              }
           }
 
        }';
        $i++;
    }
    return '{"items": ['.$insertItems.']}';
}
function ContactUnsubscribe($contactId,$bool){
    return '{
  "rootSchemaName": "Contact",
  "operationType": 2,
  "filters": {
    "items": {
      "primaryColumnFilter": {
        "filterType": 1,
        "comparisonType": 3,
        "isEnabled": true,
        "trimDateTimeParameterToDate": false,
        "leftExpression": {
          "expressionType": 1,
          "functionType": 1,
          "macrosType": 34
        },
        "rightExpression": {
          "expressionType": 2,
          "parameter": {
            "dataValueType": 0,
            "value": "'.$contactId.'"
          }
        }
      }
    },
    "logicalOperation": 0,
    "isEnabled": true,
    "filterType": 6
  },
  "columnValues": {
    "items": {
      "DoNotUseEmail": {
        "expressionType": 2,
        "parameter": {
          "dataValueType": 12,
          "value": '.$bool.'
        }
      }
    }
  },
  "isForceUpdate": false
}'; // Json Request
}
function JsonSelectSubscriptions($contactId){
    $json= '{
       "rootSchemaName":"BulkEmailSubscription",
       "operationType":0,
       "filters":{
          "items":{
             "customFilterContact_BulkEmailSubscription":{
                "filterType":1,
                "comparisonType":3,
                "isEnabled":true,
                "trimDateTimeParameterToDate":false,
                "leftExpression":{
                   "expressionType":0,
                   "columnPath":"Contact"
                },
                "rightExpression":{
                   "expressionType":2,
                   "parameter":{
                      "dataValueType":10,
                      "value":"'.$contactId.'"
                   }
                }
             }
          },
          "logicalOperation":0,
          "isEnabled":true,
          "filterType":6
       },
       "columns":{
          "items":{
             "Id":{
                "caption":"",
                "orderDirection":0,
                "orderPosition":-1,
                "isVisible":true,
                "expression":{
                   "expressionType":0,
                   "columnPath":"Id"
                }
             },
             "BulkEmailType":{
                "caption":"Bulk email type",
                "orderDirection":0,
                "orderPosition":-1,
                "isVisible":true,
                "expression":{
                   "expressionType":0,
                   "columnPath":"BulkEmailType"
                }
             },
             "BulkEmailSubsStatus":{
                "caption":"Subscription status",
                "orderDirection":0,
                "orderPosition":-1,
                "isVisible":true,
                "expression":{
                   "expressionType":0,
                   "columnPath":"BulkEmailSubsStatus"
                }
             }
          }
       },
       "isDistinct":false,
       "rowCount":30,
       "rowsOffset":0,
       "isPageable":false,
       "allColumns":false,
       "useLocalization":true,
       "useRecordDeactivation":false,
       "serverESQCacheParameters":{
          "cacheLevel":0,
          "cacheGroup":"",
          "cacheItemName":""
       },
       "queryOptimize":false,
       "useMetrics":false,
       "querySource":0,
       "ignoreDisplayValues":false,
       "conditionalValues":null,
       "isHierarchical":false
    }'; // Json Request
    return $json;
}
function JsonSelectdefaultchannels(){
    $json= '{"rootSchemaName":"BulkEmailType","operationType":0,"filters":{"items":{"64ae0f22-cb41-4599-97c1-3571c0fe56f3":{"items":{},"logicalOperation":0,"isEnabled":true,"filterType":6}},"logicalOperation":0,"isEnabled":true,"filterType":6},"columns":{"items":{"Id":{"caption":"","orderDirection":0,"orderPosition":-1,"isVisible":true,"expression":{"expressionType":0,"columnPath":"Id"}},"Name":{"caption":"","orderDirection":0,"orderPosition":-1,"isVisible":true,"expression":{"expressionType":0,"columnPath":"Name"}},"Description":{"caption":"Description","orderDirection":0,"orderPosition":-1,"isVisible":true,"expression":{"expressionType":0,"columnPath":"Description"}},"IsSignable":{"caption":"Can be subscriber","orderDirection":0,"orderPosition":-1,"isVisible":true,"expression":{"expressionType":0,"columnPath":"IsSignable"}},"EntryPointsCount":{"caption":"","orderDirection":0,"orderPosition":-1,"isVisible":true,"expression":{"expressionType":3,"aggregationType":1,"columnPath":"[EntryPoint:EntityId].Id","subFilters":{"items":{"c0c2fa11-5faa-415d-98d6-83df4bb90770":{"filterType":1,"comparisonType":3,"isEnabled":true,"trimDateTimeParameterToDate":false,"leftExpression":{"expressionType":0,"columnPath":"IsActive"},"rightExpression":{"expressionType":2,"parameter":{"dataValueType":1,"value":true}}}},"logicalOperation":0,"isEnabled":true,"filterType":6}}},"CreatedOn":{"caption":"","orderDirection":0,"orderPosition":-1,"isVisible":true,"expression":{"expressionType":0,"columnPath":"CreatedOn"}},"CreatedBy":{"caption":"","orderDirection":0,"orderPosition":-1,"isVisible":true,"expression":{"expressionType":0,"columnPath":"CreatedBy"}},"ModifiedOn":{"caption":"","orderDirection":0,"orderPosition":-1,"isVisible":true,"expression":{"expressionType":0,"columnPath":"ModifiedOn"}},"ModifiedBy":{"caption":"","orderDirection":0,"orderPosition":-1,"isVisible":true,"expression":{"expressionType":0,"columnPath":"ModifiedBy"}},"ProcessListeners":{"caption":"","orderDirection":0,"orderPosition":-1,"isVisible":true,"expression":{"expressionType":0,"columnPath":"ProcessListeners"}}}},"isDistinct":false,"rowCount":30,"rowsOffset":0,"isPageable":true,"allColumns":false,"useLocalization":true,"useRecordDeactivation":false,"serverESQCacheParameters":{"cacheLevel":0,"cacheGroup":"","cacheItemName":""},"queryOptimize":false,"useMetrics":false,"querySource":0,"ignoreDisplayValues":false,"conditionalValues":null,"isHierarchical":false}';
    return $json;
}
function JsonSelectEmailStatus($contactId){
    $json= '{
       "rootSchemaName":"Contact",
       "operationType":0,
       "filters":{
          "items":{
    		 "CustomFilters":{
    			"filterType":1,
    			"comparisonType":3,
    			"isEnabled":true,
    			"trimDateTimeParameterToDate":false,
    			"leftExpression":{
    			   "expressionType":0,
    			   "columnPath":"Id"
    			},
    			"rightExpression":{
    			   "expressionType":2,
    			   "parameter":{
    				  "dataValueType":0,
    				  "value":"'.$contactId.'"
    			   }
    			}
    		 }
    	  },
          "logicalOperation":0,
          "isEnabled":true,
          "filterType":6
       },
       "columns":{
          "items":{
             "DoNotUseEmail":{
                "caption":"Do not use email",
                "orderDirection":0,
                "orderPosition":-1,
                "isVisible":true,
                "expression":{
                   "expressionType":0,
                   "columnPath":"DoNotUseEmail"
                }
             }
          }
       },
       "isDistinct":false,
       "rowCount":30,
       "rowsOffset":0,
       "isPageable":false,
       "allColumns":false,
       "useLocalization":false,
       "useRecordDeactivation":false,
       "serverESQCacheParameters":{
          "cacheLevel":0,
          "cacheGroup":"",
          "cacheItemName":""
       },
       "queryOptimize":false,
       "useMetrics":false,
       "querySource":0,
       "ignoreDisplayValues":false,
       "conditionalValues":null,
       "isHierarchical":false
    }';
    return $json;
}

Unsubscription channels:

<?php
$contactId=$_GET['contactId'];
//contactId for test = 2480fb60-43d1-4a58-9011-0f859b431670 for test
require_once( MODX_CORE_PATH . 'model/bpmintegration/bpm_bulk_subscriptionsFunctions.php');
BPMAuth();
$jsonUseEmailQuery = JsonSelectEmailStatus($contactId);
$result = BPMQuery($jsonUseEmailQuery,4);
$r0 = json_decode($result,true);
$requestData1 = JsonSelectSubscriptions($contactId);
$result = BPMQuery($requestData1,4);
$r=json_decode($result, true);
$requestData1=JsonSelectdefaultchannels();
$result = BPMQuery($requestData1,4);
$r2=json_decode($result, true);
{//building html form 
    echo '<form method = "post" action = "/index.php?id=14&contactId='.$contactId.'">';
    if ($r0["rows"]["0"]["DoNotUseEmail"]==1) {
 
        echo '<h4>You are currently Unsubscribed from all emails, please uncheck Subscribe me back, if you wish to keep current setting on.</h4>';
        echo '<input type="checkbox" name="Subscribemeback" value="1" checked> Subscribe me back <br>';
    }
    echo '<h2>Subsctiption types</h2>';
    //print_r($r);
    foreach ($r["rows"] as $value) {
        echo '<input type="checkbox" style="display:none" name="SubscriptionData[]" value="'.$value["Id"].'" checked>';
        if ($value["BulkEmailSubsStatus"]["displayValue"]=='Subscribed'){
            echo '<input type="checkbox" name="CurrentSubscription[]" value="'.$value["Id"].'" checked> '.$value["BulkEmailType"]["displayValue"].'<br/>';
        }else{
            echo '<input type="checkbox" name="CurrentSubscription[]" value="'.$value["Id"].'"> '.$value["BulkEmailType"]["displayValue"].'<br/>';
        }
        } // Display channels already set for client
    foreach ($r2["rows"] as $value){
        foreach ($r["rows"] as $value1) {
            if ($value["Id"]==$value1["BulkEmailType"]["value"]){
                $exist=1;
            }
        }
     if (!$exist) {
         echo '<input type="checkbox" style="display:none" name="defaultsubscriptionschannels[]" value="'.$value["Id"].'" checked>';
         echo '<input type="checkbox" name="defaultsubscriptions[]" value="'.$value["Id"].'" checked> '.$value["Name"].'<br/>';
     } //if there is no such channel in basic subscription - echo some inputs
     else unset ($exist);
    } // Display Default Channels
    if ($r0["rows"]["0"]["DoNotUseEmail"]!=1) {
        echo ' <h2> OR Unsubscribe from all?</h2>
        <input type="checkbox" name="Unsibscribe_all" value="1"> Unsibscribe from all emails<br>';
    }
    echo '<input type="submit" value="Submit">
    </form>';
}//building form

Unsubscription channel request:

<?php
//$_POST['SubscriptionData']- array with all subscription preferances for current ContactID
//$_POST['CurrentSubscription'] - array with data to be subscribed
//$_POST['Defaultsubscriptions'] -array with default channels to add to subscriptions
//$_POST['defaultsubscriptionschannels'] - array with default channels
$contactId=$_GET['contactId'];
require_once( MODX_CORE_PATH . 'model/bpmintegration/bpm_bulk_subscriptionsFunctions.php');
BPMAuth();
if ($_POST['Subscribemeback']==1){
    $requestData1=ContactUnsubscribe($contactId,false);
    BPMQuery($requestData1,2);
    echo 'You were subscribed back';
}
if ($_POST['Unsibscribe_all']==1){
    $requestData1=ContactUnsubscribe($contactId,true);
    BPMQuery($requestData1,2);
    echo 'Unsubscribed from all';
    } // If Unsubscribed - post "Do no use email in BPM"
    else {
        echo '<h2>Subscription Channels were Updated</h2>';
        if (isset($_POST['CurrentSubscription'])){
            $filter=BuildIdFilter($_POST['CurrentSubscription']);
            $JsonSubscribe=BuildSubscribeJson($filter,true);// Json for Subscription Data
            BPMQuery($JsonSubscribe,2);
            $ToSetUnsubscribed=array_diff($_POST['SubscriptionData'],$_POST['CurrentSubscription']);//this is array to set unsubscribe status
            if (!empty($ToSetUnsubscribed)){
                 $filter=BuildIdFilter($ToSetUnsubscribed);
                 $JsonSubscribe=BuildSubscribeJson($filter,false);
                 BPMQuery($JsonSubscribe,2);
            }
        } 
        elseif(isset($_POST['SubscriptionData'])){
            $filter=BuildIdFilter($_POST['SubscriptionData']);
            $JsonSubscribe=BuildSubscribeJson($filter,false);
            BPMQuery($JsonSubscribe,2);//UpdateBPM
        }
        if (isset($_POST['defaultsubscriptionschannels'])){
            if (isset($_POST['defaultsubscriptions'])){
                $JsonSubscribe=JsonAddNewSubscriber($contactId,$_POST['defaultsubscriptions'],true);
                BPMQuery($JsonSubscribe,3);//UpdateBPM
                $ToAddUnsubscribed=array_diff($_POST['defaultsubscriptionschannels'],$_POST['defaultsubscriptions']);
                if (!empty($ToAddUnsubscribed)){
                    $JsonSubscribe=JsonAddNewSubscriber($contactId,$ToAddUnsubscribed,false);
                    BPMQuery($JsonSubscribe,3);//UpdateBPM
                    }
                }else{
                    $JsonSubscribe=JsonAddNewSubscriber($contactId,$_POST['defaultsubscriptionschannels'],false);
                    BPMQuery($JsonSubscribe,3);//UpdateBPM
                }
            }
        }// Defines array to add new subscription channels
?>

For additional assistance, see the video instruction at https://drive.google.com/file/d/1vJipUf0m04Mk_r3QLAakcwdXYtEon--J/view.

Like 2

Like

Share

0 comments
Show all comments