Why is wixPay.startPayment() failing with an "invalid arguments" error, even with a hardcoded amount and valid payment options?

Hi guys, im trying to solve this problem for wixpayments.

Product:

Wix Editor (not Wix Studio) and Wix Pay API.

What are you trying to achieve:

I am trying to implement a simple payment flow using wixPay.startPayment(). The user selects a quantity of items (drinks) and I need to start a payment for the correct amount when they click the submit button. I need to use Stripe, Paypal and Alipay as valid payment methods. The currency must be JPY.

import wixPay from 'wix-pay';
import wixLocation from 'wix-location';

$w.onReady(function () {
    $w("#submit").onClick(async () => {
       try {
            console.log("Attempting payment with fixed amount of 1000");
            const payment = await wixPay.startPayment(1000, {
                "currency": "JPY",
                 "paymentMethods": ["creditCard", "paypal", "alipay"]
            });
              console.log("Payment response:", payment);
            if (payment && payment.status) {
                if (payment.status === 'Successful') {
                      console.log("Payment Successful!");
                    wixLocation.to('/orders-collection');
                } else {
                    console.error("Payment Failed:", payment);
                      $w("#errorMessage").text = "支払い処理が失敗しました。";
                    $w("#errorMessage").show();
                }
            }else{
                   console.error("Payment Failed with undefined Status:", payment);
                      $w("#errorMessage").text = "支払い処理が失敗しました。";
                    $w("#errorMessage").show();
            }
        } catch (err) {
            console.error("Error starting payment:", err);
             $w("#errorMessage").text = "支払い処理でエラーが発生しました。";
             $w("#errorMessage").show();
        }
    });
});

What have you already tried:

I have tried numerous different code combinations, focusing on different aspects:

  • I have tried converting the payment amount to an integer using parseInt(amount, 10)

  • I have tried sending the payment amount as a string using String(amount)

  • I have tried various different combinations of payment options, including currency and valid payment methods.

  • I have tried using a minimal code example, where I call wixPay.startPayment() with a hardcoded integer for the amount, and a fixed list of payment options.

  • I have tried the same tests on the live and preview versions of the site.

  • I have tried to simplify the logic as much as possible.

  • I have double checked that Stripe, Paypal, and Alipay are correctly set up in the WIX settings.

Regardless of the code variations, the wixPay.startPayment() function fails with the same “invalid arguments” error . This error persists despite explicitly defining amount as a number (integer), and passing a currency parameter, and a valid payment method.

I have followed the Wix documentation on wixPay.startPayment(), and I believe my parameters are correct.

Here are the different forms of the error that I have received:

  • Error during payment wixPay.startPayment: invalid arguments

  • Wix code SDK error: The value of “amount” parameter that is passed to the startPayment method cannot be set to the value “1000”. It has an inappropriate data type. A number is expected instead of a string.

  • Wix code SDK error: The value of “amount” parameter that is passed to the startPayment method cannot be set to the value 4000. It must be of type string.

  • Wix code SDK error: The value of “amount” parameter that is passed in the startPayment method cannot be set to the value “6000”. Its length must be between 1 and 4. Please ensure that the length of the passed “amount” parameter can be set to the value 4000. its length must be between 1 and 4.

Additional information:

  • The site is configured with JPY as the main currency.

  • The console output consistently shows the same “invalid arguments” error.

  • My payment accounts (Stripe, Paypal, and Alipay) are all correctly connected.

  • I have added console logs to track exactly what is happening.

  • The issue occurs on both the preview and live site.

  • I have a very simple use case for this, that does not involve many dependencies or logic.

I’m at a loss as to why this simple payment process is not working. I suspect there might be a Wix platform issue, or an unexpected conflict. I have thoroughly analyzed the code, and I believe the code logic and values are correct.

I’m including screenshots of my console outputs.

I hope you can help me identify the cause and resolve this issue. Thank you.

Hello! I think there is a bit of a mixup here. startPayment does not take the values yor are providing to it. It takes a paymentId for the first parameter and then payment options for the second. You will need to create the payment in your backend code and call it from the client side.

You will want to take a look at this documentation. I recommend testing with the default code from the snippet here and once that is working, then make the modifications you need for your site

In this example it will give you the backend and frontend code required Start Payment | Velo

Re: wixPay.startPayment API Failing with “Invalid payment id” Error - Issue Persists After Implementation

Dear Wix Support Team / Amandan,

