I'm having difficulty using tag script in react js. I'm trying to use an online payments API. The first instruction to use the API is to use :
<script src="https://assets.pagseguro.com.br/checkout-sdk-js/rc/dist/browser/pagseguro.min.js"></script>
According to the API reference, the next step is:
var card = PagSeguro.encryptCard({
publicKey: "MY_PUBLIC_KEY",
holder: "First name Last name",
number: "4242424242424242",
expMonth: "12",
expYear: "2030",
securityCode: "123"
});
var encrypted = card.encryptedCard;
My problem is due to part PagSeguro.encryptCard(). PagSeguro is undefined. How to extract the PagSeguro and encryptCard() that is inside the script?
I'm using the code below:
import React, {useEffect, useState} from 'react'
function Pay(){
const [Infor, setInfor]=useState();
useEffect(() => {
const script = document.createElement('script');
script.src = 'https://assets.pagseguro.com.br/checkout-sdk-js/rc/dist/browser/pagseguro.min.js';
script.async = true;
script.onload = (function(){
setInfor(script);
})
console.log('script',script)
const container = document.getElementById("mydiv");
container.appendChild(script);
let card = script.PagSeguro.encryptCard({
publicKey: "MINHA_CHAVE_PUBLICA",
holder: "Nome Sobrenome",
number: "4242424242424242",
expMonth: "12",
expYear: "2030",
securityCode: "123"
});
console.log('card',card)
}, []);
return (
<div id="mydiv">
<h1>Payment</h1>
</div>
);
}
export default Pay
This is the error message. TypeError: Cannot read properties of undefined (reading 'encryptCard')
It sounds like you're including the external script after your code - as the API reference you quoted says:
After including the JavaScript you must configure the function call...
You need your code to look something like the following:
<script src="https://assets.pagseguro.com.br/checkout-sdk-js/rc/dist/browser/pagseguro.min.js"></script>
<script>
// Now, PagSeguro will have loaded
console.log(typeof PagSeguro);
// and you can proceed to use it
var card = PagSeguro.encryptCard({
publicKey: "MY_PUBLIC_KEY",
holder: "First name Last name",
number: "4242424242424242",
expMonth: "12",
expYear: "2030",
securityCode: "123"
});
var encrypted = card.encryptedCard;
</script>
If you don't want to block rendering while the script downloads, you could attach a load event listener to the script instead, and give it the async or defer attribute.