PHP – API error [code: 422, message: “Validation failed.”]

I am trying to use my platform's API by using PHP and cURL, but I have a problem when I try to PATCH some custom attributes. As the title says, I am getting an API error with code: 422 and the message: Validation failed., because the attributes field has Invalid data?

I get this error when I am using this piece of code:

$updateServiceIP = UcrmApi::ucrmRequest("clients/services/$serviceId", 'PATCH', [
    'attributes' => [
        'value' => $IPs[$ipAddress],
        'customAttributeId' => 45
    ]
]);

var_dump($updateServiceIP); // this outputs NULL

but when I use this piece of code, the value is updated successfully:

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, '{{URL}}/crm/api/v1.0/clients/services/' . $serviceId);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH");

curl_setopt($ch, CURLOPT_POSTFIELDS, "{
    \"attributes\": [
        {
            \"value\": \"lorem ipsum\",
            \"customAttributeId\": 45
        }
    ]
}");

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    "Content-Type: application/json",
    "X-Auth-App-Key: API_KEY"
));

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);

I know that I can use the second piece of code, but I do not want to, because I have a special function that calls the API and can PATCH, POST, GET from my platform.

public static function ucrmRequest($url, $method = 'GET', $post = [])
{
    $method = strtoupper($method);

    $ch = curl_init();

    curl_setopt(
        $ch,
        CURLOPT_URL,
        sprintf(
            '%s/%s',
            self::UCRM_URL,
            $url
        )
    );
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, false);

    curl_setopt(
        $ch,
        CURLOPT_HTTPHEADER,
        [
            'Content-Type: application/json',
            sprintf('X-Auth-App-Key: %s', self::UCRM_KEY),
        ]
    );

    if ($method === 'POST') {
        curl_setopt($ch, CURLOPT_POST, true);
    } elseif ($method !== 'GET') {
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    }

    if (! empty($post)) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post));
    }

    $response = curl_exec($ch);

    if (curl_errno($ch) !== 0) {
        echo sprintf('Curl error: %s', curl_error($ch)) . PHP_EOL;
    }

    if (curl_getinfo($ch, CURLINFO_HTTP_CODE) >= 400) {
        echo sprintf('API error: %s', $response) . PHP_EOL;
        $response = false;
    }

    curl_close($ch);

    return $response !== false ? json_decode($response, true) : null;
}

What can be the problem and how can I solve it? By the way, I've read some of the similar questions, but I didn't found a solution for my problem...

PHP – Incrementing element with the same name.

If you download multiple files with the same name, a number is automatically added to the file name, for example: filename(1), filename(2) etc..

What I am trying to do is when I am creating a name and there is already a same one, the name I create to appear in the list as: name(1), name(2) etc.

This is the code that I use now that only creates: name and name (1), then I get this error when trying to create the next same name, example: name (1) already exists in your list., but I shouldn't get that error and should create the next name in the list: name (2) etc..

$deviceUser = "07NAV" . $var;
$sameNames = $mktApi->comm("/ppp/secret/getall", array(
    ".proplist" => ".id",
    "?name" => $deviceUser
));

$i = 0;
if($sameNames) {
    $i++;
    $mktApi->comm("/ppp/secret/add", array(
        "name" => $deviceUser . " ($i)",
        "remote-address" => $IPs[$ipAddress],
        "password" => $devicePass,
        "service" => "pppoe",
        "comment" => $fullAddress
    ));
}

Also, I've tried using this one:

$i = 0;
if($sameNames) {
    for($i = 0; $i < 99999; $i++) {
        $i++;
        $mktApi->comm("/ppp/secret/add", array(
            "name" => $deviceUser . " ($i)",
            "remote-address" => $IPs[$ipAddress],
            "password" => $devicePass,
            "service" => "pppoe",
            "comment" => $fullAddress
        ));
    }
}

but when I create only one name in my list, automatically creates X names and I do not want that.
I've been searching for help on other communities too and somebody provided me this code, but I still get the same error ("user with same name already exists"):