Thank you for answering my question.

I am writing to follow up on my previous support request regarding the wixPay.startPayment API failing with the “Invalid payment id” error.

As per your guidance, I have implemented the suggested changes:

  • I have created a backend module (pay.web.js) to handle payment creation using wixPayBackend.createPayment().

  • I have updated my frontend code to call the backend createMyPayment() function and then use the returned paymentId with wixPayFrontend.startPayment().

  • The code is passing the amount as an integer, and the items array, but not specifying which payment methods should be used.

Despite implementing these changes, the “Invalid payment id” error still persists. I am still receiving the same error message in the console:

Payment failed: {error: ‘Invalid payment id’} as well as a 400 (Bad Request) error on the cashier.wixapps.net url. The Cannot read properties of undefined (reading ‘message’) error also persists.

Key Points:

  • Issue Persists: Please note that this issue is persisting even with the changes to the backend and frontend code. This strongly suggests that the problem is likely not in my code logic.

  • Payment Methods: The issue is occurring when using either PayPal or Credit/Debit card methods. All payment methods are correctly setup and verified.

  • Console Logs: Please see the most recent console output below, as well as the previous console logs (which have all been provided in the previous communication), which shows that the code and parameters are correct.

Frontend Code:

import wixLocation from ‘wix-location’;
import wixPayFrontend from ‘wix-pay-frontend’;
import { createMyPayment } from ‘backend/pay.web’;
import wixData from ‘wix-data’;

