How can I test RESTful api of DELETE in Laravel by using Codeception?
I use the following function:
public function authenticatedUserSuccessDeleteEmployee(ApiTester $I)
{
$I->wantToTest('authenticated super user success delete employee');
// set header authorization
$I->amBearerAuthenticated($this->token);
//
$this->employee = factory(\App\Models\Employee::class)->create([
'id' => '20200100000000'
]);
// see database row is containing our expected data
$I->seeRecord('employees', ['id' => '20200100000000']);
// Send delete request
$I->sendDELETE('employees', array('id' => '20200100000000'));
// check expected response code is 200 OK
$I->seeResponseCodeIs(200);
}
But the employee does not created in the DB!
How can I create an object for testing delete API?
I found the problem. I need to send the id as part of the url!
$I->sendDELETE('employees/20200100000000');
Related
In my tutorial, I realised that I am able to get the number/id of the order during every event except orders/delete. In my controller below, I try to retrieve the order number just as I do for every topic ('orders/create', 'orders/paid')etc, but then I get an error saying:
Undefined index: number in Controller
Controller
public function registerOrderDeleteWebhook()
{
$shop = Auth::user()->site;
$token = Auth::user()->access_token;
$shopify = Shopify::setShopUrl($shop)->setAccessToken($token);
Shopify::setShopUrl($shop)->setAccessToken($token)->post("admin/webhooks.json", ['webhook' =>
['topic' => 'orders/delete',
'address' => 'https://example.domain.com/order-delete-webhook',
'format' => 'json'
]
]);
}
public function orderDeleteWebhook(Request $request)
{
$order = $request->getContent();
$order = json_decode($order, true);
$order_id = $order['number'];
//send notification to Admin with order number deleted below
}
Why could this be happening for only orders/delete?
the undefinded index error
occurs because there is no number field in Shopify Order Delete webhook response. Moreover, it is always a good idea to check if the field exists in the first place.
If you look at the Delete Order response sent by Shopify, it only includes,
{
"id": 777859760246
}
where id is the Order Id. But as the order is deleted you cannot get anymore details later even via API. According to this forum post an order cannot be deleted until it is cancelled first. So a workaround is to listen to Order Cancel hook too and save this information somwehere in your Laravel application ( database etc ) and use it later when Order Delete webhook is recieved.
Im using this laravel package "https://github.com/kanazaca/easypay" to create a MB reference using the Easypay API.
I have this method to create the reference:
public function generateReference()
{
$amount = Session::get('total');
$payment_info = [
't_value' => $amount,
'o_obs' => '',
't_key' => 1
];
$easypay = new EasyPay($payment_info);
$reference = $easypay->createReference();
Session::put('entity', $reference['ep_entity']);
Session::put('reference', $reference['ep_reference']);
Session::put('value', $reference['ep_value']);
}
And it works fine with this code I get some reference codes which can be payed using MB or credit-card.
Then, when a payment is made, easypay will call a "Notification URL".
that we should configure on easypay's backoffice under "URL Configurations".
Because when the easypay service receives the payment they will call the URL that we provided. So I defined a url in the easypay´s backoffice and created a route in the project:
Route::get('/easypay/notification-callback', [
'uses' => 'PaymentController#receiveNotifications',
'as' =>'mb.notifications'
]);
In the api backoffice there is a button that simulates a payment, after this button is clicked nothing happens and if I manually access "http://....ngrok.io/easypay/notification-callback" it appears an empty array:
[]
But in the documentation (https://docs.easypay.pt/workflow/payment-notification) says that when Easypay calls this endpoint, it comes with a few parameters: "ep_cin", "ep_user" and "ep_doc" that will be necessary in the process. So it should not appear an empty array.
Do you know what can be the issue? Im a beginner uing API´s so Im not understnading what the issue can be.
PaymentController receiveNotifications() method:
public function receiveNotifications(Request $request)
{
dd($request->all());
//$easypay = new EasyPay($payment_info);
//$xml = $easypay->processPaymentInfo();
//return \Response::make($xml, '200')->header('Content-Type', 'text/xml'); //must return in text/xml for easypay
}
receiveNotifications() method with log:
public function receiveNotifications(Request $request)
{
//dd($request->all());
Log::info('Showing info: ' .var_export($request->all(),true));
$payment_info = [
'ep_cin' => $request->ep_cin,
'ep_user' => $request->ep_user,
'ep_doc' => $request->ep_doc
];
Log::info('Showing info: ' .var_export($payment_info,true));
//dd($payment_info);
$easypay = new EasyPay($payment_info);
$xml = $easypay->processPaymentInfo();
return \Response::make($xml, '200')->header('Content-Type', 'text/xml'); //must return in text/xml for easypay
}
The session is saved in the session file of the user that visits your website that initiates the payment.
The receiveNotifications would call data from the session file that belongs to the payment gateway server if you were doing anything there. The data isn't matched because the two don't know about each other.
Also, you might not have a Session::save() somewhere in your request handling which writes the session data to file.
Store the reference in a database. Create a model for storing this data, so you can then query that model for the correct reference ID to verify/do stuff.
When the request comes back from the payment gateway use the variables ep_cin, ep_user and ep_doc to get the data from the model.
When you manually request that data you are requesting it with a GET request, which doesn't send the above data along.
The request made by the payment provider will get the result of the DD but that's logged nowhere, so nothing happens.
Log your data for requests triggered by remote api's to see what happens.
Hi guys I am having a problem with twilio currently setting an assignment to a worker and i need to pass the worker to the conference. My problem is that i cant use session to retrieve the id in the session and the id will be the conference name of the conference to be able to have a unique conference name for a worker.
This is my callback in twilio
This is my code to get the task. And the id will be passed on forward_queue_conference.
public function assignment()
{
id = $this->session->userdata('user_id');
$TaskAttributes = $_POST['TaskAttributes'];
$json = json_decode($TaskAttributes, true);
$this->Mytwilio->SetAssignment($json['from'], AFTERTALK, HTTP_BASE_URL."agent/call_controls/forward_queue_conference?data=".$id);
}
This is my code on forward_queue_conference to retrieve the pass data
public function forward_queue_conference()
{
roomName = $_GET['data'];
$this->Mytwilio->CallerToQueue($roomName);
}
MyTwilio is a library that i made for twilio functions.
function CallerToQueue($roomName)
{
$response = new Services_Twilio_Twiml;
$dial = $response->dial();
$dial->conference($roomName, array(
'startConferenceOnEnter' => 'true',
'endConferenceOnExit' => 'true',
'muted' => 'false',
'record' => 'record-from-start',
'waitUrl' => 'http://twimlets.com/holdmusic?Bucket=com.twilio.music.ambient',
));
print $response;
}
And this is my whole process my problem is that i cant get the session data to become the conference room.
Twilio developer evangelist here.
When Twilio makes a callback to a URL on your website, it does not share the same session as your logged in user. It is therefore impossible to get the current user ID from the session.
However, your workers have an ID in the Twilio system. And that ID is sent as part of the parameters for the webhook. So, I recommend using the WorkerSid as the conference room instead of your own ID. Or alternatively, you could map between your worker ID and the user ID in your system.
I am using the codeigniter rest server api library.
When I enter http://localhost/projects/myapi/key/index_put.php and hit enter gives me the following error:
<xml>
<status>0</status>
<error>Invalid API Key</error>
</xml>
When I give a dummy string in the url, like:
http://localhost/projects/myapi/key/index_put.php?X-API-KEY=asldfj9alsdjflja97979797997
I get the same problem. Any idea?
index_put.php:
public function index_put() {
// Build a new key
$key = self::_generate_key();
// If no key level provided, give them a rubbish one
$level = $this->put('level') ? $this->put('level') : 1;
$ignore_limits = $this->put('ignore_limits') ? $this->put('ignore_limits') : 1;
// Insert the new key
if (self::_insert_key($key, array('level' => $level, 'ignore_limits' => $ignore_limits))) {
$this->response(array('status' => 1, 'key' => $key), 201); // 201 = Created
} else {
$this->response(array('status' => 0, 'error' => 'Could not save the key.'), 500); // 500 = Internal Server Error
}
}
i faced the same issue .don't mention put/get/post in URL ,RestServer itself recognizes the request nature base on parameter you pass two step required to solve your problem .
1st Step :
http://localhost/projects/myapi/key/index_put.php
must change to :
http://localhost/projects/myapi/key/index.php
2nd step:
create an api kay using sha1(max 40 character) in the keys table (table structure show in config/rest.php file),
enter 1 in is_private_key field and ::1 in ip_address field.
create the record ,and check it again .
This question is old but for those who finds this, the answer is:
The library https://github.com/chriskacerguis/codeigniter-restserver when using PUT method, the API KEY should be in the put header variables as x-www-form-urlencoded type.
Use google chrome postman and fill like image below:
I am able to view and delete the data by passing ID in the URl in format of:
/apis/view/id.json
using:
public function view($id) {
$api = $this->Api->findById($id);
$this->set(array(
'api' => $api,
'_serialize' => array('api')
));
}
Similarly I want to implement add and edit, where I can pass data in Json format in the HTTP body and store/edit it in the database.
I couldn't follow the this solution:
CakePHP API PUT with JSON input
I couldn't understand how to use
$data = $this->request->input('json_decode');
to achieve it.
Add can simply be used as given in documentation by appending .json to it. The URL at which you post the data will become /apis.json. This will automatically access the add() method.
Assuming you pass json values email and password in such format: {"email":"abc#def.com","password":"123456"}
public function add(){
$data=$this->request->input('json_decode', true ); //$data stores the json
//input. Remember, if you do not add 'true', it will not store in array format.
$data = $this->Api->findByEmailAndPassword($data['email'],$data['password']);
//simple check to see if posted values match values in model "Api".
if($data) {$this->set(array(
'data' => $data,
'_serialize' => array('data')));}
else{ $this->set(array(
'data' => "sorry",
'_serialize' => array('data')));}
}// The last if else is to check if $data is true, ie. if value matches,
// it will send the input values back in JSON response. If the email pass
// is not found, it will return "Sorry" in json format only.
Hope that answers your question! Put is also very similar, except it will check if the data exists, if it doesn't it will create or else it will modify existing data. If you have any further doubts don't hesitate to ask :)
As explained in the linked documentation, CakeRequest::input() reads the raw input data, and optionally passes it through a decoding function.
So $this->request->input('json_decode') gives you the decoded JSON input, and in case it's formatting follows the Cake conventions, you can simply pass it to one of Model save methods.
Here's a very basic (untested) example:
public function add()
{
if($this->request->is('put'))
{
$data = $this->request->input('json_decode', true);
$api = $this->Api->save($data);
$validationErrors => $this->Api->validationErrors;
$this->set(array
(
'api' => $api,
'validationErrors' => $validationErrors,
'_serialize' => array('api', 'validationErrors')
));
}
}
This will try to save the data and return the save result as well as possible validation errors.
In case the formatting of the input data doesn't follow the Cake conventions, you'll have to transform it accordingly.