Migrating from Legacy stripe checkout to the new version in codeigniter - php

I am working on a project which will work as a marketplace website. I already have stripe library as an initial payment method where will receive payment from customers from the website but it seems like the old version of stripe has been upgraded and I want to adopt the new version.
public function stripe_payment_post()
{
require_once(APPPATH . 'third_party/stripe/vendor/autoload.php');
try {
$token = $this->input->post('payment_id', true);
$email = $this->input->post('email', true);
$payment_amount = $this->input->post('payment_amount', true);
$currency = $this->input->post('currency', true);
//Init stripe
$stripe = array(
"secret_key" => $this->payment_settings->stripe_secret_key,
"publishable_key" => $this->payment_settings->stripe_publishable_key,
);
\Stripe\Stripe::setApiKey($stripe['secret_key']);
//customer
$customer = \Stripe\Customer::create(array(
'email' => $email,
'source' => $token
));
//charges
$charge = \Stripe\Charge::create(array(
'customer' => $customer->id,
'amount' => $payment_amount,
'currency' => $currency,
'description' => trans("stripe_checkout")
));
//add to database
$data_transaction = array(
'payment_method' => "Stripe",
'payment_id' => $token,
'currency' => $currency,
'payment_amount' => get_price($payment_amount, 'decimal'),
'payment_status' => $this->input->post('payment_status', true),
);
} catch (\Stripe\Error\Base $e) {
$this->session->set_flashdata('error', $e->getMessage());
$data = array(
'status' => 0,
'redirect' => generate_url("cart", "payment")
);
echo json_encode($data);
} catch (Exception $e) {
$this->session->set_flashdata('error', $e->getMessage());
$data = array(
'status' => 0,
'redirect' => generate_url("cart", "payment")
);
echo json_encode($data);
}
}
// Here is the client side
<script src="https://checkout.stripe.com/v2/checkout.js"></script>
<script>
var handler = StripeCheckout.configure({
key: '<?php echo $this->payment_settings->stripe_publishable_key; ?>',
image: 'https://stripe.com/img/documentation/checkout/marketplace.png',
locale: 'auto',
currency: '<?php echo $currency; ?>',
token: function (token) {
var data = {
'payment_id': token.id,
'email': token.email,
'currency': '<?php echo $currency; ?>',
'payment_amount': '<?php echo $total_amount; ?>',
'payment_status': 'success',
'sys_lang_id': sys_lang_id
};
data[csfr_token_name] = $.cookie(csfr_cookie_name);
$.ajax({
type: "POST",
url: base_url + "stripe-payment-post",
data: data,
success: function (response) {
var obj = JSON.parse(response);
if (obj.result == 1) {
window.location.href = obj.redirect;
} else {
location.reload();
}
}
});
}
});
document.getElementById('btn_stripe_checkout').addEventListener('click', function (e) {
handler.open({
name: '<?php echo html_escape($this->general_settings->application_name); ?>',
description: '<?php echo trans("stripe_checkout"); ?>',
amount: '<?php echo $total_amount; ?>'
});
e.preventDefault();
});
// Close Checkout on page navigation:
window.addEventListener('popstate', function () {
handler.close();
});
</script>

You can find documentation describing this migration here: https://stripe.com/docs/payments/checkout/migration

Related

Build dynamically ChartJs Datasets for JSON Ajax response in PHP

