Back

[SOLVED] POST Requests are failing

  • 0
  • Functions
SnIpEzzz
13 Oct, 2023, 18:24
TypeScript
    // Prepare and send the WhatsApp message
    $headers = [
        "Content-Type" => "application/json",
        "Accept" => "application/json",
    ];

    $data = [
        "from" => $_ENV["VONAGE_WHATSAPP_NUMBER"],
        "to" => $body["from"],
        "message_type" => "text",
        "text" => 'Hi there! You sent me: ' . $body["text"],
        "channel" => "whatsapp",
    ];

$client = new Client();
    $url = "https://messages-sandbox.nexmo.com/v1/messages";

    try {
        $response = $client->post($url, [
            "headers" => $headers,
            "json" => $data,
            "auth" => [
                $_ENV["VONAGE_API_KEY"],
                $_ENV["VONAGE_API_SECRET"]
            ],
        ]);

        if ($response->getStatusCode() === 200) {
            $result = json_decode($response->getBody(), true);
            return $context->res->json(["ok" => true]);
        } else {
            return $context->error("Error " . $response->getBody());
        }
    } catch (Exception $e) {
        return $context->res->json(["ok" => false], 500);
    }
};
?>
TL;DR
The user was experiencing issues with their POST requests failing. The problem was that there were errors preventing the post request from executing. Implementing try and catch blocks resolved the issue. The user also tried increasing the timeout and removing code incrementally to narrow down the problem, but the issue persisted. The user also made some changes to the code, but the problem still persisted. The solution suggested was to return json after the `$context->error` statement.
Drake
13 Oct, 2023, 18:42

btw, it's helpful to include the language after the 1st 3 backticks to enable syntax highlighting

Drake
13 Oct, 2023, 18:43

any errors or logs on that execution tab?

Drake
13 Oct, 2023, 18:44

you can't return an error like:

TypeScript
return $context->error("Error " . $response->getBody());
SnIpEzzz
13 Oct, 2023, 19:19

yeah, I'm getting

TypeScript
An internal curl error has occurred within the executor! Error Msg: Operation timed out\nError Code: 500
SnIpEzzz
13 Oct, 2023, 19:24

I've updated the code:

TypeScript
<?php

require(__DIR__ . '/../vendor/autoload.php');
require(__DIR__ . '/utils.php');

use \Firebase\JWT\JWT;
use GuzzleHttp\Client;

return function ($context) {

    throw_if_missing($_ENV, [
      'VONAGE_API_KEY',
      'VONAGE_API_SECRET',
      'VONAGE_API_SIGNATURE_SECRET',
      'VONAGE_WHATSAPP_NUMBER',
  ]);

    if ($context->req->method === 'GET') {
        return $context->res->send(get_static_file('index.html'), 200, [
            'Content-Type' => 'text/html; charset=utf-8',
        ]);
    }

    $body = $context->req->body;
    $headers = $context->req->headers;
    $token = (isset($headers["Authorization"])) ? explode(" ", $headers["Authorization"])[1] : "";


    try {
      $decoded = JWT::decode($token, $_ENV['VONAGE_API_SIGNATURE_SECRET'], ['HS256']);
      $context->log($decoded);
    } catch (Exception $e) {
      $context->error("JWT decoding error: " . $e->getMessage());
    }

    if (hash('sha256', $context->req->bodyRaw) !== $decoded['payload_hash']) {
      return $context->res->json([
        'ok' => false,
        'error' => 'Payload hash mismatch'
      ]);
    }

    try {
      throwIfMissing($context->req->body, ['from', 'text']);
    } catch ( Exception $e) {
      return $context->res->json([ "ok"=> false, "error"=> $e->getMessage()], 400);
    }
SnIpEzzz
13 Oct, 2023, 19:24
TypeScript

    $vonageApiKey = $_ENV['VONAGE_API_KEY'];
    $vonageAccountSecret = $_ENV['VONAGE_API_SECRET'];

    $basicAuthToken = base64_encode("$:$vonageAccountSecret");
    $headers = [
      'Content-Type:application/json',
      'Accept:application/json'
    ];

    $data = [
      'from' => $_ENV['VONAGE_WHATSAPP_NUMBER'],
      'to' => $context->req->body['from'],
      'message-type' => 'text',
      'text' => 'Hi there! You sent me: ' . $context->req->body['text'],
      'channel' => 'whatsapp'
    ];
    $client = new Client();
    $url = "https://messages-sandbox.nexmo.com/v1/messages";

    try {
        $response = $client->post($url, [
            "headers" => $headers,
            "json" => $data,
            "auth" => [
                $_ENV["VONAGE_API_KEY"],
                $_ENV["VONAGE_API_SECRET"]
            ],
        ]);

        if ($response->getStatusCode() === 200) {
            $result = json_decode($response->getBody(), true);
            return $context->res->json(["ok" => true]);
        } else {
            return $context->error("Error " . $response->getBody());
        }
    } catch (Exception $e) {
        return $context->res->json(["ok" => false], 500);
    }
}
Drake
13 Oct, 2023, 19:36

I still see return $context->error("Error " . $response->getBody());

SnIpEzzz
13 Oct, 2023, 20:19

I did fix it but still getting the same error. Is it related to syntax?

Drake
13 Oct, 2023, 20:20

maybe. or maybe it's a network problem.

Drake
13 Oct, 2023, 20:21

you should probably return json after $context->error("JWT decoding error: " . $e->getMessage());

SnIpEzzz
13 Oct, 2023, 20:22

i'm a bit confused because if it was a network problem the get request should not be fulfilled right? but only the post request is failing

SnIpEzzz
13 Oct, 2023, 20:22

oh, i'll check

Drake
13 Oct, 2023, 20:25

I mean network problem between the runtime container and nexmo causing a timeout

SnIpEzzz
13 Oct, 2023, 20:27

hm 🤔

SnIpEzzz
13 Oct, 2023, 20:27

there should be a way to resolve this if that's the case

SnIpEzzz
13 Oct, 2023, 20:35

still on the same error

Drake
13 Oct, 2023, 20:36

Maybe increase the timeout? Maybe remove code until it works and then incrementally add so you can narrow down where the problem is?

SnIpEzzz
13 Oct, 2023, 20:41

Increased timeout results in

TypeScript
Operation timed out after 30001 milliseconds with 0 bytes received with status code 0\nError Code: 0
SnIpEzzz
13 Oct, 2023, 20:41

I think i should probably track down the code as you suggested

SnIpEzzz
13 Oct, 2023, 20:41

that'd be better

SnIpEzzz
15 Oct, 2023, 15:19

Update:

Issue Resolved ✅

Drake
18 Oct, 2023, 16:04

what was the problem?

SnIpEzzz
18 Oct, 2023, 18:43

there were a bunch of errors that were preventing the post request from executing, Implementing try and catch blocks instead resolved the issue

Drake
18 Oct, 2023, 18:49

[SOLVED] POST Requests are failing

Reply

Reply to this thread by joining our Discord

Reply on Discord

Need support?

Join our Discord

Get community support by joining our Discord server.

Join Discord

Get premium support

Join Appwrite Pro and get email support from our team.

Learn more