MYSQLI UPDATE not working but no errors on log or shown on screen - mysqli

i have a little problem and i have no clue on how to solve it, i´ve tried everything i could and i have no idea where the problem is, the thing is that after the ipn listener insert the transaction data into the ipn_data_tbl, i want to update the record with the same value as $custom, but is not working, is the only thing i need, everything else but this is working as expected, this is my code:
$tokens = explode("\r\n\r\n", trim($res));
$res = trim(end($tokens));
if (strcmp($res, "VERIFIED") == 0 || strcasecmp($res, "VERIFIED") == 0) {
//Payment data
$item_name = $_POST['item_name'];
$txn_id = $_POST['txn_id'];
$payment_gross = $_POST['mc_gross'];
$currency_code = $_POST['mc_currency'];
$payment_status = $_POST['payment_status'];
$create_date = date('Y-m-d H:i:s');
$payment_date = date('Y-m-d H:i:s');
$payer_email = $_POST['payer_email'];
$txn_type = $_POST['txn_type'];
$custom = $_POST['custom'];
//Check if payment data exists with the same TXN ID.
$prevPayment = $con->query("SELECT UID FROM ipn_data_tbl WHERE txn_id = '".$txn_id."'");
if($prevPayment->num_rows > 0){
exit();
}else{
//Insert tansaction data into the database
$insert = $con->query("INSERT INTO ipn_data_tbl(item_name,txn_id,amount,currency,payment_status,create_date,payment_date,payer_email,txn_type,UID) VALUES('".$item_name."','".$txn_id."','".$payment_gross."','".$currency_code."','".$payment_status."','".$create_date."', '".$payment_date."','".$payer_email."','".$txn_type."','".$custom."')");
}
if ($con->query($insert) === TRUE) {
echo $update = $con->query("UPDATE `transportation` SET `paypal_status`='$payment_status' WHERE `id`='$custom'");
}
else {
$delete = $con->query("DELETE FROM transportation WHERE txn_id = '".$txn_id."'");
}
}

I'm sorry, the only thing i had to change was this:
if ($con->query($insert) === TRUE) {
echo $update = $con->query("UPDATE `transportation` SET `paypal_status`='$payment_status' WHERE `id`='$custom'");
}
else {
$delete = $con->query("DELETE FROM transportation WHERE txn_id = '".$txn_id."'");
}
to this
if ($insert) === TRUE) {
echo $update = $con->query("UPDATE `transportation` SET `paypal_status`='$payment_status' WHERE `id`='$custom'");
}
else {
$delete = $con->query("DELETE FROM transportation WHERE txn_id = '".$txn_id."'");
}

Related

Update controller method not rendering json data in Laravel

I have a simple form with some text inputs and uploading photos with that form. Store method working very well but I'm doing something wrong in update method.
This is my store method which works fine:
public function store(Request $request)
{
dd($request);
$post = new Post;
$post->title = $request->title;
$post->user_id = $request->user()->id;
$post->who = $request->who;
$post->when = $request->when;
$post->where = $request->where;
$post->body_text = $request->body;
$post->embed = $request->embed;
$post->status = "4";
$post->tags = $request->tags;
$post->slug = "asdasd";
$post->ip = request()->ip();
if($request->hasfile('photo'))
{
foreach($request->file('photo') as $image)
{
$name= time()."".$this->photo_san($image->getClientOriginalName());
$image->move(public_path().'/uploads/', $name);
$data[] = $name;
}
$post->photo = json_encode($data);
}
$post->save();
$post->slug = $post->id."-".$this->make_slug($request->title);
$post->save();
Session::flash('success', 'Well done.');
return redirect()->route('archive');
}
And this is my update method which saves everything but photos:
public function update(Request $request, $id)
{
if(Auth::user()->role == 3 || Auth::user()->id == Post::find($id)->user_id){
$post = Post::find($id);
$post->title = $request->title;
$post->user_id = $request->user()->id;
$post->who = $request->who;
$post->when = $request->when;
$post->where = $request->where;
$post->body_text = $request->body;
$post->embed = $request->embed;
$post->status = "4";
$post->tags = $request->tags;
$post->slug = $id."-".$this->make_slug($request->title);
$post->ip = request()->ip();
if($request->hasFile('photo'))
{
foreach($request->file('photo') as $image)
{
$name= time()."-edit-".$this->photo_san($image->getClientOriginalName());
$image->move(public_path().'/uploads/', $name);
$data[] = $name;
}
$post->photo = json_encode($data);
}
$post->save();
Session::flash('success', 'Well done.');
return redirect()->route('new');
}
else
Session::flash('error', 'Shame on you :( ');
return redirect()->route('new');
}
When I'm updating any post, everything updating but photos and I don't have any idea what's wrong.
I don't know if it differs but I'm using Laravel 5,8