$w.onReady(async function () {
const successMessage = $w(“#successMessage”);
const errorMessage = $w(“#errorMessage”);
const paymentButtons = ;
const NUM_OF_BUTTONS = 10;
const PRICE_PER_DRINK = 1000;

successMessage.hide();
errorMessage.hide();

async function initializePayment() {
    let storeId;
    try {
        // Store ID の取得と検証
        storeId = wixLocation.query.storeId;
        if (!storeId || typeof storeId !== 'string' || storeId.trim() === "") {
            console.error("Error: Invalid Store ID in URL parameters:", storeId);
            disablePaymentButtons("Invalid store ID.");
            return;
        }

        console.log("Store ID:", storeId);

        const storeExists = await checkStoreIdExists(storeId);
        if (!storeExists) {
            console.error("Error: Store ID not found in Stores Collection:", storeId);
            disablePaymentButtons("Store not found.");
            return;
        }

        for (let i = 1; i <= NUM_OF_BUTTONS; i++) {
            paymentButtons.push($w(`#paybutton${i}`));
        }

        for (let i = 0; i < paymentButtons.length; i++) {
            paymentButtons[i].onClick(async () => {
              const quantity = i + 1;
                let amount = quantity * PRICE_PER_DRINK;

                if (amount <= 0) {
                   showError("Invalid amount.");
                    console.error("Error: Calculated amount is invalid:", amount);
                   return;
               }

               console.log("Starting payment for amount:", amount);
                errorMessage.hide();

                try {
                    const stockCheck = await checkStock(storeId, quantity);
                    if (!stockCheck) {
                        showError("Not enough stock available.");
                        return;
                    }

                    const items = [{
                        name: "Drink",
                        price: PRICE_PER_DRINK,
                        quantity: quantity,
                    }];
                 
                   console.log("calling createMyPayment with", amount, items)
                  const payment = await createMyPayment(amount, items);
                   console.log("Payment object returned:", payment)

                    if (payment && payment.id) {
                     
                       console.log("payment id: ", payment.id);
                        const paymentResult = await wixPayFrontend.startPayment(payment.id);
                        console.log("Payment Result:", paymentResult);
                        if (paymentResult && paymentResult.status === 'Successful') {
                             console.log("Payment successful:", paymentResult);
                            const orderId = await createNewOrder(storeId, quantity, amount, paymentResult.transactionId);
                            if (orderId) {
                                 const updateResult = await updateStoreInfo(storeId, quantity);
                                 if (updateResult) {
                                   wixLocation.to(`/customerdrinkorders/${orderId}`);
                                    successMessage.show("fade");
                                     setTimeout(() => {
                                         successMessage.hide("fade");
                                    }, 3000);
                               } else {
                                     showError("Failed to update store information.");
                               }
                           } else {
                                showError("Failed to create order.");
                             }
                       } else {
                           showError("Payment unsuccessful.");
                            console.error("Payment failed:", paymentResult);
                        }
                   } else {
                      showError("Payment unsuccessful.");
                       console.error("Payment failed:", payment);
                   }
               } catch (err) {
                  showError("An error occurred during payment.");
                  console.error("Error starting payment:", err);
             }
          });
        }
    } catch (error) {
        console.error("Initialization error:", error);
        disablePaymentButtons("Error during initialization");
   }
}
    initializePayment();

    //---- helper functions ---//
  async function checkStock(storeId, quantity) {
     try {
            const results = await wixData.query("StoresCollection")
                .eq("storeId", storeId)
                .find();

            if (results.items.length === 0) {
               console.error("Store not found with ID:", storeId);
               return false;
           }
           const currentItem = results.items[0];

            if (currentItem.currentStock < quantity) {
              console.log("Not enough stock.");
                return false;
            }
            return true;
        } catch (error) {
           console.error("Error checking stock:", error);
            return false;
      }
    }

   async function updateStoreInfo(storeId, quantity) {
     try {
            const results = await wixData.query("StoresCollection")
                .eq("storeId", storeId)
               .find();

            if (results.items.length === 0) {
                console.error("Store not found with ID:", storeId);
                return false;
            }
            const currentItem = results.items[0];

            const newStock = currentItem.currentStock - quantity;
            const newMonthlyRebate = currentItem.monthlyRebate + (quantity * PRICE_PER_DRINK * 0.4);

            const options = { // 楽観的ロックの実装
              suppressAuth: true
            };

            await wixData.update("StoresCollection", {
              _id: currentItem._id,
                currentStock: newStock,
                monthlyRebate: newMonthlyRebate,
            }, options);

            console.log("Store information updated.");
            return true;
        } catch (error) {
            console.error("Error updating store information:", error);
           return false;
       }
    }

    async function createNewOrder(storeId, quantity, amount, transactionId) {
     try {
            const itemToInsert = {
              storeId: storeId,
                orderDate: new Date(),
                quantity: quantity,
               paymentMethod: 'Pay Button by Wix',
               totalAmount: amount,
                transactionId: transactionId
            };
          const insertResult = await wixData.insert("OrdersCollection", itemToInsert);
           console.log("New order created.");
           return insertResult._id;
      } catch (error) {
         console.error("Error creating new order:", error);
            return null;
     }
    }

    async function checkStoreIdExists(storeId) {
      try {
         console.log("checkStoreIdExists called, with id:", storeId);
            const results = await wixData.query("StoresCollection")
              .eq("storeId", storeId)
               .find();
             console.log("checkStoreIdExists results:", results);
           return results.items.length > 0;
      } catch (error) {
            console.error("Error checking storeId existence:", error);
           return false;
     }
    }

    function disablePaymentButtons(message = "Payment buttons are disabled") {
       for (let i = 1; i <= NUM_OF_BUTTONS; i++) {
           $w(`#paybutton${i}`).disable();
        }
        if (message) showError(message);
    }

   function showError(msg) {
      errorMessage.text = msg;
      errorMessage.show("fade");
       setTimeout(() => {
            errorMessage.hide("fade");
        }, 5000);
   }

});

Backend code:

import { Permissions, webMethod } from “wix-web-module”;
import wixPayBackend from “wix-pay-backend”;

export const createMyPayment = webMethod(Permissions.Anyone, async (amount, items) => {
try {
const payment = await wixPayBackend.createPayment({
items: items,
amount: amount,
});
return payment
} catch (error) {
console.error(“Error creating payment:”, error);
throw error;
}
});

Additional Information:

  • I have extensively tested the code in different browsers and using different payment methods. All of which fail with the same error.

  • I have made sure that the settings on my Wix platform are correct and also that all the payment methods have been setup correctly.

Request:

  • I urgently request your assistance in investigating what could be causing this issue, as it seems to be related to the wixPay API.

  • Please check your internal logs to see the request and what is happening internally in your system.

  • Please check if there are any specific requirements of the API which I am not complying with.

  • Please also check if there is an issue with the way the Wix API is being setup in my account.

  • I am at a loss as to why I am still receiving this error, which is preventing payments on my site.

I really appreciate your prompt attention to this critical issue.

Sincerely,

Hello - one clarification is that the customer care team is not present in this forum and cannot open a ticket from here.

I am not seeing anything in your updated code that looks incorrect so if you have exhausted all other checks on your store setup, I would reccomend opening a ticket with customer care to triage this issue in your account specifically Contact Wix