I'm stuck with production payment got bad request error

Just finished successfully the squareup demo payment, but when I tried to change it to production payment got this error: (after hooked up the 401 unauthorized error)
Error: Bad Request
at createError (C:\xampp\htdocs\web-payments\node_modules\micro\lib\index.js:20:14)
at createPayment (C:\xampp\htdocs\web-payments\server.js:24:11)
at processTicksAndRejections (node:internal/process/task_queues:96:5)

maybe something wrong with this section:

async function createPayment(token) {

    const body = JSON.stringify({

      locationId,

      sourceId: token,

      Authorization: 'Bearer my_access_token',

    });

    const paymentResponse = await fetch('/payment', {

      method: 'POST',

      headers: {

        'Content-Type': 'application/json',

      },

      body,

    });

    if (paymentResponse.ok) {

      return paymentResponse.json();

    }

    const errorBody = await paymentResponse.text();

    throw new Error(errorBody);

  }

thanks for help

:wave: When you switched to production did you complete all the deployment tasks:

  1. Get production application credentials. In the Get Sandbox application credentials section, you obtained Sandbox credentials. Follow the steps to open the Developer Dashboard, but this time choose Production mode, and then copy the production application ID and access token.
  2. Update script references. In the ADD SCRIPT REFERENCES section, you added script references in index.html. Update the domain string in the JavaScript reference from sandbox.web.squarecdn.com/v1/square.js to web.squarecdn.com/v1/square.js .
  3. Provide your production application ID. The Web Payments SDK requires a valid application ID to return a payment token. In the Provide your application ID section, you provided a Sandbox application ID. Update the code by providing your production application ID.
  4. Configure your backend server to use a production access token. In the Configure the backend with your access token section, you provided a Sandbox access token. Replace it with the production access token.

Yes, changed and copied the product app id, product access token and product location id
changed the script tag src to “https://web.squarecdn.com/v1/square.js
product app id: sq0idp-8kMSx1TR4xB83iDEp8sBrw
but not sure I’ve put in the right place the production Access Token

If you are using our quickstart example you will need to create a .env.production and configure the access token there.

yes done it, but when it rename to .env.production the error is 404 didn’t find the .env.sandbox now its name is .env.sandbox and the Authorization: ‘Bearer EAAAEbUirRCgjITtd9MQq4nmK_…’ is in the async function createPayment(token) {
const body = JSON.stringify({
locationId,
sourceId: token,
Authorization: ‘Bearer EAAAEbUirRCgjIT…’,
}

If you start the server using npm run instead of npm run dev does it work?

no only with npm run dev, also npm run start:sandbox

Lifecycle scripts included in @square/[email protected]:
start
NODE_ENV=production micro --listen tcp://0.0.0.0:${PORT-3000}
test
npm-run-all --serial lint test:*

available via npm run-script:
start:sandbox
NODE_ENV=sandbox micro --listen tcp://0.0.0.0:${PORT-3000}
inspect
node --inspect node_modules/.bin/micro-dev
dev
micro-dev
lint
npm-run-all --serial lint:*
lint:eslint
eslint --ignore-path .gitignore --cache .
lint:prettier
prettier --ignore-path .gitignore --check .
lint:prettier:fix
prettier --ignore-path .gitignore --write .
test:unit
nyc ava

PS C:\xampp\htdocs\web-payments>

My mistake, if you do npm start it should work. :slightly_smiling_face:

nope
npm start

PS C:\xampp\htdocs\web-payments> npm start

@square/[email protected] start
NODE_ENV=production micro --listen tcp://0.0.0.0:${PORT-3000}

‘NODE_ENV’ is not recognized as an internal or external command,
operable program or batch file.
PS C:\xampp\htdocs\web-payments>

When you get:

and go to localhost:3000 does the page load?

no

This site can’t be reached

localhost refused to connect.

here is the full code:

Square Web Payments Quickstart const appId = 'sq0idp-8kMSx1TR4xB83iDEp8sBrw'; const locationId = 'L074SV8417BRZ';
  async function initializeCard(payments) {
    const card = await payments.card();
    await card.attach('#card-container');
    return card;
  }

  async function createPayment(token) {
    console.log(token);
    const body = JSON.stringify({
      locationId,
      sourceId: token,
      Authorization: 'Bearer EAAAEbUirRCgjITtd9MQ...',
    });

    const paymentResponse = await fetch('/payment', {
      method: 'POST',
      headers: {
        'access-control-allow-credentials': 'true',
        'access-control-allow-headers': 'Origin, Content-Type, X-Allow-Cookies, X-Block-Cookies',
        'access-control-allow-methods': 'OPTIONS, POST',
        'access-control-allow-origin': 'https://web.squarecdn.com',
        'Content-Type': 'application/json',
      },
      body,
    });

    if (paymentResponse.ok) {
      return paymentResponse.json();
    }
    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-button');
    cardButton.addEventListener('click', async function (event) {
      await handlePaymentMethodSubmission(event, card);
    });
  });
</script>
<form id="payment-form">
  <div id="card-container"></div>
  <button id="card-button" type="button">Pay £1.00</button>
</form>
<div id="payment-status-container"></div>   

only works with npm run dev
no-one else

npm help
says:

@square/[email protected] test
npm-run-all --serial lint test:*

@square/[email protected] lint
npm-run-all --serial lint:*

@square/[email protected] lint:eslint
eslint --ignore-path .gitignore --cache .

Browserslist: caniuse-lite is outdated. Please run:
npx browserslist@latest --update-db

Why you should do it regularly:

C:\xampp\htdocs\web-payments\server\square.js
3:23 error ‘SQUARE_ACCESS_TOKEN’ is assigned a value but never used no-unused-vars
7:15 error Insert ⏎··· prettier/prettier

:heavy_multiplication_x: 2 problems (2 errors, 0 warnings)
1 error and 0 warnings potentially fixable with the --fix option.

ERROR: “lint:eslint” exited with 1.
ERROR: “lint” exited with 1.

sorry, my bad:
npm test says the previous post

In your createPayment you shouldn’t be passing your access token. If you create a .env.production with your production access token then run npm start it will process production payments. :slightly_smiling_face:

renamed to .env.production with my production access token, deleted from ceratePayment method but it same.
npm start

@square/[email protected] start
NODE_ENV=production micro --listen tcp://0.0.0.0:${PORT-3000}

‘NODE_ENV’ is not recognized as an internal or external command,
operable program or batch file.
PS C:\xampp\htdocs\web-payments>

now got a different error like:
npm start

node:internal/url:536
throw new ERR_INVALID_URL(input);

Were you able to get past this issue? I’m having the exact same problem.

Hi.
No noone answered me after that. I just leave it.

@Bryan-Square Could you please assist?