Requesting SOAP using CURL on Codieigniter 4 - codeigniter

I am consuming a service using CURL. I am able to connect all the functions of the services in the form of a CXF Service List using the following code.
$client = \Config\Services::curlrequest();
$response = $client->request('GET', 'www.soapservice.co.za/service');
var_dump($response->getBody());
Var Dump Returns a string with Available services
The service has 10 functions listed in this manner getDataFunction.
How do I invoke the function? Or how do I get the contents of the body and start using Service functions?
Any help would be appreciated

This is how I resolved my issue using Codeignter 4 and Soap Client.
public function ownersearch()
{
helper(['form']);
$username = "";
$password = "";
$url = 'getProperty?wsdl';
$first_name = $this->request->getVar('first_name');
$second_name = $this->request->getVar('second_name');
$last_name = $this->request->getVar('last_name');
$user_id = $this->request->getVar('user_id');
$session_id = session()->get('user_id');
$client = new \SoapClient($url);
$deedsusagemodel = new UsageLogModel();
$args = [
'idNumber'=> $user_id,
'username'=> $username,
'password' => $password,
'officeCode' => 1
];
$usageData = [
'user_id' => $session_id
];
if($user_id != Null){
$response = $client->getFunctionByIDNumber($args);
$ndata = $response->return;
if($ndata->errorResponse->errorCode == 64)
{
$error = $ndata->errorResponse->errorDescription;
return $this->fail($error);
}
if($ndata->errorResponse->errorCode == 550)
{
$error = $ndata->errorResponse->errorDescription;
return $this->fail($error);
}
else{
$usagemodel->insert($usageData);
return $this->respond($ndata, 200);
}
}
}

Related

Facebook uploading image with laravel framework

I am trying to uploading image to the facebook page using GraphQL API
Bellow is some code I am using
use SammyK\LaravelFacebookSdk\LaravelFacebookSdk as Facebook;
try {
$token = $token ? $token : $this->access_token;
// $fb = app(Facebook::class);
$fb = new Facebook(array( 'appId' => '366774494090568', 'secret' => '9f847b900176325ce45d87dec94e81ea', 'fileUpload' => true));
//$fb->setFileUploadSupport(true);
//$fb->setDefaultAccessToken($token);
return $fb;
} catch (\Exception $e) {
throw $e;
}
$payload = unserialize($scheduledPost->payload);
$images = $payload['images'];
$timezone = $payload['scheduled']['publishTimezone'];
$appUrl = config("app.url");
$mediaIds = [];
$mediaCount = 0;
foreach($images as $image){
$relativePath = $image['relativePath'];
$fullPath = $appUrl."/".$relativePath;
$media = ["url" => $fullPath, "published" => false];
$uploadResponse = $this->uploadMedia($media);
$mediaId = $uploadResponse['id'];
$mediaIds["attached_media[$mediaCount]"] = "{'media_fbid': '$mediaId'}";
$mediaCount++;
}
public function uploadMedia($media)
{
$fb = $this->setAsCurrentUser($this->access_token);
$response = $fb->post("/{$this->original_id}/photos", $media);
return $response->getDecodedBody();
}
When I use setFileUploadSupport(true), there is error that function is not defined
If I use new Facebook with 'fileupload' => 'true' it gives me error like bellow
exception: "Symfony\Component\Debug\Exception\FatalThrowableError"
file: "C:\Users\king\Documents\work\01_Unicilix\API\vendor\sammyk\laravel-facebook-sdk\src\LaravelFacebookSdk\LaravelFacebookSdk.php"
line: 28
message: "Argument 1 passed to SammyK\LaravelFacebookSdk\LaravelFacebookSdk::__construct() must implement interface Illuminate\Contracts\Config\Repository, array given, called in C:\Users\king\Documents\work\01_Unicilix\API\app\Traits\Facebook\FacebookTrait.php on line 22
This code was very correct.
The problem was I can get storage image from url because of the server(ubunt) permmission.

How can I store the web push notification settings after the login in database

