I am trying to use the WebSDK and Payment API in express.js and react. I keep on getting a 401 error with authentication.
This is what i have on my server.js using express.
const Square = require(“square”);
const squareClient = new Square.SquareClient({
accessToken: process.env.SQUARE_ACCESS_TOKEN,
environment: Square.SquareEnvironment.Sandbox, // Change to Environment.Production when live
});
app.post(“/create-payment”, async (req, res) => {
const {sourceId, amount, currency} = req.body;
try {
const paymentsApi = squareClient.payments;
const response = await paymentsApi.create({
sourceId,
idempotencyKey: crypto.randomUUID(),
amountMoney: {
amount: BigInt(amount),
currency: currency || "USD",
},
})
res.json({
success: true,
payment: response.result.payment
})
} catch (error) {
console.error("Error processing payment", error);
res.status(500).json({
success: false,
error: error.message,
})
}
})
And this is what I have on my react .jsx file
useEffect(() => {
async function initializeSquare() {
if (!window.Square) {
console.error(“Square is not available.”);
return;
}
try {
const paymentsInstance = await window.Square.payments(
applicationID
locaitonID
);
setPayments(paymentsInstance);
} catch (error) {
console.error("Error initializing Square:", error);
}
}
initializeSquare();
}, []);
useEffect(() => {
if (!payments || !cardContainerRef.current) return;
async function attachCard() {
try {
const cardInstance = await payments.card();
await cardInstance.attach(cardContainerRef.current);
setCard(cardInstance);
} catch (error) {
console.error("Error attaching Square card:", error);
}
}
if (!card) attachCard();
}, [payments]);
const [isProcessing, setIsProcessing] = useState(false); // Track payment status
const handleCheckout = async () => {
if (!card) {
console.error("Square payment form not initialized.");
return;
}
try {
const result = await card.tokenize();
console.log("Tokenization result:", result);
if (result.status === "OK") {
const response = await fetch("http://localhost:5001/create-payment", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
sourceId: result.token,
amount: totalAmount * 100, // Convert dollars to cents
currency: "USD"
}),
});
const data = await response.json();
console.log("Payment response:", data);
if (data.payment && data.payment.status === "COMPLETED") {
setOrderComplete(true);
alert("Payment successful!");
} else {
console.error("Payment failed:", data);
alert("Payment failed. Check console for details.");
}
} else {
console.error("Tokenization failed:", result);
alert("Card tokenization failed.");
}
} catch (error) {
console.error("Payment error:", error);
alert("An error occurred during payment.");
}
};
I just don’t know if I have it setup right or if I am missing something. I am just learning this stuff as I am building my first full stack website for my family’s company. I am still going to college so I am a bit lost.