make a custom error message and prevent duplicate mail id from inserting in db

I have checked email unique in codeigniter. In else past I diplayed error. But the system error is not convenient. how to customise error...
i have tried giveng javascript alert instead of that error message... but after that alert the data are storing in database.. Actually the data should not store in database if the email is not unique..
public function add_applicants() {
// $field_name=$this->input->post('photo');
$data = $this->input->post();
$mobile = $this->db->get_where('applicants',array('mobile_number'=>$this->input->post('mobile_number')));
if($mobile->num_rows()>0)
{
throw new Exception("Mobile Number Already Registered");
}
$email = $this->db->get_where('applicants',array('email_id'=>$this->input->post('email_id')));
if($email->num_rows()>0)
{
throw new Exception("Email_id Already Registered");
}
$school_id= $this->input->post('school_code');
$name_of_exam= $this->input->post('name_of_exam');
$name= $this->input->post('name_candiadte');
switch($name_of_exam){
case '1':
$exam='NMMS';
break;
case '2':
$exam='NTS';
break;
}
$school_code = $this->Welcome_Model->getschoolData($school_id);
if (isset($_FILES['photo']) == 1) {
$config['upload_path'] = FCPATH . 'uploads/'. $school_code->name_of_the_school.'/'. $exam ;
$this->upload_path = $config['upload_path'];
if ($this->validate_upload_path() == TRUE) {
$config['upload_path'] = $this->upload_path;
// print_r($this->upload_path) ;
// die();
}
$config['allowed_types'] = 'jpg';
$config['max_size'] = 2000;
$config['remove_spaces'] = TRUE;
$config['overwrite'] = true;
$config['file_name'] = $name.'-'.date('Ymdhis') . '.jpg';
$file_name = $config['file_name'];
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('photo')) {
$this->upload->display_errors();
}
}
$data['photo'] = $file_name;
$insetapplicants = $this->Welcome_Model->insertApplicants($data);
if ($insetapplicants == 'Success') {
echo "<script>
alert('New Applicants Added Successfully');
// window.location.href='dashboard';
</script>";
}
}

Laravel - paypal keep maximum 30 second exceed