// Start your update here:
$i = 0;
$deviceUser = $deviceUserOriginal = "07NAV" . $var;
$sameNames = false;
do {
    // First - check if a dupe exists...
    $sameNames = $mktApi -> comm("/ppp/secret/getall", array(
        ".proplist" => ".id",
        "?name" => $deviceUser
    ));

    // Second - update and prepare for rechecking ...
    if($sameNames === true) {
        $i ++;
        $deviceUser = $deviceUserOriginal . "(". $i .")";
    }

    // Finally, below, if check failed, cycle and check again with the new updated name...
}
while($sameNames === true);

// Finally, tidy up.
// If you need the original value of $deviceUser you can retain it.
unset($i, $deviceUserOriginal);

// Continue your script here:
$mktApi -> comm("/ppp/secret/add", array(
    "name" => $deviceUser,
    "remote-address" => $IPs[$ipAddress],
    "password" => $devicePass,
    "service" => "pppoe",
    "comment" => $fullAddress
));

How to get IP from text area that contains multiple IPs and their CIDR?

My question is simple: I have a text area that is filled with IP/CIDR's and I want to know how I can retrieve an IP from there and then check the IP as used.

The text area (which is implemented in plugin's page configuration and I can edit the configuration page through API, I can get the value from the text area using $pluginData -> ipAddresses) I have, is filled with IP/CIDR that are separated by comma, such as: "32.89.178.0/24, 63.119.179.0/24, 23.119.180.0/24,154.119.181.0/24,193.119.182.0/24,133.119.183.0/24".

My question is: how can I retrieve all the IPs that are in that text area and show them on my admin page, aswell as setting them as a attribute to a service for my client? If it used to check it as "used" and cannot longer be used until it is unchecked.

Since I try to find a solution for my problem I just tried to use "cidrToRange" function but the only thing that I get is "Array".

Getting the value of a specific ID.

Hello,

As the title says, my question is: how I can get the values for specific ID? For example, my plugin creates a PDF that automatically fills in with information that I get using API from my CRM platform. So, what I am trying to do now, is that in my contract template I have a section where the information must be filled in with custom attributes information (NAME of the custom attribute ID 20 = VALUE of the custom attribute ID 20).

Down below is a foreach code that get me all the custom attributes at once:

foreach ($response['attributes'] as $set) {
    echo "ID: {$set['id']},\r\n"
    . "Client ID: {$set['clientId']},\r\n"
    . "Custom Attribute ID: {$set['customAttributeId']},\r\n"
    . "Name: {$set['name']},\r\n"
    . "Key: {$set['key']},\r\n"
    . "Value: {$set['value']},\r\n"
    . "Client Zone Visible: " . ($set['clientZoneVisible'] ? "true" : "false") . "\r\n";
}

This is the message that I get from the foreach code when I am accessing the plugin page on my platform:

ID: 11, Client ID: 1238, Custom Attribute ID: 18, Name: USER, Key: user, Value: CT565244, Client Zone Visible: true ID: 12, Client ID: 1238, Custom Attribute ID: 19, Name: PAROLA, Key: parola, Value: qwerty1234, Client Zone Visible: true ID: 13, Client ID: 1238, Custom Attribute ID: 20, Name: Serie C.I., Key: serieCI, Value: KZ, Client Zone Visible: true ID: 14, Client ID: 1238, Custom Attribute ID: 21, Name: Numar C.I., Key: numarCI, Value: 565244, Client Zone Visible: true ID: 15, Client ID: 1238, Custom Attribute ID: 22, Name: CNP, Key: cnp, Value: 5010214261989, Client Zone Visible: true ID: 16, Client ID: 1238, Custom Attribute ID: 23, Name: Emis de, Key: emisDe, Value: SPCLEP Navodari, Client Zone Visible: true ID: 17, Client ID: 1238, Custom Attribute ID: 24, Name: Data emiterii, Key: dataEmiterii, Value: 2019-02-21, Client Zone Visible: true

And here is the HTML code where I want to get the name and value for custom attribute ID X:

&nbsp;<strong>Seria:&nbsp;</strong>SERIA BULETIN // CUSTOM ATTRIBUTE ID 20
&nbsp;<strong>NR.:&nbsp;</strong>NR. BULETIN // CUSTOM ATTRIBUTE ID 21
&nbsp;<strong>CNP:&nbsp;</strong>COD NUMERIC PERSONAL // CUSTOM ATTRIBUTE ID 22

Here is the code for $response contents:

// API doRequest - Client Information & Custom Attributes
$response = UCRMAPIAccess::doRequest(sprintf('clients/%d', $clientId),
    'GET',
    [
        'fullAddress' => $cFAddress,
        'firstName' => $cFName,
        'lastName' => $cLName,
        'companyTaxId' => $cCompanyTaxID,
        'companyRegistrationNumber' => $cCompanyRegistrationNumber,
        'city' => $cCity,
        'street1' => $cStreet1,
        'street2' => $cStreet2,
        'organizationName' => $cOrganizationName,
        'invoiceStreet1' => $cInvoiceStreet1,
        'invoiceStreet2' => $cInvoiceStreet2,
        'invoiceCity' => $cInvoiceCity,
        'invoiceZipCode' => $cInvoiceZipCode,
        'attributes' => $cAttributes = [
            'name' => $cAttrName,
            'value' => $cAttrValue,
            'key' => $cAttrKey,
            'id' => $cAttributeID,
        ],
    ]
);

Notice: Undefined index ( PHP & API Plugin )

Hello DaniWeb Community,

I am a newbie in PHP, but I tried to create a plugin for my CRM platform using API to get informations, but I get some errors: Notice: Undefined index. Click here for an image with the errors..

Here are the lines where I got the errors:

` 
// API doRequest - Custom Attributes Information
    $customAttributes = UCRMAPIAccess::doRequest(sprintf('custom-attributes?attributeType=client')) ?: [];
    foreach($customAttributes as $customAttr) {
        $responseCA = UCRMAPIAccess::doRequest(sprintf('custom-attributes?attributeType=client'),
            'GET',
            [
                'id' => $cAttributeID,
                'key' => $cAttributeKey,
                'name' => $cAttributeName,
                'attributeType' => $cAttributeType,
                'value' => $cAttrValue,
            ]
        );

        if($responseCA !== null) {
            echo '<ul>';
                echo sprintf('<li>ID:</li> %d', $cAttributeID);
                echo sprintf('<li>key:</li> %s', $responseCA['key']); // line 117
                echo sprintf('<li>name:</li> %s', $responseCA['name']); // line 118
                echo sprintf('<li>value:</li> %s', $responseCA['value']); // line 119
            echo '</ul>';
        } else {
            echo 'There was an error retrieving custom attributes.' . PHP_EOL;
        }
     }
`

And here is where I use $_GET function:

`
// Custom Attributes Information
$cAttributeName = (isset($_GET['name']) ? $_GET['name'] : null);
$cAttributeID = (isset($_GET['id']) ? $_GET['id'] : null);
$cAttributeKey = (isset($_GET['key']) ? $_GET['key'] : null);
$cAttributeType = (isset($_GET['attributeType']) ? $_GET['attributeType'] : null);
`

What I am trying to do aswell, after I get the custom attributes, I want to get them for each client I have:

$cAttributes = (isset($_GET['attributes']) ? $_GET['attributes'] : [
    $cAttrName = (isset($_GET['name']) ? $_GET['name'] : null),
    $cAttrKey = (isset($_GET['key']) ? $_GET['key'] : null),
    $cAttrValue = (isset($_GET['value']) ? $_GET['value'] : null),
    $cAttrClientID = $clientId,
]);

This is the $_GET function for Client Custom Attributes

And this is the API doRequest function for clients, where I had added the attributes, but I don't know if I did it right.

// API doRequest - Client Information & Custom Attributes
    $response = UCRMAPIAccess::doRequest(sprintf('clients/%d', $clientId),
        'GET',
        [
            'fullAddress' => $cFAddress,
            'firstName' => $cFName,
            'lastName' => $cLName,
            'companyTaxId' => $cCompanyTaxID,
            'companyRegistrationNumber' => $cCompanyRegistrationNumber,
            'city' => $cCity,
            'street1' => $cStreet1,
            'street2' => $cStreet2,
            'organizationName' => $cOrganizationName,
            'invoiceStreet1' => $cInvoiceStreet1,
            'invoiceStreet2' => $cInvoiceStreet2,
            'invoiceCity' => $cInvoiceCity,
            'invoiceZipCode' => $cInvoiceZipCode,
            'attributes' => [
            'name' => $cAttrName,
            'value' => $cAttrValue,
            'key' => $cAttrKey,
            'id' => $cAttributeID,
        ],
    ]
);