I am having a problem with building JSON in PHP, as a response on Ajax call for populating dynamically datasets for ChartsJs.
In PHP I have an return of Ajax call that works for 1 ChartJs Dataset:
<?php
$returnData['line'] = array(
'type' => 'line',
'title' => $title,
'labels' => array('Jan','Feb','March','April','Mai'),
'datasets' => array(
array(
'data' => array(10,20,15,45,21),
'borderColor' => "#f7464a",
'label' => "Label 1",
'fill' => false
)
)
);
echo json_encode($returnData);
?>
JavaScript that builds the Chart:
$.ajax({
url: "div.php",
type: "POST",
dataType: 'json',
success: function(rtnData) {
$.each(rtnData, function(dataType, data) {
var ctx = document.getElementById("myChart").getContext("2d");
var config = {
type: data.type,
data: {
datasets: data.datasets,
labels: data.labels
},
options: {
responsive: true,
title: {
display: true,
text: data.title
},
legend: {
display: true,
position: 'right',
labels: {
fontColor: '#333'
}
}
}
};
window.myPie = new Chart(ctx, config);
});
},
error: function(rtnData) {
alert('error' + rtnData);
}
});
Now my question, when I have Data for 5 or more Datasets:
//Data
$title = "MyTitle";
$labels= array('Jan','Feb','March','April','Mai');
//Datasets
$linelabels= array('Line1','Line2','Line3','Line4','Line5');
$mydata1 = array(10,20,15,45,21);
$mydata2 = array(21,45,15,20,10);
$mydata3 = array(10,20,15,45,21);
$mydata4 = array(21,45,15,20,10);
$mydata5 = array(10,20,15,45,21);
$colors = array("#f7464a","#8e5ea2","#f7464a","#8e5ea2","#f7464a");
How can I build those Datasets dynamically in the JSON response? For example:
'datasets' => array(
for(i=0:i<5;i++)
{
array(
'data' => array($mydata1[i]),
'borderColor' => $colors[i],
'label' => $linelabels[i],
'fill' => false
),
}
)
SOLVED. To create dynamically Json for Ajax response for Charts, maybe can help someone out:
$returnData2['line'] = array(
'type' => 'line',
'title' => 'my Title',
'labels' => array('Jan','Feb','March','April','Mai'),
'datasets' => array(
array(
'data' => array(10,20,15,45,21),
'borderColor' => "#f7464a",
'label' => "Label 1",
'fill' => false
),
array(
'data' => array(21,45,15,20,10),
'borderColor' => "#8e5ea2",
'label' => 'Line2',
'fill' => false
),
array
(
'data' => array(10,20,15,45,21),
'borderColor' => "#f7464a",
'label' => 'Line3',
'fill' => false
),
array
(
'data' => array(21,45,15,20,10),
'borderColor' => "#8e5ea2",
'label' => 'Line4',
'fill' => false
),
array(
'data' => array(10,20,15,45,21),
'borderColor' => "#f7464a",
'label' => 'Line5',
'fill' => false
)
)
);
echo json_encode($returnData2);
I used this construct, I admit it is not the finest way, but it works. :)
$title = "MyTitle";
$labels= array('Jan','Feb','March','April','Mai');
$linelabels= array('Line1','Line2','Line3','Line4','Line5');
$mydata1 = array(10,20,15,45,21);
$mydata2 = array(21,45,15,20,10);
$mydata3 = array(35,24,20,18,11);
$mydata4 = array(18,5,34,17,42);
$mydata5 = array(23,17,34,12,45);
$colors = array("#E74C3C","#76448A","#148F77","#D4AC0D","#1ABC9C");
$returnData = new stdClass();
$returnData->line = new stdClass();
$returnData->line->type = 'line';
$returnData->line->title = 'my Title';
$returnData->line->labels = $labels;
$returnData->line->datasets = new stdClass();
$dataset = array();
for($i=0;$i<5;$i++)
{
$mydata = array();
if($i==0)
$mydata = $mydata1;
else if($i==1)
$mydata = $mydata2;
else if($i==2)
$mydata = $mydata3;
else if($i==3)
$mydata = $mydata4;
else if($i==4)
$mydata = $mydata5;
$datasets = new stdClass();
$datasets->data = $mydata;
$datasets->borderColor = $colors[$i];
$datasets->label = $linelabels[$i];
$datasets->fill = false;
$dataset[] = $datasets;
}
$returnData->line->datasets = $dataset;
echo json_encode($returnData);
Ajax response for bulding Charts:
$.ajax({
url: "div.php",
type: "POST",
dataType: 'json',
success: function(rtnData) {
$.each(rtnData, function(dataType, data) {
var ctx = document.getElementById("myChart").getContext("2d");
var config = {
type: data.type,
data: {
datasets: data.datasets,
labels: data.labels
},
options: {
responsive: true,
title: {
display: true,
text: data.title
},
legend: {
display: true,
position: 'right',
labels: {
fontColor: '#333'
}
}
}
};
window.myPie = new Chart(ctx, config);
});
},
error: function(rtnData) {
alert('error' + rtnData);
}
});
And the result in Canvas:
enter image description here

laravel POST works in postman but not with axios instance in react-native