I want to send web push notification on the browser. I used this tutorial to
send the notification. This is working fine and show the details.
{
"endpoint":"https://fcm.googleapis.com/fcm/send/ftB1OYn5bJY:APA91bGNcquGDcUXr29JiVV5Zos4Vi7FzmZ_wJQMITEXt8FlVBRBtgrPdLnPR6GALtnCOe9RNPP1cmC_bkv9D1BE1o6_-0cMXQsodpPoRCeOP5EDt6EwqK0ys36MbCi3HNTWf7ZcItVi",
"expirationTime":null,
"keys":{"p256dh":"BLJQqNovnlJ28d5xteX8whwdby6l0BYLvC_iyNtY2nO7YXQSI-EOvdOs1LXy8F_EuH2MZi0FU_HoCO-5GRQYYVQ",
"auth":"tDcEgiy5M5tJ3_vXuuQ9uw"}
}
but I want to integrate with my Laravel API.
After the user login, I want to save the endpoint, public key, and auth
to the database.
Login Controller
public function authenticate(Request $request)
{
$credentials = $request->only('username', 'password');
// return $credentials;
$response = array(
'status' => 'Failed',
'msg' => '',
'is_success' => false,
'data' => ''
);
try {
if (!$token = JWTAuth::attempt($credentials)) {
$response["msg"] = "Wrong Username or Password";
$response["status"] = "Failed";
$response["is_success"] = false;
} else {
if (Auth::user()->is_active == 0) {
$response["msg"] = "Your account has not been activated";
$response["status"] = "Failed";
$response["is_success"] = false;
} else {
$data = array();
$user = User::find(Auth::user()->id);
$data['id'] = $user->id;
$data['fname'] = $user->fname;
$data['lname'] = $user->lname;
$data['email'] = $user->email;
$data['username'] = $user->username;
$response["msg"] = "Login Successfully";
$response["status"] = "Success";
$response["data"] = compact('token');
$response["user"] = Auth::user();
}
}
} catch (\Exception $th) {
$response["msg"] = $th->getMessage();;
$response["status"] = "Failed";
$response["is_success"] = false;
}
return $response;
}
I think the best way to solve this, is to make another model for that data, a one to one relationship between user model and push notification data model. Make a controller for CRUD operations on this new model, and just have another http call from the front end to store the data.

Cannot Update On Laravel 5.5

I get problem.
This is my controller
public function finish(Request $request)
{
$result = $request->input('data');
//$data = json_decode($result, true);
return $this->InvoiceBayar($result);
}
public function InvoiceBayar($result)
{
$data = json_decode($result, true);
$transaction = $data['transaction_status'];
$type = $data['payment_type'];
$order_id = $data['order_id'];
$fraud = $data['fraud_status'];
Fee::where('invoice',$order_id)
->update([
'status' => 'Paid',
]);
echo "Transaction order_id: " . $order_id ." successfully transfered using " . $type;
}
This is my Route
Route::POST('/notification', 'SnapController#finish');
When Payment gateway, send a parameter to me, I cannot update DB.
But when I use POSTMAN. I success update DB
You need to use $request->all() as it will contain all payment gateway data.
public function finish(Request $request)
{
$result = $request->all();
return $this->InvoiceBayar($result);
}
Alternately you can do this
$update = Fee::where('invoice',$order_id)->first();
$update->status = 'Paid';
$update->save();
You should try this:
public function InvoiceBayar($result)
{
$data = json_decode($result, true);
$transaction = $data->transaction_status;
$type = $data->payment_type;
$order_id = $data->order_id;
$fraud = $data->fraud_status;
Fee::where('invoice',$order_id)
->update([
'status' => 'Paid',
]);
echo "Transaction order_id: " . $order_id ." successfully transfered using " . $type;
}

Laravel : API response with pagination parameter

I want to pass pagination parameters through POSTMAN and pass sort,order,limits in my model to get query with paginate.? how can i do this? Currently it return error.
Currently my route :
http://localhost:8000/api/allpost
My PostController function :
public function index(Request $request)
{
try {
$allPost = Post::allUserPost();
if($allPost !="" && count($allPost)>0) {
return [
'status_code' => 200,
'message' => "Post retrieved successfully",
'PostDetails' => $allPost,
];
} else {
return response()->json([
'message' => "Post data not found",
'status_code' => 403,
]);
}
} catch (\Exception $ex) {
return response()->json([
'message' => "Internal server error",
'status_code' => 500,
]);
}
}
And my POST model function :
public static function allUserPost(Request $request){
$sort = $this->parameters->sort();
$order = $this->parameters->order();
$limit = $this->parameters->limit();
$userPost = Post::with(['product','categories','user.userDetails'])->whereStatus("Active")->orderBy($sort, $order)->paginate($limit)->get();
$userPost_array = $userPost->toArray();
foreach ($userPost_array as $key => $value) {
# code...
$attributes_arr = array_column($userPost_array[$key]['categories'], 'attribute_id');
$category_ids = Attribute::whereIn("id",$attributes_arr)->pluck('category_id');
$category_ids = array_unique($category_ids->toArray());
$category_details_with_att = Post::getCategoryWithAttributeData($attributes_arr,$category_ids);
unset($userPost_array[$key]["categories"]);
$userPost_array[$key]["categories"] = $category_details_with_att->toArray();
}
return $userPost_array;
}
Currently it returns error
Type error: Too few arguments to function App\Post::allUserPost(), 0 passed in D:\xampp\htdocs\IDM\app\Api\V1\Controllers\Front\PostController.php on line 30 and exactly 1 expected
So how can i pass parameters in postmen and whats the solution for this error?
First change this line to $allPost = Post::allUserPost();
$allPost = Post::allUserPost($request);
and then change this code
$sort = $this->parameters->sort();
$order = $this->parameters->order();
$limit = $this->parameters->limit();
To
$sort = $request->sort;
$order = $request->order;
$limit = $request->limit;
and then you can pass these paramets in a query string like
http://localhost:8000/api/allpost?sort=somesort&order=asc&limit=10
Also chage this line
$userPost = Post::with(['product','categories','user.userDetails'])->whereStatus("Active")->orderBy($sort, $order)->paginate($limit)->get();
to
$userPost = Post::with(['product','categories','user.userDetails'])->whereStatus("Active")->orderBy($sort, $order)->paginate($limit);
You are missing an argument when calling the allUserPost function inside the try block.
It should be
$allPost = Post::allUserPost($request);
and then you can retrieve the parameters from the $request variable.
Just change this line in your code
$allPost = Post::allUserPost($request);
And then in your function, you have to change your request type. And after that you have to do one more change only use paginate() method not with get() method.
public static function allUserPost(Request $request){
$sort = $request->sort;
$order = $request->order;
$limit = $request->limit;
$userPost = Post::with(['product','categories','user.userDetails'])->whereStatus("Active")->orderBy($sort, $order)->paginate($limit);
$userPost_array = $userPost->toArray();
foreach ($userPost_array as $key => $value) {
$attributes_arr = array_column($userPost_array[$key]['categories'], 'attribute_id');
$category_ids = Attribute::whereIn("id",$attributes_arr)->pluck('category_id');
$category_ids = array_unique($category_ids->toArray());
$category_details_with_att = Post::getCategoryWithAttributeData($attributes_arr,$category_ids);
unset($userPost_array[$key]["categories"]);
$userPost_array[$key]["categories"] = $category_details_with_att->toArray();
}
return $userPost_array;
}
I hope this will help you.

