Sagepay refund error - 3047 : Invalid VPSTxId format - opayo

I have an error while writing the code to refund a transaction from Sagepay:
3047 : Invalid VPSTxId format.
The code I used here is:
if ($this->config->get('sagepay_direct_v3_test') == 'live') {
$url = 'https://live.sagepay.com/gateway/service/refund.vsp';
$payment_data['VPSProtocol'] = '3.00';
} elseif ($this->config->get('sagepay_direct_v3_test') == 'test') {
$url = 'https://test.sagepay.com/gateway/service/refund.vsp';
$payment_data['VPSProtocol'] = '3.00';
}
$this->load->model('checkout/order');
$this->load->model('payment/sagepay_direct_v3');
$order_info = $this->model_checkout_order->getOrder($order_id);
$sagepay_direct_v3_order = $this->getOrder($order_info['advance_order_confirmed_id']);
$params = array();
$params['VPSProtocol'] = urlencode($payment_data['VPSProtocol']);
$params['TxType'] = urlencode('REFUND');
$params['Vendor'] = urlencode($this->config->get('sagepay_direct_v3_vendor'));
$params['VendorTxCode'] = $this->request->get['order_id'] . 'T' . strftime("%Y%m%d%H%M%S") . mt_rand(1, 999);
$params['Amount'] = $this->currency->format($order_info['total'], $order_info['currency_code'], false, false);
$params['Currency'] = $this->currency->getCode();
$params['Description'] = urlencode(substr($this->config->get('config_name'), 0, 100));
$params['RelatedVPSTxId'] = urlencode($sagepay_direct_v3_order['VPSTxId']);
$params['RelatedVendorTxCode'] = urlencode($this->request->get['order_id'] . 'T' . strftime("%Y%m%d%H%M%S") . mt_rand(1, 999));
$params['RelatedSecurityKey'] = urlencode($sagepay_direct_v3_order['SecurityKey']);
$params['RelatedTxAuthNo'] = urlencode($sagepay_direct_v3_order['TxAuthNo']);
$response = $this->model_payment_sagepay_direct_v3->sendCurl($url, $params);
var_dump( $response );

I suspect this is because you are urlencoding the RelatedVPSTxId (and other fields).

Related

Laravel 6 - How to upload multi file through laravel?

I wrote these code for upload files through laravel 6.
But I only success for upload one file,even I am sure I got all files while uploading by check from dd($request->files)
in the begining the $index = 0 and in the end it change to 1,first round is ok but the it didn't continue to second run.
I don't know why,please help! thank you~
if($request->hasFile('files')){
$index = 0;
foreach($request->files as $key=>$file){
$originalName = $file[$index]->getClientOriginalName();
$size = $file[$index]->getClientSize();
$ext = $file[$index]->getClientOriginalExtension();
$newName = date('Ymd').mt_rand(100,999).$originalName;
$savePath = '/attachments/'.$newName;
$movePath = base_path().'/public/attachments/'.$newName;
$file[$index]->move(base_path().'/public/attachments',$newName);
$attachment = new attachment();
$attachment->bulletin_id = $bulletin->id; //already got this value before
$attachment->original_name = $originalName;
$attachment->name = $newName;
$attachment->type = $file[$index]->getClientMimeType();
$attachment->path = $savePath;
$attachment->size = ($size/1000);
$attachment->save();
++$index;
}
}
You try this way and it is simple
foreach($request->file('files') as $key=>$file){
$originalName = $file->getClientOriginalName();
$size = $file->getClientSize();
$ext = $file->getClientOriginalExtension();
$newName = date('Ymd').mt_rand(100,999).$originalName;
$savePath = '/attachments/'.$newName;
$movePath = base_path().'/public/attachments/'.$newName;
$file->move(base_path().'/public/attachments',$newName);
$attachment = new attachment();
$attachment->bulletin_id = $bulletin->id; //already got this value before
$attachment->original_name = $originalName;
$attachment->name = $newName;
$attachment->type = $file->getClientMimeType();
$attachment->path = $savePath;
$attachment->size = ($size/1000);
$attachment->save();
}

Custom chunk implementation

