Using API response to submit PUT request

Hello, I have a question and was wondering if anyone could hint me in the right direction.

I have a form which is submitting a POST request to a CRM api with the following JSON data to create a client:

  "fname": "Ben",
  "email": "",
  "input_channel_id": 8,
  "source_id": 2,
  "interest_type_id": 4

If successful there will be a 200 response. With the clients data (as JSON).

The API will check if the client exists by using the ‘email’ (to not duplicate), but will not update the ‘phone’ if it is different to what is on file.

I was wondering if I can use the received 200 response to check whether ‘phone’ is different, and if so submit a PUT request with the new data?

Where would I start with something like this? :slight_smile:

If the entry with the email address already exists, you will probably not get a 200 response? Without knowing the API and what it returns in which error case, it’s impossible to give you useful advice, as every API is different.

Or am I misunderstanding what you are trying to achieve?

Thanks for your response.

I have tested it and if the email address does already exist, or if it does not yet exist, it will return a 200 response. For example if this contact had been added previously, but with a different telephone number the response would be:

  "data": {
    "type": "clients",
    "id": "1365",
    "attributes": {
      "id": 1365,
      "fname": "Ben",
      "phone": "+519999999",
      "email": "",
      "created_at": 1517374800,
      "interest_type_id": 4,
      "input_channel_id": 4

If the email address had not existed yet, the response would be exactly the same, however the phone number would be the one shown in the original question.

I have finalised the initial API Post request and it is working. It is not the leanest piece of code, but it is getting the job done:

return function($kirby, $site, $pages, $page) {

    $alert = null;

    if($kirby->request()->is('POST') && get('submit')) {

        // check the honeypot
        if(empty(get('website')) === false) {

        $data = [
            'fname'             => get('fname'),
            'lname'             => get('lname'),
            'email'             => get('email'),
            'phone'             => get('phone'),
            'text'              => get('text'),
            'checkbox'          => get('checkbox'),
            'project'           => get('project'),
            'input_channel_id'  => 8,
            'source_id'         => 2,
            'interest_type_id'  => 4

        $rules = [
            'fname'     => ['required', 'minLength' => 3],
            'lname'     => ['required', 'minLength' => 3],
            'email'     => ['required', 'email'],
            'phone'     => ['required'],
            'checkbox'  => ['required']

        $messages = [
            'fname'     => 'Este campo es requerido.',
            'lname'     => 'Este campo es requerido.',
            'email'     => 'Introduzca una dirección de correo electrónico válida.',
            'phone'     => 'Introduzca un número de telefono válido.',
            'checkbox'  => 'Este campo es requerido.'

        // some of the data is invalid
        if($invalid = invalid($data, $rules, $messages)) {
            $alert = $invalid;

            // the data is fine, let's send the email
        } else {
            try {
                    'template' => 'email',
                    'from'     => '',
                    'replyTo'  => $data['email'],
                    'to'       => '',
                    'subject'  => 'Mensaje recibido del formulario del sitio web',
                    'data'     => [
                        'fname'     => esc($data['fname']),
                        'lname'     => esc($data['lname']),
                        'email'     => esc($data['email']),
                        'phone'     => esc($data['phone']),
                        'project'   => esc($data['project']),
                        'text'      => esc($data['text'])

            } catch (Exception $error) {
                    $alert['error'] = 'No se pudo enviar el formulario: <strong>' . $error->getMessage() . '</strong>';
                    $alert['error'] = 'No se pudo enviar el formulario. Inténtalo de nuevo.';

            // no exception occured, let's send a success message
            if (empty($alert) === true) {
                $success = 'Gracias por su mensaje, nos pondremos en contacto con usted lo antes posible.';
                $data = [];

                $object= array(
                    'fname'             => get('fname'),
                    'lname'             => get('lname'),
                    'email'             => get('email'),
                    'phone'             => get('phone'),
                    'project_id'        => get('project'),
                    'input_channel_id'  => 8,
                    'source_id'         => 2,
                    'interest_type_id'  => 4,
                    'observation'       => get('text')
                $object = (object) array_filter((array) $object);
                $result = json_encode($object);

                $curl = curl_init();
                curl_setopt_array($curl, array(
                  CURLOPT_URL => '',
                  CURLOPT_RETURNTRANSFER => true,
                  CURLOPT_ENCODING => '',
                  CURLOPT_MAXREDIRS => 10,
                  CURLOPT_TIMEOUT => 0,
                  CURLOPT_FOLLOWLOCATION => true,
                  CURLOPT_CUSTOMREQUEST => 'POST',
                  CURLOPT_POSTFIELDS => $result,
                  CURLOPT_HTTPHEADER => array(
                    'Authorization: XXXXXXXX',
                    'Content-Type: application/json'

                // $response = curl_exec($curl);
                // echo $response;

    return [
        'alert'   => $alert,
        'data'    => $data ?? false,
        'success' => $success ?? false

I am beginning to start thinking about how to read the received 200 response to check whether ‘phone’ is different, and if so submit a PUT request with the new ‘phone’ data.

Would something like this below be the right direction?

if (!empty($response->content)) {
$newData = json_decode($response->content, true);
} ?>
<?php if($newData['phone'] == $data['phone']): ?>
<?php endif ?>

You only want to update when the values are different? But apart from that yes.

Thanks for spotting that, I have updated it now and got it working.

I would like to prepend an area code to a phone number received in the form before submitting the POST request.

I thought something like this would work… but no:

$object= array(
   'phone' => '+51' . get('phone')

Don’t know your context there, is the form data still available?

Yes, form data is still available. get('phone') pulls number correctly, but the '+51' is not being added.

So when you dump($object) there is no +51 prepended? That would be weird.

Thank you, yes it was working. There was an issue further down the code.

I would like to create a rule that only allows numbers in the form input eg below, but not sure how to do it?

$rules = [
  'phone' => ['required']
$rules = [
  'phone' => ['required', 'num']

Amazing, thank you