adding the uploaded file name to database in blueimp fileupload jquery plugin

I am hoping someone has some experience with the blueimp fileupload jquery plugin at : https://github.com/blueimp/jQuery-File-Upload
How to add the uploaded file name to database ?
In the options array (look for $this->options = array( )
and insert
'database' => 'database_name',
'host' => 'localhost',
'username' => 'user',
'password' => 'password',
Then after
protected function handle_file_upload($uploaded_file, $name, $size, $type, $error,
$index = null, $content_range = null) {
$file = new stdClass();
$file->name = $this->get_file_name($name, $type, $index, $content_range);
$file->size = $this->fix_integer_overflow(intval($size));
$file->type = $type;</code></pre>
Insert this code
//Start added coded
// prepare the image for insertion
$data = addslashes (file_get_contents($uploaded_file));
// get the image info..
$size = getimagesize($uploaded_file);
$file->upload_to_db = $this->add_img($data, $size, $name);
//end added code
and after the function handle_file_upload insert the following code to actually upload the image to the database.
function query($query) {
$database = $this->options['database'];
$host = $this->options['host'];
$username = $this->options['username'];
$password = $this->options['password'];
$link = mysql_connect($host,$username,$password);
if (!$link) {
die(mysql_error());
}
$db_selected = mysql_select_db($database);
if (!$db_selected) {
die(mysql_error());
}
$result = mysql_query($query);
mysql_close($link);
return $result;
}
function add_img($data,$size,$name)
{
$add_to_db = $this->query("INSERT INTO your_database_name
(image_type ,image, image_size, file_name)
VALUES
('{$size['mime']}', '{$data}', '{$size[3]}', '{$name}')") or die(mysql_error());
return $add_to_db;
}
This will store the actual image in the database if you don't want that change the add_img($data,$size,$name) to add_img($size,$name) and just don't pass the $data variable. The $data variable should be stored as a medium or long blob.
You can also comment out the fileupload to directory stuff so you don't get errors if you don't what the images uploaded to a directory. This is in the protected function handle_file_upload
//comment out file upload stuff since storing in database
/*
if ($this->validate($uploaded_file, $file, $error, $index)) {
$this->handle_form_data($file, $index);
$upload_dir = $this->get_upload_path();
if (!is_dir($upload_dir)) {
mkdir($upload_dir, $this->options['mkdir_mode'], true);
}
$file_path = $this->get_upload_path($file->name);
$append_file = $content_range && is_file($file_path) &&
$file->size > $this->get_file_size($file_path);
if ($uploaded_file && is_uploaded_file($uploaded_file)) {
// multipart/formdata uploads (POST method uploads)
if ($append_file) {
file_put_contents(
$file_path,
fopen($uploaded_file, 'r'),
FILE_APPEND
);
} else {
move_uploaded_file($uploaded_file, $file_path);
}
} else {
// Non-multipart uploads (PUT method support)
file_put_contents(
$file_path,
fopen('php://input', 'r'),
$append_file ? FILE_APPEND : 0
);
}
$file_size = $this->get_file_size($file_path, $append_file);
if ($file_size === $file->size) {
$file->url = $this->get_download_url($file->name);
list($img_width, $img_height) = #getimagesize($file_path);
if (is_int($img_width) &&
preg_match($this->options['inline_file_types'], $file->name)) {
$this->handle_image_file($file_path, $file);
}
} else {
$file->size = $file_size;
if (!$content_range && $this->options['discard_aborted_uploads']) {
unlink($file_path);
$file->error = 'abort';
}
}
$this->set_additional_file_properties($file);
}
*/

Resources