Is it possible to read API payload variable using Google Tag Manager

Viewed 372

As the title said, I am trying to extract value for "ssoid" variable that is available in the API payload. Is it possible to do this using JS? Thank you very much!

enter image description here

Payload object:

{
    "query": "query Driver_All($customer: DriverInput!) {\n        driver(customer: $customer) {\n                authenticated\n                accounts\n                sharedAccounts\n         units {\n            count\n            previous\n            next\n            facets {\n              name\n              displayName\n              facetValues {\n                value\n                count\n              }\n            }\n            results {\n              productLineDesc\n              hasPendingTasks\n              hasAppointment\n              hasOpenDefects\n              currentStatusStage\n              status\n              activeStatusStep {\n                status\n                description\n                dateTimeFormatted\n                active\n                action\n                transactonDate\n                filterStatus\n              }\n              openDefectDate\n              countOfVehiclesWithPendingTasks\n              showMiles\n              showReeferHours\n              showStandbyHours\n              groups {\n                id\n                name\n              }\n              workflows {\n                section\n                steps {\n                  dateTimeFormatted\n                  description\n                  active\n                  status\n                  action\n                  alwaysLastStep\n                  transactonDate\n                }\n              }\n              unitStatus{\n                maintenanceStatusDate,\n                maintenanceStatusDescription\n                roadsideCaseStatusDate\n                roadsideCaseStatusDescription\n                odometerStatusDate\n                odometerStatusDescription\n               }\n               unitSummary {\n                location {\n                  locationSummary {\n                    locationCode\n                    locationId\n                    locationName\n                    street1\n                    street2\n                    city\n                    state\n                    zip\n                    latitude\n                    longitude\n                  }\n                  shop {\n                    phone\n                  }\n                }\n                unitId\n                unitNumber\n                customerUnitNumber\n                vehicleVin\n                odometer\n                odometerReadingDate\n                chassisMake\n                chassisModel\n                locationNumber\n                locationName\n                nextPM\n                pMLastDate\n                pMNextDate\n                vehicleMake\n                vehicleYear\n                vehicleModel\n              }\n              unitDetail {\n                accountNumber\n                fISAccountNumber\n                customerAssignedNumber\n                isShared\n                engineMake\n                engineModel\n                unitType\n                vehicleLicenseDate\n                vehicleLicenseTag\n                accountMgrNational\n                chassisAxleCount\n                chassisGearRatio\n                transMake\n                transModel\n                transNoSpeeds\n                suspensionMake\n                suspensionModel\n                suspensionType\n                vehicleGVWQty\n                engineEstLife\n                engineHP\n                engineNumCylinders\n                leaseExpirationDate\n                leaseTermMonths\n                tireSizeFront\n                tireSizeRear\n                tTTUnitType\n                billingDistrictCode\n                physicalDistrictCode\n                hasLiftgate\n                isRefrigerated\n                bodyLength\n                bodyHeight\n                bodyWidth\n                bodyType\n                referMake\n                referModel\n                rearAxleMake\n                rearAxleModel\n                rearAxleType\n              }\n              unitAppointment\n              {\n                appointmentId\n                appointmentDate\n                appointmentStatus\n                appointmentEndTime\n                appointmentLocation\n                appointmentStartTime\n                appointmentWorkItems\n                formattedTime\n                formattedAppointmentDate\n              }\n              vehicleOdometer {\n                lastBilledDate\n                billingToDate\n                billingFromDate\n                billingDueDate\n                billedOdometer\n                billedReeferHours\n                billedStdByHours\n                lastReadingDate\n                lastOdometerReading\n                lastReeferHoursReading\n                lastStandByHoursReading\n                odometerUnitOfMeasure\n                source\n              }\n            }\n          }\n        }\n}",
    "variables": {
        "customer": {
            "userName": "abc.com",
            "id": "4b470c91-5425-4b95-9bb9-393a8f4c6af7",
            "ssoid": "14642008",
            "token": "",
            "firstName": "FN",
            "lastName": "LN",
            "accessingOneVehicleNumber": "",
            "unitsPage": "?maximumRows=20&startPageIndex=1&sortBy=StatusOrder ASC, StatusOrder < 16 ? ActiveStatusStep.TransactionDateTime.Value.Date : DateTime.Now.Date ASC, UnitSummary.UnitNumber ASC",
            "phoneNumber": "+1 566-444-4444"
        }
    }
}```
1 Answers

Not sure how you want to integrate it with Google Tag Manager, but this script will intercept fetch requests and allow you to access the body/payload as JSON, then forward the request after getting what you need from the request payload. Tested in Chrome and Firefox. Thanks to the following resources for helping build this solution: capturing fetch requests and this github issue showing how to clone a request.

If you need help making this work with GTM, then please provide more details on what you are trying to accomplish and I will look into it.

window.fetch = new Proxy(window.fetch, {
  apply(fetch, that, args) {
    return (async() => {
      try {
        //change this condition to only match the request you want to intercept
        var req = args[0];
        if (req.method === "POST") {
          //clone the request because payload can only be consumed once.
          var payload = await req.clone().json();
          console.log({payload});
        }
      } catch (e) {
        console.log(e)
      };
      //Perform fetch
      const result = fetch.apply(that, args);
      return result;
    })()
  }
});

Edit: args[0] should refer to the Request object. method refers to the request method property, which should be "POST" since you are expecting a payload to be sent with the request.

If for some reason the first item in the args array is not a request object, you can change the reference to the index, but I'm not sure why it wouldn't be. You can log all the args to the console to troubleshoot that part.

I mentioned in the comment that you can change that condition to suit your needs. For example, if there is a specific URL path you want to target, then you can add that logic to the if statement. For other options, check out the link about request objects above, or simply log the whole thing to console to see all the request properties.

var path = "api/path/";
if (req.method === "POST" && req.url.indexOf(path) > -1) {
  //clone the request because payload can only be consumed once.
  var payload = await req.clone().json();
  console.log({payload});
}
Related