0

I have integrated stripe into my website and when I tried adding stripe to a theme template file I keep getting this error: "The Stripe Token was not generated correctly". I can't comprehend why it's showing up after the page loads because this error is only supposed to appear when form is processing via $_POST.

This is the code:

<script src="https://checkout.stripe.com/checkout.js"></script> 
<button id="customButton" class="withpaypal btn white pay_featured_button">
Betal med kreditkort
</button>

<script>     
var handler = StripeCheckout.configure({
    key: '<?php echo $stripe['publishable_key']; ?>',

    image: '<?php if (get_option('wpjobster_stripe_logo_url')) { echo get_option('wpjobster_stripe_logo_url'); } else { echo get_template_directory_uri().'/images/stripe-img.png'; } ?>',
    locale: 'dk',
    token: function(token) {
        $('input[name="stripeToken"]').val(token.id);
        $('form[name="stripeBadge"]').submit();
    }
});



document.getElementById('customButton').addEventListener('click', function(e) {

    // Open Checkout with further options
    handler.open({
        name: '<?php if (get_option('wpjobster_stripe_marketplace_name')) { echo get_option('wpjobster_stripe_marketplace_name'); } else { echo get_bloginfo('name'); } ?>',
        email: '<?php echo $current_user->user_email; ?>',
        billingAddress:false,
        description: '<?php echo "Buy: ".$job_title; ?>',
        amount: '<?php echo intval($amt*100);?>',
        currency:'<?php echo $currency; ?>',
        allowRememberMe: false,
        panelLabel: '<?php  _e('Betal','wpjobster') ?>  {{amount}}' ,
        /*closed:function(){
            var myVar=setInterval(function(){

                if(!tokenisinplace()){
                    clearInterval(myVar);
                    window.history.back()
                    //window.location.replace("<?php bloginfo("url") ?>/?jb_action=purchase_this&jobid=<?php echo $_GET["jobid"] ?>");
                }
            },200);
        }*/
    });

    e.preventDefault();
});
</script>
    <form name="stripeBadge" method="POST" action="">
<input type="hidden" name="recipient_description" value="<?php bloginfo('name'); ?>">
<input type="hidden" name="language" value="EN">
<input type="hidden" name="merchant_fields" value="field1">
<input type="hidden" name="field1" value="<?php echo $pid.'|'.$uid.'|'.$tm.$extrs2; ?>">
<input type="hidden" name="amount" value="<?php echo $amt*100; ?>">
<input type="hidden" name="currency" value="<?php echo $currency; ?>">
<input type="hidden" name="detail1_description" value="Product: ">
<input type="hidden" name="detail1_text" value="<?php echo $job_title; ?>">
<input type="hidden" name="extras" value="<?php echo $partial_ttl; ?>">
<input type="hidden" name="return_url" value="<?php echo $ccnt_url; ?>">
<input type="hidden" name="stripeToken" value="">

//Then the php code for charging the payment

  <?php
 $msg = '';
 $err = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $error = false;
    $cust     = $_POST['field1'];
    $cust     = explode("|", $cust);

    $pid      = $cust[0];
    $uid      = $cust[1];
    $datemade = $cust[2];

    $xtr = '';
    for($i=3;$i<12;$i++){
        if(!empty($cust[$i]))
            $xtr=$xtr.$cust[$i].'|';
    }

  //-----------------------------------------------------
    // calculate total
    //-----------------------------------------------------

    $extr_ttl = 0; $xtra_stuff = '';

    $extras = $xtr;
    $extras = explode("|", $extras);

    if(count($extras)){
        foreach($extras as $myitem){
            if(!empty($myitem)){
                $extra_price    = get_post_meta($pid, 'extra'.$myitem.'_price',         true);
                $extr_ttl += $extra_price;
                $xtra_stuff .= '|'. $myitem;
            }
        }
    }

     $total = $price + $extr_ttl + $shipping;
    $mc_gross = $total;

    $tax_amount = get_user_meta($uid,'wpjobster_taxable_amount', true);
    if (is_numeric($tax_amount) && $tax_amount > 0) {
        // all good.
    } else {
        $tax_amount = 0;
    }

    $amn = wpjobster_formats_special_exchange($mc_gross+$buyer_processing_fees+$tax_amount, 2);

    // https://support.stripe.com/questions/which-zero-decimal-currencies-does-stripe-support

    $zero_decimal_currencies = array(
        "BIF",
        "CLP",
        "DJF",
        "GNF",
        "JPY",
        "KMF",
        "KRW",
        "MGA",
        "PYG",
        "RWF",
        "VND",
        "VUV",
        "XAF",
        "XOF",
        "XPF"
        );

    if (!in_array($currency, $zero_decimal_currencies)) {
        $amn = $amn * 100;
    }

  try {
    if (!isset($_POST['stripeToken'])) throw new Exception("The Stripe Token was not generated correctly");

    Stripe::setApiKey($stripe['secret_key']); //Replace with your Secret Key

    $charge = Stripe_Charge::create(array(
      'source'     => $_POST['stripeToken'],
      'amount'   => $amn,
      'currency' => $currency,
      'description' => 'Bought: '. $job_title
    ));

  } catch (Exception $e) {
    $error = $e->getMessage();
  }

  if ($error=='') {
$success = __('Your payment was successful.', 'wpjobster');

sleep(1);
   /* $cust = $_POST['field1'];

    // insert order
    $orderid = wpjobster_insert_order($cust, $currency, "|");

    if ($orderid) {
        wp_redirect(get_bloginfo('siteurl').'/?jb_action=chat_box&oid='.$orderid);

        exit;
    } else {
        echo __('Error while inserting the order. Please contact the site administrator.', 'wpjobster');
    }
*/
} 
  else {
      ?>
    <p style="margin-top: -0.2em;float: right;">
    <?php echo $error; ?></p>
</button>
<?php 
  }
}
 ?>

I have tried to move the checkout.js above the get_header(); but nothing changes. I'm kinda stuck with this error, any help will be highly appreciated.

  • it looks like your js uses jQuery, but jQuery object reference in WordPress is jQuery, not $, this should produce an error in the js console if that's the case. – Milo Oct 15 '16 at 15:58
  • @ Milo, thanks for your suggestion but I don't think using the $ as a jQuery object reference is causing the error, plus I see not js errors in the console. I have also localized the current jQuery version to the theme. – Viktor Dmitriev Oct 16 '16 at 7:24
  • After 3 hours of agony, I changed the form's post method to " if (isset($_POST['stripeToken'])) " and voila! the error was gone : ) I think the previous post method was interfering with the code since this template acts as a form handler for another template i.e. when a user clicks on a form it takes them to this page. Whew!, that was a tough nut to crack. – Viktor Dmitriev Oct 16 '16 at 7:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.