I'm trying to create a PaymentIntent object created in the server using stripe-php and laravel 5.8 with the following code:
in routes/api.php:
Route::post('/create-payment-intent', 'Api\v1\PaymentController#createPaymentIntent');
in PaymentController.php:
public function createPaymentIntent(Request $request) {
$validator = Validator::make($request->all(), [
'amount' => 'required',
'currency' => 'required',
'voucherId' => 'required',
]);
$user = Auth::user();
$voucher = AppVoucher::where('id', $request->input('voucherId'))->first();
$voucherOwner = User::where('id', $voucher['business_id'])->first();
try {
$paymentIntent = \Stripe\PaymentIntent::create([
'amount' => $request->input('amount') * 100 ,
'currency' => $request->input('currency'),
'customer' => $user->client_stripe_id,
'description' => $voucher->description,
'on_behalf_of' => $voucherOwner->stripe_account_id,
'payment_method_types' => ['card'],
'receipt_email' => $user->email,
'transfer_data' => ['destination' => $voucherOwner->stripe_account_id],
]);
return response()->json(['paymentIntent' => $paymentIntent], 200);
}
catch (\CardErrorException $e) {
return response()->json([
'information' => 'Error. Something went wrong. Please try again',
'error_on' => 'creating a Payment Intent object in Stripe',
], 400);
}
}
on my client (React-Native app), I created an axios instance and an apiCall helper function to make all requests to my api as such:
axiosInstance & apiCall helper function:
const axiosInstance = axios.create({
baseURL: config.apiUrl.local, // LOCAL ENV
// baseURL: config.apiUrl.staging, // STAGING ENV
cancelToken: source.token,
});
const apiCall = async ({ url, method, data, options, onSuccess, onError }) => {
const token = await getToken();
const headers = {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
};
if (options.withPhoto) {
headers['Content-Type'] = 'multipart/form-data';
}
if (options.withToken) {
headers.Authorization = `Bearer ${token}`;
}
axiosInstance({ url, method, data, headers })
.then((res) => {
if (res.status >= 200 || res.status < 300) {
onSuccess(res.data);
}
})
.catch(err => onError(err));
};
export default apiCall;
in componentDidMount of CheckoutContainer:
componentDidMount() {
const { navigation, onPaymentIntentStart, onPaymentIntentFail } = this.props;
const voucher = navigation.getParam('voucher');
onPaymentIntentStart();
apiCall({
url: 'create-payment-intent',
data: {
amount: Number(voucher.amount),
currency: 'gbp',
voucherId: voucher.id,
},
method: 'post',
options: { withToken: true, withPhoto: false },
onSuccess: res => console.log('onSuccess res: ', res),
// onSuccess: res => this.onPaymentIntentSuccess(res),
onError: err => console.log('onError err: ', err),
// onError: err => onPaymentIntentFail(err.message),
});
}
This set up works for every single apiCall I make in the app except for the concerned method, which works with Postman but not with axios in react-native. I also tried increasing the timeout in the axiosInstance by adding a timeout key, but still gives me error status code 500.
If I remove the code in the server related to $paymentIntent and just return $user, $voucher and $voucherOwner using axios, I get the response.
I have been stuck for days. What could I be missing here?

DataTable Odd Behavior when Deleting Data

