The AuthsignalProvider component allows you to use the useAuthsignal hook. Render the AuthsignalProvider component
at the root of your application so that it is available everywhere you need it.
The startChallenge function triggers the authentication flow.
import{ useAuthsignal }from"@authsignal/react";exportfunctionCheckout(){const{ startChallenge }=useAuthsignal();consthandlePayment=async()=>{const response =awaitfetch("/api/payment",{ method:"POST", headers:{"Content-Type":"application/json",},});const data =await response.json();if(data.token){startChallenge({ token: data.token,onChallengeSuccess:({ token })=>{// Challenge was successful// Send the token to your server to validate the challenge},onCancel:()=>{// User cancelled the challenge},onTokenExpired:()=>{// Token expired},});}};return(<div><buttontype="button"onClick={handlePayment}>Pay</button></div>);}
As well as a token, the startChallenge function accepts the following callbacks:
onChallengeSuccess
function
A callback function that is called when the challenge is successful. It receives an object with a
token property. This token should be sent to your server to validate the
challenge.
onCancel
function
A callback function that is called when the user cancels the challenge.
onTokenExpired
function
A callback function that is called when the token expires.
Alternatively, you can use the startChallengeAsync function, which returns a Promise that resolves with a token when the challenge is successful.
It will throw a ChallengeError if the user cancels the challenge or the token expires.
import{ useAuthsignal,ChallengeError}from"@authsignal/react";exportfunctionCheckout(){const{ startChallengeAsync }=useAuthsignal();consthandlePayment=async()=>{const response =awaitfetch("/api/payment",{ method:"POST", headers:{"Content-Type":"application/json",},});const data =await response.json();if(data.token){try{const{ token }=awaitstartChallengeAsync({ token: data.token,});// Challenge was successful// Send the token to your server to validate the challenge}catch(e){if(e instanceofChallengeError){if(e.code==="USER_CANCELED"){// User cancelled the challenge}elseif(e.code==="TOKEN_EXPIRED"){// Token expired}}}}};return(<div><buttontype="button"onClick={handlePayment}>Pay</button></div>);}