Paypal in laravel keep returning maximum 30 seconds timeout, sometime it can proceed smoothly but when cart product increase, it will keep return this error, and sometime the error is when create payment, sometime is execute payment, extremely not stable, how can i solve this? i have tried extend the timeout setting to 300, but it still return me a timeout error.
here is my create payment code:
$item_array = [];
$shipping = $request->shipping;
$tax = $request->tax;
$tax_amount = 0;
$subtotal = $total = 0;
$currency = "MYR";
$payer = new Payer();
$payer->setPaymentMethod("paypal");
$credential = new OAuthTokenCredential(env('PAYPAL_SANDBOX_CLIENT_ID'), env('PAYPAL_SANDBOX_SECRET'));
$apiContext = new ApiContext($credential, null);
$order = Order::findOrFail($id);
// change order product status
foreach ($order->orderProduct as $order_product_key => $order_product) {
// get variant
$variant_title_array = array();
if (count($order_product->variantValue) > 0) {
foreach ($order_product->variantValue->variantOption as $variant_option) {
array_push($variant_title_array, $variant_option->name);
}
}
$variant= "";
if (count($variant_title_array) > 0) {
$variant = " ( ".implode(', ', $variant_title_array)." )";
}
// calculate product price and promotion price
$product_price = $compare_price = "";
$product_promotion = get_cart_product_promotion ($order_product, $order);
$product_price = get_product_price_in_cart ($order_product);
// if promotion exits
if (count($product_promotion) != 0) {
$compare_price = get_product_price_in_cart ($order_product);
$product_price = calculate_product_price_after_promotion ($compare_price, $product_promotion);
}
$item = new Item();
$item->setName($order_product->product->title . $variant)
->setCurrency($currency)
->setQuantity($order_product->quantity)
->setSku(get_product_sku_in_cart ($order_product)) // Similar to `item_number` in Classic API
->setPrice((float) str_replace('RM ','', $product_price));
$item_array[$order_product_key] = $item;
$subtotal += (float) str_replace('RM ','', $product_price) * $order_product->quantity;
}
// calculate tax
$tax_amount = ($subtotal * $tax) / 100;
$itemList = new ItemList();
$itemList->setItems($item_array);
$shipping_address = new ShippingAddress();
$shipping_address->setCity('City')
->setCountryCode('AR')
->setPostalCode('200')
->setLine1('Adress Line1')
->setState('State')
->setRecipientName('Recipient Name');
$details = new Details();
$details->setShipping($shipping)
->setTax($tax_amount)
->setSubtotal($subtotal);
$total = $subtotal + $shipping + $tax_amount;
$amount = new Amount();
$amount->setCurrency($currency)
->setTotal($total)
->setDetails($details);
$transaction = new Transaction();
$transaction->setAmount($amount)
->setItemList($itemList)
->setDescription("Payment description")
->setInvoiceNumber(uniqid());
$baseUrl = url('/');
$redirectUrls = new RedirectUrls();
$redirectUrls->setReturnUrl("$baseUrl/ExecutePayment.php?success=true")
->setCancelUrl("$baseUrl/ExecutePayment.php?success=false");
$payment = new Payment();
$payment->setIntent("sale")
->setPayer($payer)
->setRedirectUrls($redirectUrls)
->setTransactions(array($transaction));
$request = clone $payment;
try {
$payment->create($apiContext);
} catch (PayPalConnectionException $ex) {
echo $ex->getCode(); // Prints the Error Code
echo $ex->getData(); // Prints the detailed error message
die($ex);
} catch (Exception $ex) {
die($ex);
}
$approvalUrl = $payment->getApprovalLink();
$response = array(
'paymentID' => $payment->id
);
return json_encode($response);
here is my execute payment code:
$shipping = $request->shipping;
$tax = $request->tax;
$tax_amount = 0;
$subtotal = $total = 0;
$currency = "MYR";
$credential = new OAuthTokenCredential(env('PAYPAL_SANDBOX_CLIENT_ID'), env('PAYPAL_SANDBOX_SECRET'));
$apiContext = new ApiContext($credential, null);
$paymentId = $request->paymentID;
$payment = Payment::get($paymentId, $apiContext);
$transaction = new Transaction();
$amount = new Amount();
$details = new Details();
$order = Order::findOrFail($id);
// store order address
$order_address = OrderAddress::firstOrCreate(
[
'order_id' => $order->id
],
[
'name' => $request->shipping_name ,
'phone' => $request->shipping_phone ,
'address1' => $request->shipping_address1 ,
'address2' => $request->shipping_address2 ,
'postcode' => $request->shipping_postcode ,
'state' => $request->shipping_state ,
'country' => $request->shipping_country ,
'city' => $request->shipping_city ,
'order_id' => $order->id
]
);
// update address if exist
$order_address->update([
'name' => $request->shipping_name ,
'phone' => $request->shipping_phone ,
'address1' => $request->shipping_address1 ,
'address2' => $request->shipping_address2 ,
'postcode' => $request->shipping_postcode ,
'state' => $request->shipping_state ,
'country' => $request->shipping_country ,
'order_id' => $order->id
]);
// change order product status
foreach ($order->orderProduct as $order_product) {
// calculate product price and promotion price
$product_price = $compare_price = "";
$product_promotion = get_cart_product_promotion ($order_product, $order);
$product_price = get_product_price_in_cart ($order_product);
// if promotion exits
if (count($product_promotion) != 0) {
$compare_price = get_product_price_in_cart ($order_product);
$product_price = calculate_product_price_after_promotion ($compare_price, $product_promotion);
}
$product_price = (float) str_replace("RM ","",$product_price);
// add promotion to order product if promotion exist
if ($compare_price != "") {
$order_product->order_promotion_id = $order->orderPromotion->promotion_id;
}
$order_product->price = $product_price;
$order_product->status = 2;
$subtotal += $product_price * $order_product->quantity;
$order_product->save();
}
// calculate tax
$tax_amount = ($subtotal * $tax) / 100;
// change cart detail
$current_date_time = Carbon::now();
$order->update([
'subtotal' => $subtotal,
'status' => 2,
'submited_on' => $current_date_time,
'payment_method' => "paypal"
]);
// update shipping fees
if ($shipping > 0) {
$order->shipping_fees = $shipping;
}
// update tax
if ($tax > 0) {
$order->tax = ($subtotal * $tax) / 100;
}
$order->save();
// paypal settings
$total = $subtotal + $shipping + $tax_amount;
$details->setShipping($shipping)
->setTax($tax_amount)
->setSubtotal($subtotal);
$amount->setCurrency($currency);
$amount->setTotal($total);
$amount->setDetails($details);
$transaction->setAmount($amount);
// Add the above transaction object inside our Execution object.
$execution->addTransaction($transaction);
try {
$result = $payment->execute($execution, $apiContext);
try {
$payment = Payment::get($paymentId, $apiContext);
} catch (Exception $ex) {
exit(1);
}
} catch (Exception $ex) {
exit(1);
}
echo "success";