I'm adding and deleting row on datatable via ajax.. when I delete data on the datatable and call the additional_info_datatable.ajax.reload() it gives me errors.
here's the error:
Here's my code:
PHP
public function ajax_call_additional_info(){
$result = $this->main_m->get_all_where('additional_info', array('is_deleted' => 0));
$data = array();
if(!empty($result)){
foreach($result as $row){
array_push($data,
array(
'id' => $row['additional_info_id'],
'description' => $row['description'],
'action' => "<button type='button' data-url='".site_url(array('events','soft_delete_additional_info'))."' data-name='".$row['description']."' data-id='".$row['additional_info_id']."' class='btn btn-danger delete_additional_info'><i class='fa fa-fw fa-trash'></i></button>"
));
}
echo json_encode(array('data' => $data));
}else{
echo json_encode(array("draw" => 0, "recordsTotal" => 0, "recordsFiltered" => 0, "data" => array()));
}
}
public function soft_delete_additional_info(){
$id = $this->input->post('id');
$name = $this->input->post('name');
$check_if_exist = $this->main_m->get_where('additional_info', array('additional_info_id' => $id));
if(!empty($check_if_exist)){
$this->main_m->update_data('additional_info', array('is_deleted' => 1), 'additional_info_id', $id);
// $newdata = array(
// 'type' => 'success',
// 'message' => $name."'s successfully deleted!"
// );
// $this->session->set_userdata($newdata);
$message = array('type' => 'alert-success', 'message' => $name."'s successfully deleted!");
echo json_encode($message);
// echo site_url(array("events", "hotel_groupings", $check_if_exist['event_id']));
// echo 1;
}
}
JQUERY
INITIALIZE DATATABLE:
var additional_info = $("#additional_info_table");
var additional_info_datatable = additional_info.DataTable({
"ajax": additional_info.data('url'),
"columns": [
{ "data": "id" },
{ "data": "description" },
{ "data": "action" },
],
"autoWidth": false,
// scrollX: true,
keys: true,
// iDisplayLength: 10,
// "lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
// buttons: []
});
DELETE CODE
$(document).on('click', '.delete_additional_info', function(){
var $this = $(this);
var $url = $this.data('url');
var $id = $this.data('id');
var $name = $this.data('name');
var $csrf_token = $("#csrf_token").val();
bootbox.confirm({
title: "Delete Data",
message: "Do you want to delete <strong>"+$name+"</strong>? This process is irreversible.",
buttons: {
cancel: {
label: '<i class="fa fa-times"></i> Cancel'
},
confirm: {
label: '<i class="fa fa-check"></i> Confirm'
}
},
callback: function (result) {
// console.log('This was logged in the callback: ' + result);
if(result){
$.ajax({
url:$url,
type:'post',
data:{id : $id, name: $name, csrf_test_name : $csrf_token},
dataType:'json',
success:function(data){
// console.log(data);
$(".alert").css("display","block");
$(".alert").addClass(data['type']);
$("#additional_info_message").html(data['message']);
additional_info_datatable.ajax.reload();
}
});
}
}
});

give user media in instagram in laravel 5.4

I'm Trying use Access_token to give user media.
I give Code and Access_token This Way:
My Controller and view has this Code:
public function indexx(Request $request)
{
$code = $this->code = $request->get('code');
try {
$client = new Client();
$res = $client->request('POST', 'https://api.instagram.com/oauth/access_token', [
'form_params' => [
'client_id' => ''client_id',
'client_secret' => 'client_secret' ,
'grant_type' => 'authorization_code',
'redirect_uri'=> 'http://asemi.ir/laravel/public/instagram/s, 'code' => $code
]
]);
$status = $res->getStatusCode();
if ($status == 200) {
$body = $res->getBody();
$obj = \GuzzleHttp\json_decode($body);
//(cookie('access', $access, 45000));
$username = $obj->user->username;
$img = $obj->user->profile_picture;
$full_name = $obj->user->full_name;
$bio = $obj->user->bio;
$website = $obj->user->website;
$access_token=$obj->access_token;
$data = array(
'username' => $username,
'img' => $img,
'full_name' => $full_name,
'bio' => $bio,
'website' => $website,
'access' => $access_token
);
echo view('json')->with($data);
} else {
echo "status is not 200";
}
} catch (BadResponseException $e) {
echo "error1";
}
and view file has this code:
<script>
$(document).ready(function () {
$("button").click(function () {
$.ajax({
method: 'GET',
url: './amir?code={{$code}}',
success: function (data) {
$("#test").html(data);
}
});
});
});
How can I use access_token in controller with json and Guzzle to give user Media ?

Why am I getting error 500 (Internal Server Error) on my ajax?

the problem begins when I try to use my data to the server. once I uncomment this line $data_product = $this->item->addProduct($descripcion,$cost_price,$selling_price,$wprice,$stock); I get the problem 500 Internal Server Error, but I dont know why if I have everything ok, ids,names, etc. I want to send my array to the server. how can I debug this error and fix it? I tried it to see my logs, and there are nothing..
this is the link: http://alasksoft.tk/inventory/product
login credentials: admin - admin
controller
public function addProduct(){
$descripcion = $this->input->post('description');
$cost_price = $this->input->post('cost_price');
$selling_price = $this->input->post('selling_price');
$wprice = $this->input->post('wprice');
$stock = $this->input->post('stock');
$data_product = $this->item->addProduct($descripcion,$cost_price,$selling_price,$wprice,$stock);
$data = array(
'description' => $descripcion,
'cost_price' => $cost_price,
'selling_price' => $selling_price,
'wprice' => $wprice,
'stock' => $stock
);
$this->json($data_product);
}
model
public function addProduct($descripcion,$cost_price,$selling_price,$wprice,$stock){
$data = array(
'descripcion' => $descripcion,
'precio_compra' => $cost_price,
'precio_venta' => $selling_price,
'precio_mayoreo' => $wprice,
'existencia' => $stock
);
$query = $this->db->insert('storelte_articulos',$data);
return $query->result_array();
}
ajax
$('#add').on('click',function(){
$("#description").mask("(999) 999-9999");
$("#new_product").validate();
BootstrapDialog.show({
message: function(dialog) {
var $message = $('<div></div>');
var pageToLoad = dialog.getData('pageToLoad');
$message.load(pageToLoad);
return $message;
},
data: {
'pageToLoad': URL_GET_VIEW_PRODUCT
},
closable: false,
buttons:[{
id: 'btn-ok',
cssClass: 'btn-primary',
icon: 'glyphicon glyphicon-send',
label: ' Save',
action: function (e) {
var description = $('#description').val();
var cost_price = $('#cost_price').val();
var selling_price = $('#selling_price').val();
var wprice = $('#wprice').val();
var stock = $('#stock').val();
if($("#new_product").valid()){
$.ajax({
url: URL_GET_ADD_PRODUCT,
type: 'POST',
data: {description: description, cost_price: cost_price, selling_price: selling_price, wprice: wprice, stock: stock}
}).done(function (e) {
console.log(e);
});
}
}
},{
id: 'btn-cancel',
cssClass: 'btn-danger',
icon: 'glyphicon glyphicon-remove',
label: ' Cancel',
action: function (e) {
e.close();
}
}]
});
});

Categories