Quantcast
Channel: Square Developer Forums - Latest topics
Viewing all articles
Browse latest Browse all 1325

Issue with nonce/source_id while trying to store card to a customer

$
0
0

Hi everyone,

I just started digging around the Square API the other day and I am trying to get a very basic setup and understanding of how I can implement what I need into my existing website. I will try to go into as much detail as possible, but any help would be greatly appreciated.

I was able to create customers without any issues, but where I am really struggling is having a form where that customer can enter in their credit card numbers and then have it stored under their Square customer information. The issue that I am having definitely has to do with the nonce/source_id because when I use the sandbox “cnon:card-nonce-ok” the information gets loaded to the customers Square without any issues.

For testing I have been trying to keep all of the code in one page so I will include all of that below.

<script type="text/javascript" src="https://web.squarecdn.com/v1/square.js"></script>
<script type="text/javascript">    
document.addEventListener('DOMContentLoaded', async function() {
    const payments = Square.payments('xxxx', 'xxxx');
    const card = await payments.card();
    await card.attach('#card-container');

    document.getElementById('payment-form').addEventListener('submit', async function(event) {
        event.preventDefault();
        const tokenResult = await card.tokenize();
        if (tokenResult.status === 'OK') {
            console.log('Tokenization succeeded, nonce:', tokenResult.token);
            document.getElementById('nonce').value = tokenResult.token;
            this.submit(); // Submit the form with the nonce as part of the request
        } else {
            console.error('Tokenization failed with errors:', tokenResult.errors);
            alert('Failed to tokenize card. Please try again.');
        }
    });
});
</script>

                    
<form id="payment-form" method="post">
    <div id="card-container"></div>
    <input type="text" id="nonce" name="nonce">
    <button id="submitCard" type="submit">Submit Card</button>
</form>
                    
                    
                    
<?php
                    
use Square\SquareClient;
use Square\Environment;
use Square\Models\CreateCustomerCardRequest;
                                       
                    
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['nonce'])) {
    
    $client = new SquareClient([
        'accessToken' => 'xxxx',
        'environment' => Environment::SANDBOX
    ]);
                    
    $cardNonce = $_POST['nonce'];
    $idempotencyKey = bin2hex(random_bytes(22)); 
    echo $cardNonce;
    echo '<br /><br />';
       
    
    $card = new \Square\Models\Card();
    $card->setCardholderName('John Doe');
    $card->setCustomerId('Q59NEW831WS7HJVC1KMRWJP9V0');
                    
  
    $body = new \Square\Models\CreateCardRequest(
    $idempotencyKey,
    $cardNonce,
    $card
);
    
    $api_response = $client->getCardsApi()->createCard($body);

    if ($api_response->isSuccess()) {
        $result = $api_response->getResult();
        var_dump($result);
    } else {
        $errors = $api_response->getErrors();
        print_r($errors);
    }


}
                    
                    
?> 

If I submit the form as it is right now with that code then I receive the error below, but like I mentioned before if I replace $cardNonce with “cnon:card-nonce-ok” then everything works as intended.

Array ( [0] => Square\Models\Error Object ( [category:Square\Models\Error:private] => INVALID_REQUEST_ERROR [code:Square\Models\Error:private] => INVALID_CARD_DATA [detail:Square\Models\Error:private] => Invalid card data. [field:Square\Models\Error:private] => source_id ) )

I assume that I am doing something wrong when generating/making a token for the nonce, but I have spent days on this now and I am completely stumped at the moment. Hoping someone here is able to help point me in the right direction.

4 posts - 3 participants

Read full topic


Viewing all articles
Browse latest Browse all 1325

Trending Articles