SugarCRM 6.5 How to print php template?

I am newly SugarCRM 6.5 developer, I have write view.detail.php file and controller file. How to print template controller action json data php template. please help me. I have create controller and view.details code below.
Controller
protected function action_printinvoice(){
global $current_user, $db, $region;
$db = DBManagerFactory::getInstance();
$id = $_POST['record'];
$sql = "select gn.client_name, gn.client_address, gn.client_address_city, gn.client_address_state, gn.client_address_country, gn.client_address_postalcode, gn.id, gn.recipient_name, gn.recipient_address_city, gn.recipient_address_state, gn.recipient_address_country, gn.recipient_address_postalcode, gn.recipient_address, gn.recipient_vat_id, gn.recipient_tax_no, gn.recipient_name, gn.invoice_number as ginvo_client_invoice_id, "
. " gcstm.* "
. "from ginvo_client_invoice as gn "
. " inner join ginvo_client_invoice_cstm as gcstm on gn.id=gcstm.id_c "
. "where "
. " gn.deleted=0 and gn.id='".$id."' limit 1 ";
$result = $db->query($sql);
$ginv_invoice_ary=array();
while($row = $db->fetchByAssoc($result) ) {
$ginv_invoice_ary[]=$row;
}
if ($ginv_invoice_ary[0]['region_c'] == 'non_eu_client_and_freelancer_provider') {
$region = 'Non EU client and freelancer provider';
}else if($ginv_invoice_ary[0]['region_c'] == 'non_eu_client_and_employed_provider'){
$region = 'Non EU client and employed provider';
}else if($ginv_invoice_ary[0]['region_c'] == 'german_client_and_freelancer_provider'){
$region = 'German client and freelancer provider';
}else if($ginv_invoice_ary[0]['region_c'] == 'german_client_and_employed_provider'){
$region = 'German client and employed provider';
}else if($ginv_invoice_ary[0]['region_c'] == 'eu_client_and_freelancer_provider'){
$region = 'EU client and freelancer provider';
}else if ($ginv_invoice_ary[0]['region_c'] == 'eu_client_and_employed_provider') {
$region = 'EU client and employed provider';
}else {
$region = '';
}
echo json_encode($ginv_invoice_ary);
$this->view = 'invoiceprint';
//$this->view = 'custom/modules/ginvo_client_invoice/metadata/ClientInvoice.php';
exit;
}
View.detail.php
<?php
require_once('include/MVC/View/views/view.detail.php');
// require_once('modules/ginvo_client_invoice/view/invoice.php');
class ginvo_client_invoiceViewDetail extends ViewDetail {
function ginvo_client_invoiceViewDetail(){
parent::ViewDetail();
}
function display(){
echo $ginv_invoice_ary;
//$this->populateQuoteTemplates();
$this->displayPopupHtml();
parent::display();
}
function populateQuoteTemplates(){
global $app_list_strings, $current_user;
$inv_id = $this->bean->id;
$sql = "SELECT * FROM ginvo_client_invoice WHERE deleted=0 AND id='$inv_id'";
$res = $this->bean->db->query($sql);
$app_list_strings[] = array();
while($row = $this->bean->db->fetchByAssoc($res)){
if($row){
$app_list_strings[$row] = $row;
}
}
}
function displayPopupHtml(){
global $app_list_strings,$app_strings, $mod_strings;
$templates = array_keys($app_list_strings);
if($templates){
echo '
<script>
function showPopup(task){
var record = \''.$this->bean->id.'\';
var fdata = {\'record\':record};
var params = jQuery.param(fdata);
$.ajax({
type:\'post\',
data: fdata,
// dataType: "json",
// url:\'custom/client_invoice.php?\'+params,
//url:\'custom/modules/ginvo_client_invoice/ClientInvoice.php?\'+params,
url:\'index.php?module=ginvo_client_invoice&action=printinvoice\',
error:function(resp){},
success:function(resp){
console.log(resp);
// location.reload(true);
}
});
// var w = window.open(\'custom/ClientInvoice.php\');
//
// $(w).ready(function(){
// w.print();
// });
}
</script>';
}
else{
echo '<script>
function showPopup(task){
alert(\''.$current_user.'\');
}
</script>';
}
}
}
?>

EnvelopeID Changed after correction?

I have 2 signature document and the first signer already signed. The document is still in process. So I went to correct the second signer. I realised the envelopeID changed after the correction.
What will it happen to the old envelope? Voided?
function getDocuments($pdfbytes) {
$documents = array();
$id = 1;
$d = new Document();
$d->PDFBytes = $pdfbytes;
$d->Name = "Demo Document";
$d->ID = $id++;;
$d->FileExtension = "pdf";
array_push($documents, $d);
return $documents;
}
function buildEnvelope($pdfbytes) {
$envelope = new Envelope();
$envelope->Subject = $_SESSION["Taskmaster"];
$envelope->EmailBlurb = "Please Sign by logining ";
$envelope->AccountId = $_SESSION["AccountID"];
$envelope->Recipients = constructRecipients();
$envelope->Tabs = addTabs(count($envelope->Recipients));
$envelope = processOptions($envelope);
$envelope->Documents = getDocuments($pdfbytes);
return $envelope;
}
function constructRecipients() {
$recipients = array();
$r = new Recipient();
$r->UserName =$_SESSION["Secretaryname"];
$r->Email = $_SESSION["Secretaryemail"];
$r->RequireIDLookup = false;
$r->ID = 1;
$r->Type = RecipientTypeCode::Signer;
$r->RoutingOrder = "2";
// if(!isset($_POST['RecipientInviteToggle'][$i])){
$r->CaptiveInfo = new RecipientCaptiveInfo();
$r->CaptiveInfo->ClientUserId = 2;
$r->CaptiveInfo->embeddedRecipientStartURL=SIGN_AT_DOCUSIGN;
// }
array_push($recipients, $r);
if(empty($recipients)){
$_SESSION["errorMessage"] = "You must include at least 1 Recipient";
//header("Location: error.php");
exit;
}
return $recipients;
}
function sendNow($envelope) {
$api = getAPI();
$csParams = new CreateAndSendEnvelope();
$csParams->Envelope = $envelope;
//print_r($csParams);
try {
$status = $api->CreateAndSendEnvelope($csParams)->CreateAndSendEnvelopeResult;
//echo "Result for Create and Send <br>";
//print_r($status);
if ($status->Status == EnvelopeStatusCode::Sent) {
addEnvelopeID($status->EnvelopeID);
$correct = new Correction;
$correct->EnvelopeID = $status->EnvelopeID;
$correct->RecipientCorrections = addRecipientCorrection();
$correctparams = new CorrectAndResendEnvelope();
$correctparams->Correction = $correct;
//print_r($correctparams);
//Send
$response = $api->CorrectAndResendEnvelope($correctparams);
//print_r($response);
//exit;
$_SESSION["EnvelopeID"]=null;
$_SESSION["Direct"]="Yes";
header("Location: getstatusanddocs.php?envelopid=" . $status->EnvelopeID .
"&accountID=" . $envelope->AccountId . "&source=Document");
}
} catch (SoapFault $e) {
$_SESSION["errorMessage"] = $e;
header("Location: error.php");
}
}
function addRecipientCorrection(){
$correction = new RecipientCorrection();
$correction->PreviousUserName = "xxxxxx";
$correction->PreviousEmail = "xxxxxxx";
$correction->PreviousSignerName = $correction->PreviousUserName;
$correction->PreviousRoutingOrder = "2";
$correction->CorrectedUserName = $_SESSION["Secretaryname"];
$correction->CorrectedEmail = $_SESSION["Secretaryemail"];
$correction->CorrectedSignerName = $correction->CorrectedUserName;
return $correction;
}
//========================================================================
// Main
//========================================================================
loginCheck();
if($_SESSION["Taskmaster"]=="xxxxx"){
$api = getAPI();
$RequestPDFParam = new RequestPDF();
$RequestPDFParam->EnvelopeID = $_SESSION["EnvelopeID"];
$result = $api->RequestPDF($RequestPDFParam);
$envPDF = $result->RequestPDFResult;
//file_put_contents("./Cert/".$_SESSION["EnvelopeID"].".pdf", $envPDF->PDFBytes);
//echo "Stop here";
//exit;
$envelope = buildEnvelope($envPDF->PDFBytes);
sendNow($envelope);
}else{
echo "You have no power";
}
EnvelopeId does not change after correction. The envelopeID never changes. New envelopes can be created, but the original GUID that was used will keep living in the system.