i am trying to integrate stripe payment gateway to my codeigniter project, i did the following in my checkout page:
(function() {
'use strict';
$('[data-toggle="popover"]').popover()
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
} else {
event.preventDefault();
$.blockUI({
css: {
border: 'none',
padding: '15px',
backgroundColor: '#000',
'-webkit-border-radius': '10px',
'-moz-border-radius': '10px',
opacity: .5,
color: '#fff'
}
});
// createToken returns immediately - the supplied callback submits the form if there are no errors
Stripe.card.createToken({
number: $('.cc-number').val(),
cvc: $('.cc-cvc').val(),
exp_month: $('.cc-month').val(),
exp_year: $('.cc-year').val(),
name: $('.cc-name').val(),
}, stripeResponseHandler);
$.unblockUI();
return false; // submit from callback
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
window.appFilePath = '<?php echo base_url(); ?>';
var stripeForm = $('.needs-validation');
// this identifies your website in the createToken call below
Stripe.setPublishableKey(stripeForm.data('stripe-publishable-key'));
function stripeResponseHandler(status, response) {
var stripeError = $('.alert-danger');
var stripeSuccess = $('.alert-success');
if (response.error) {
stripeError.show().delay(3000).fadeOut();
$('#errorMsg').text(response.error.message);
} else {
var token = response['id'];
stripeForm.append("<input type='hidden' name='stripeToken' value='" + token + "' />");
var dataPost = [];
dataPost.push({
name: 'vid',
value: '<?=$this->session->userdata('
id ')?>'
});
dataPost.push({
name: 'plan',
value: '<?=$_POST['
plan ']?>'
});
dataPost.push({
name: 'planamount',
value: '<?=$_POST['
amount ']?>'
});
dataPost.push({
name: 'pid',
value: '<?=$_POST['
pid ']?>'
});
var dataPost = stripeForm.serializeArray();
$.post(appFilePath + "home/stripePost", dataPost, function(response) {
$.unblockUI();
if (response.success) {
stripeForm[0].reset();
stripeSuccess.show().delay(3000).fadeOut();
$('#successMsg').text(response.message);
// Redirect to success page after showing success message
setTimeout(function() {
window.location.href = '<?php echo site_url("home/success"); ?>';
}, 2000);
} else {
stripeError.show().delay(3000).fadeOut();
$('#errorMsg').text(response.message);
}
}, "json").fail(function(xhr, textStatus, errorThrown) {
// Log the error details to the console
console.error("AJAX Request Failed:", textStatus, errorThrown);
});
}
}
// only numbers are allowed
$(".number").keydown(function(e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+v, Command+V
(e.keyCode == 118 && (e.ctrlKey === true || e.metaKey === true)) ||
// Allow: Ctrl+V, Command+V
(e.keyCode == 86 && (e.ctrlKey === true || e.metaKey === true)) ||
// Allow: Ctrl+A, Command+V
((e.keyCode == 65 || e.keyCode == 97 || e.keyCode == 103 || e.keyCode == 99 || e.keyCode == 88 || e.keyCode == 120) && (e.ctrlKey === true || e.metaKey === true)) ||
// Allow: home, end, left, right, down, up
(e.keyCode >= 35 && e.keyCode <= 40)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
my controller function is like:
public function stripePost()
{
//include Stripe PHP library
require_once APPPATH.'third_party/stripe-php/init.php';
StripeStripe::setApiKey($this->config->item('stripe_secret'));
$message = null;
$success = false;
$charge = null;
$err = null;
$data = [];
try {
//Creates timestamp that is needed to make up orderid
$timestamp = strftime('%Y%m%d%H%M%S');
//You can use any alphanumeric combination for the orderid. Although each transaction must have a unique orderid.
$orderid = $timestamp.'-'.mt_rand(1, 999);
//charge a credit or a debit card
$charge = StripeCharge::create([
'amount' => $this->input->post('amount') * 100,
'currency' => 'usd',
'source' => $this->input->post('stripeToken'),
'description' => 'UpkeeProperties Plan PAYMENT',
'metadata' => [
'order_id' => $orderid,
],
]);
} catch (StripeErrorCard $e) {
// Since it's a decline, StripeErrorCard will be caught
$body = $e->getJsonBody();
$err = $body['error'];
/* print('Status is:' . $e->getHttpStatus() . "n");
print('Type is:' . $err['type'] . "n");
print('Code is:' . $err['code'] . "n");
// param is '' in this case
print('Param is:' . $err['param'] . "n");
print('Message is:' . $err['message'] . "n"); */
$message = $err['message'];
} catch (StripeErrorRateLimit $e) {
// Too many requests made to the API too quickly
} catch (StripeErrorInvalidRequest $e) {
// Invalid parameters were supplied to Stripe's API
} catch (StripeErrorAuthentication $e) {
// Authentication with Stripe's API failed
// (maybe you changed API keys recently)
} catch (StripeErrorApiConnection $e) {
// Network communication with Stripe failed
} catch (StripeErrorBase $e) {
// Display a very generic error to the user, and maybe send
// yourself an email
} catch (Exception $e) {
// Something else happened, completely unrelated to Stripe
}
if ($charge) {
//retrieve charge details
$chargeJson = $charge->jsonSerialize();
//check whether the charge is successful
if ($chargeJson['amount_refunded'] == 0 && empty($chargeJson['failure_code']) && $chargeJson['paid'] == 1 && $chargeJson['captured'] == 1) {
// insert response into db
$this->product->response = json_encode($chargeJson);
$this->product->amount = $this->session->flashdata('planamount');
$this->product->plan = $this->session->flashdata('plan');
$this->product->vid = $this->session->flashdata('vid');
$this->product->pid = $this->session->flashdata('pid');
$this->product->dater = date('Y-m-d');
$this->product->status = TRANS_SUCCESS;
$this->product->insert_transaction();
$data = [
'balance_transaction' => $chargeJson['balance_transaction'],
'receipt_url' => $chargeJson['receipt_url'],
'order_id' => $orderid,
];
$success = true;
$message = 'Payment made successfully.';
} else {
// insert response into db
$this->product->response = json_encode($chargeJson);
$this->product->amount = $this->session->flashdata('planamount');
$this->product->plan = $this->session->flashdata('plan');
$this->product->vid = $this->session->flashdata('vid');
$this->product->pid = $this->session->flashdata('pid');
$this->product->dater = date('Y-m-d');
$this->product->status = TRANS_FAIL;
$this->product->insert_transaction();
$success = true;
$message = 'Something went wrong.';
}
}
if ($success) {
echo json_encode(['success' => $success, 'message' => $message, 'data' => $data]);
} else {
// insert response into db
$this->product->response = json_encode($err);
$this->product->status = TRANS_FAIL;
$this->product->insert_transaction();
echo json_encode(['success' => $success, 'message' => $message, 'data' => $data]);
}
}
this was working fine in test keys, it showed errors and when it was success it took to success page, now i made keys to live in config.php, now the issue is its not showing any errors or if the payment is success its not taking to success page or getting saved to database even though payment is cut from bank and its showing in stripe dashoard, i get only this error in console,
POST https://landlord.upkeeproperty.com/home/stripePost 500 (Internal Server Error)
AJAX Request Failed: error Internal Server Error
what could be the issue, thanks in advance