Getting error "Unexpected end of JSON input" while implement PHP Web SDK

Respected
I am using HTML-PHP web SDK. I am getting error “Unexpected end of JSON input” in html page. But I payment made successful. Please help me

Code

const appId = 'sandbox-xxxxxxxxx';
      const locationId = 'xxxxxxxxx';

      async function initializeCard(payments) {
        const card = await payments.card();
        await card.attach('#card-container');

        return card;
      }

      async function createPayment(token) {
        const body = JSON.stringify({
          locationId,
          sourceId: token,
        });

        const paymentResponse = await fetch('/payment', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body,
        });

        if (paymentResponse.ok) { // working here
          return paymentResponse.json(); // may be getting error in this line
        }

        const errorBody = await paymentResponse.text();
        throw new Error(errorBody);
      }

      async function tokenize(paymentMethod) {
        const tokenResult = await paymentMethod.tokenize();
        if (tokenResult.status === 'OK') {
          return tokenResult.token;
        } else {
          let errorMessage = `Tokenization failed with status: ${tokenResult.status}`;
          if (tokenResult.errors) {
            errorMessage += ` and errors: ${JSON.stringify(
              tokenResult.errors
            )}`;
          }

          throw new Error(errorMessage);
        }
      }

      // status is either SUCCESS or FAILURE;
      function displayPaymentResults(status) {
        const statusContainer = document.getElementById(
          'payment-status-container'
        );
        if (status === 'SUCCESS') {
          statusContainer.classList.remove('is-failure');
          statusContainer.classList.add('is-success');
        } else {
          statusContainer.classList.remove('is-success');
          statusContainer.classList.add('is-failure');
        }

        statusContainer.style.visibility = 'visible';
      }

      document.addEventListener('DOMContentLoaded', async function () {
        if (!window.Square) {
          throw new Error('Square.js failed to load properly');
        }

        let payments;
        try {
          payments = window.Square.payments(appId, locationId);
        } catch {
          const statusContainer = document.getElementById(
            'payment-status-container'
          );
          statusContainer.className = 'missing-credentials';
          statusContainer.style.visibility = 'visible';
          return;
        }

        let card;
        try {
          card = await initializeCard(payments);
        } catch (e) {
          console.error('Initializing Card failed', e);
          return;
        }

        // Checkpoint 2.
        async function handlePaymentMethodSubmission(event, paymentMethod) {
          event.preventDefault();

          try {
            // disable the submit button as we await tokenization and make a payment request.
            cardButton.disabled = true;
            const token = await tokenize(paymentMethod);
            const paymentResults = await createPayment(token);
            displayPaymentResults('SUCCESS');

            console.debug('Payment Success', paymentResults);
          } catch (e) {
            cardButton.disabled = false;
            displayPaymentResults('FAILURE');
            console.error(e.message);
          }
        }

        const cardButton = document.getElementById('card-buttona');
        cardButton.addEventListener('click', async function (event) {
          await handlePaymentMethodSubmission(event, card);
        });
      });

Thanks in advance

:wave: What’s the applicationId you’re using? That error normally happens if the client isn’t able to POST to your server to make the CreatePayment request. :slightly_smiling_face:

Thanks for responding
Currently I am using sandbox application id.
Is createpayment api response should be in json ? I think that’s the problem.

Yes, our response will be a JSON response object. :slightly_smiling_face:

We have to convert bellow create payment response in json right ?

$amount_money = new \Square\Models\Money();
$amount_money->setAmount(1000);
$amount_money->setCurrency('USD');

$app_fee_money = new \Square\Models\Money();
$app_fee_money->setAmount(10);
$app_fee_money->setCurrency('USD');

$body = new \Square\Models\CreatePaymentRequest(
    'ccof:GaJGNaZa8x4OgDJn4GB',
    '7b0f3ec5-086a-4871-8f13-3c81b3875218',
    $amount_money
);
$body->setAppFeeMoney($app_fee_money);
$body->setAutocomplete(true);
$body->setCustomerId('W92WH6P11H4Z77CTET0RNTGFW8');
$body->setLocationId('L88917AVBK2S5');
$body->setReferenceId('123456');
$body->setNote('Brief description');

$api_response = $client->getPaymentsApi()->createPayment($body);

if ($api_response->isSuccess()) {
    $result = $api_response->getResult();
} else {
    $errors = $api_response->getErrors();
}

Yeah, here is the link to our php example to give you some guidance. :slightly_smiling_face:

Hi can you guys guide me how to fetch php file in your example inside the laravel code?

or please show me the code where you are using this to convert the response from php file and process in javascript inside index.blade.php?