Is it possible to customize the chunk configuration in Filepond such that the chunk information is provided to the upload server:
as query parameters instead of headers
with custom query parameter names instead of Upload-Length, Upload-Name, and Upload-Offset
I am trying to fit Filepond's chunk implementation to a third party upload endpoint that I don't have control over.
I have found the Advanced configuration where you provide a process function which I've played with a little bit to see what comes through the options param -- however that appears (I think) to make the chunking calculations my responsibility. My original thought was to manipulate the options.chunkServer.url to include the query params I need but I don't believe this processes individual chunks.
In case it makes a difference, this is being done in React using the react-filepond package.
I made and implementation in Laravel 6 using Traits and some "bad practices" (I didn't have time because ... release in prod) to join chunks into a file
Basically:
post to get unique id folder to storage
get chunks and join together
profit!
Here's the full code:
<?php
namespace App\Http\Traits\Upload;
use Closure;
use Faker\Factory as Faker;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
trait Uploadeable
{
public function uploadFileInStorage(Request $request, Closure $closure)
{
// get the nex offset for next chunk send
if (($request->isMethod('options') || $request->isMethod('head')) && $request->has('patch')) {
//get the temp dir
$dir = $request->patch . DIRECTORY_SEPARATOR;
// reead all chunks in directory
$patch = collect(Storage::files($dir))
->sortBy(function ($file) {
return Storage::lastModified($file);
});
// read offsets for calculate
$offsets = array();
$size = 0;
$last_offset = 0;
foreach ($patch as $filename) {
$size = Storage::size($filename);
list($dir, $offset) = explode('file.patch.', $filename, 2);
array_push($offsets, $offset);
if ($offset > 0 && !in_array($offset - $size, $offsets)) {
$last_offset = $offset - $size;
break;
}
// last offset is at least next offset
$last_offset = $offset + $size;
}
// return offset
return response($last_offset, 200)
->header('Upload-Offset', $last_offset);
}
// chunks
if ($request->isMethod('patch') && $request->has('patch')) {
// get the temp dir
$dir = $request->patch . DIRECTORY_SEPARATOR;
// read headers
$offset = $request->header('upload-offset');
$length = $request->header('upload-length');
// should be numeric values, else exit
if (!is_numeric($offset) || !is_numeric($length)) {
return response('', 400);
}
// get the file name
$name = $request->header('Upload-Name');
// sleep server for get a diference between file created to sort
usleep(500000);
// storage the chunk with name + offset
Storage::put($dir . 'file.patch.' . $offset, $request->getContent());
// calculate total size of patches
$size = 0;
$patch = Storage::files($dir);
foreach ($patch as $filename) {
$size += Storage::size($filename);
}
// make the final file
if ($size == $length) {
// read all chunks in directory
$files = collect(Storage::files($dir))
->sortBy(function ($file) {
return Storage::lastModified($file);
});
// create output file
//Log::info(storage_path('app'));
$new_file_name = $final_name = trim(storage_path('app') . DIRECTORY_SEPARATOR . $dir . $name);
$file_handle = fopen($new_file_name, 'w');
// write patches to file
foreach ($files as $filename) {
// get offset from filename
list($dir, $offset) = explode('.patch.', $filename, 2);
// read chunk
$patch_handle = fopen(storage_path('app') . DIRECTORY_SEPARATOR . trim($filename), 'r');
$patch_contents = fread($patch_handle, filesize(storage_path('app') . DIRECTORY_SEPARATOR . trim($filename)));
fclose($patch_handle);
// apply patch
fseek($file_handle, $offset);
fwrite($file_handle, $patch_contents);
}
// done with file
fclose($file_handle);
// file permission (prefered 0755)
chmod($final_name, 0777);
// remove patches
foreach ($patch as $filename) {
$new_file_name = storage_path('app') . DIRECTORY_SEPARATOR . trim($filename);
unlink($new_file_name);
}
// simple class (no time to explain)
$file = new UploadedFile(
$final_name,
basename($final_name),
mime_content_type($final_name),
filesize($final_name),
false
);
$dir = $request->patch . DIRECTORY_SEPARATOR;
$object = new \stdClass();
$object->full_path = (string)$file->getPathname();
$object->directory = (string)($dir);
$object->path = (string)($dir . basename($final_name));
$object->name = (string)$file->getClientOriginalName();
$object->mime_type = (string)$file->getClientMimeType();
$object->extension = (string)$file->getExtension();
$object->size = (string)$this->formatSizeUnits($file->getSize());
// exec closure
$closure($file, (object)$object, $request);
}
// response
return response()->json([
'message' => 'Archivo subido correctamente.',
'filename' => $name
], 200);
}
// get dir unique id folder temp
if ($request->isMethod('post')) {
$faker = Faker::create();
$unique_id = $faker->uuid . '-' . time();
$unique_folder_path = $unique_id;
// create directory
Storage::makeDirectory($unique_folder_path);
// permisos directorio
chmod(storage_path('app') . DIRECTORY_SEPARATOR . $unique_folder_path . DIRECTORY_SEPARATOR, 0777);
// response with folder
return response($unique_id, 200)
->header('Content-Type', 'text/plain');
}
}
private function formatSizeUnits($bytes)
{
if ($bytes >= 1073741824) {
$bytes = number_format($bytes / 1073741824, 2) . ' GB';
} elseif ($bytes >= 1048576) {
$bytes = number_format($bytes / 1048576, 2) . ' MB';
} elseif ($bytes >= 1024) {
$bytes = number_format($bytes / 1024, 2) . ' KB';
} elseif ($bytes > 1) {
$bytes = $bytes . ' bytes';
} elseif ($bytes == 1) {
$bytes = $bytes . ' byte';
} else {
$bytes = '0 bytes';
}
return $bytes;
}
}
ยดยดยด

How to get the values of an array retrieved from database in codeigniter?

I have a code with me to get the values from the database in an array as shown below :
$uri = $this->uri->uri_to_assoc(4);
$student_id='S17AB21017';
$data['profile_data']=$this->studentsmodel->get_Cinprofile($student_id);
$pay = $this->instamojo->pay_request(
$amount = "6930" ,
$purpose = "Primary Colors Internationals" ,
$buyer_name = "Apple" ,
$email = "webteam6#marrs.in" ,
$phone = "7034805760" ,
$send_email = 'TRUE' ,
$send_sms = 'TRUE' ,
$repeated = 'FALSE'
);
I want to get the values in $data values for $buyer_name,$email and $phone and give it in the pay_request(). The values for name,email and phone is obtained from the table students_to_cin.How can I get the values ?
The code for get_Cinprofile() is shown below :
public function get_Cinprofile($student_id)
{
//echo $student_id;die;
$this->db->select('students_to_cin.*,schools.school_name,schools.school_address,schools.school_address1,schools.school_email,schools.school_phone,schools.school_principal_name,schools.school_medium,states.state_subdivision_name,class.class_key,category.categoryKey,period.period_name,countries.country_name,studentlist.stud_cin,studentlist.stud_syllabus,studentlist.stud_school_state,studentlist.stud_school_country,schools.school_pincode');
$this->db->from('students_to_cin');
$this->db->join('schools','schools.school_id=students_to_cin.school_id');
$this->db->join('states','states.state_subdivision_id=students_to_cin.state_id');
$this->db->join('class','students_to_cin.class_id = class.class_id'); /*class.class_key,*/
$this->db->join('category','students_to_cin.category_id = category.category_id');
$this->db->join('period','students_to_cin.period_id = period.period_id');
$this->db->join('countries','students_to_cin.country_id = countries.country_id');
$this->db->join('studentlist','students_to_cin.cin = studentlist.stud_cin');
$this->db->where('students_to_cin.student_id',$student_id);
$query = $this->db->get();//echo $this->db->last_query();exit;
$result = $query->row_array();
return $result;
}
Can anyone help me on this ?
You can use it like.....
$uri = $this->uri->uri_to_assoc(4);
$student_id='S17AB21017';
$data['profile_data']=$this->studentsmodel->get_Cinprofile($student_id);
$pay = $this->instamojo->pay_request(
$amount = $data['profile_data']['yourfieldname'] ,
$purpose = $data['profile_data']['yourfieldname'] ,
$buyer_name = $data['profile_data']['yourfieldname'] ,
$email = $data['profile_data']['yourfieldname'] ,
$phone = $data['profile_data']['yourfieldname'] ,
$send_email = $data['profile_data']['yourfieldname'] ,
$send_sms = $data['profile_data']['yourfieldname'] ,
$repeated = $data['profile_data']['yourfieldname']
);

laravel - foreach repeat many times

I have two model : User & Book. I want create a book for each user with a specific QR code
$users = User::get();
$date = ... ;
$finalCount = 0;
$code = 150;
$userCount = count($users);
foreach ($users as $user) {
$book = new Book();
$book->unique_id = uniqid('', true);
$book->user_id = $user->unique_id;
$book->code = "PP-" . strval(mt_rand(100, 999)) . strval($code);
$book->create_date = $date;
$book->status = 'active';
$book->save();
$QRCode = new BaconQrCodeGenerator;
$file = public_path('/images/book/' . $book->code . '.png');
$QRCode->encoding('UTF-8')
->format('png')
->merge('/public/image/logo.png', .15)
->size(1000)
->generate($book->unique_id, $file);
if (File::exists($file))
$finalCount++;
$code++;
if ($finalCount == $userCount)
break;
}
After this function called, i have 20 book for each user. I used an if statement for break the loop ( if ($finalCount == $userCount) ) but it doesn't work.
I can't understand whats going on here and also i have not any error log
Instead of
$file = public_path('/images/book/' . $book->code . '.png');
try
$file = public_path().'/images/book/' . $book->code . '.png';

Yii:Why images are not resized correctly ?

I am using image extension for image re sizing but they are not resized according to the parameters which i gave. Here is my code.Is there any mistake in my code or what. Images which are resized have dimension equal to "800*533"
but not exactly equals to 800*600.
public function actionCreate()
{
$model=new Business;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Business']))
{
$rnd = rand(0, 9999); // generate random number between 0-9999
$model->attributes = $_POST['Business'];
$uploadedFile = CUploadedFile::getInstance($model, 'image');
$fileName = "{$rnd}-{$uploadedFile}"; // random number + file name
$model->image = $fileName;
if ($model->save()) {
if(!empty($uploadedFile)) // check if uploaded file is set or not
{
//$uploadedFile->saveAs(Yii::getPathOfAlias('webroot')."/img".$filename);
$uploadedFile->saveAs(Yii::app()->basePath . '/../img/' . $fileName);
$image = Yii::app()->image->load(Yii::app()->basePath . '/../img/' . $fileName);
$image->resize(800, 600);
$image->save(Yii::app()->basePath . '/../img/' . $fileName);
}
$this->redirect(array('view', 'id' => $model->id));
}
}
$this->render('create', array(
'model' => $model,
));
}
First advise. Don't store not resized image you can use
tempName property of CUploadedFile
$image = Yii::app()->image->load($uploadedFile->tempName );
$image->resize(800, 600);
$image->save(Yii::app()->basePath . '/../img/' . $fileName);
About resize i think you have to calculate size of resized picture.
Here is my code
protected static function getImgBox($img,$width,$height,$bySide,$boxType){
$img_width=$img->getSize()->getWidth();
$img_height=$img->getSize()->getHeight();
$newWidth =0;
$newHeight=0;
switch($boxType){
case self::BOX_TYPE_FILL:
{
$newWidth=$width;
$newHeight=$height;
}
break;
case self::BOX_TYPE_WO:{
if($bySide==self::BY_SIDE_WIDTH) {
$newWidth = $width;
$newHeight = $img_height * $newWidth / $img_width;
}
if($bySide==self::BY_SIDE_HEIGHT){
$newHeight=$height;
$newWidth = $img_width*$newHeight/$img_height;
}
}
break;
case self::BOX_TYPE_INSIDE:{
$newWidth = $width;
$newHeight = $img_height * $newWidth / $img_width;
if($newHeight>=$height){
$newHeight=$height;
$newWidth = $img_width*$newHeight/$img_height;
}
}
}
if($newHeight!=0 && $newWidth!=0){
return new Box(ceil($newWidth),ceil($newHeight));
}
else
return null;
}
I don't know witch extension you use. I use Imagine Extension for Yii 2
$imgpathlogo = App::param("upload_path").'outletlogo'. DIRECTORY_SEPARATOR;
$imgpathlogothumb100 = App::param("upload_path")."outletlogo". DIRECTORY_SEPARATOR."thumb100". DIRECTORY_SEPARATOR;
$imgpathlogothumb200 = App::param("upload_path")."outletlogo". DIRECTORY_SEPARATOR."thumb200". DIRECTORY_SEPARATOR;
///////////////////Chek Outlet New Logo Images////////////////
if ($_FILES['OutletMaster']['name']['outlet_logo'] != "") {
$imagelogo=$files['OutletMaster']['name']['outlet_logo'];
$logofilename=explode(".", $imagelogo);
$logofileext = $logofilename[count($logofilename) - 1];
$newlogofilename = uniqid(). "." . $logofileext;
$model->outlet_logo = $newlogofilename;
move_uploaded_file($_FILES['OutletMaster']['tmp_name']['outlet_logo'],$imgpathlogo.$newlogofilename);
//////////////////Creating Thumbnail For Outlet Logo///////////////////////////
$ext = explode(".", strtolower($newlogofilename))[1];
$src = $imgpathlogo.$newlogofilename;
if ($ext == 'gif')
$resource = imagecreatefromgif($src);
else if ($ext == 'png')
$resource = imagecreatefrompng($src);
else if ($ext == 'PNG')
$resource = imagecreatefrompng($src);
else if ($ext == 'jpg' || $ext == 'jpeg')
$resource = imagecreatefromjpeg($src);
$width = imagesx($resource);
$height = imagesy($resource);
$thumbWidth100 = 100;
$desired_width100 = $thumbWidth100;
$desired_height100 = floor( $height * ( $thumbWidth100 / $width ) );
$virtual_image = imagecreatetruecolor($desired_width100,$desired_height100);
imagecopyresized($virtual_image,$resource,0,0,0,0,$desired_width100,$desired_height100,$width,$height);
imagejpeg( $virtual_image, "{$imgpathlogothumb100}{$newlogofilename}" );
$thumbWidth200 = 200;
$desired_width200 = $thumbWidth200;
$desired_height200 = floor( $height * ( $thumbWidth200 / $width ) );
$virtual_image = imagecreatetruecolor($desired_width200,$desired_height200);
imagecopyresized($virtual_image,$resource,0,0,0,0,$desired_width200,$desired_height200,$width,$height);
imagejpeg( $virtual_image, "{$imgpathlogothumb200}{$newlogofilename}" );
}

Resources