Laravel Restclient 500 error in api - php

I wanted to test an laravel api by connecting it with android studio by asyn task but i'm getting HTTP status code 500
Here is my code in AbcController :
public function register_otpsent(Request $req)
{
// $myclass = new MyClasses();
//{cardno}, {mobileno}
$cardno = $req->input('cardno');
$mobileno = $req->input('mobileno');
//
// if(strlen($cardno)==0){
// return response()->json("Please enter valid card number !" , 400);
// }
$cnt = DB::table('acc_status')->where('cardno','=',$cardno)->count();
if($cnt==0){
return response()->json("This card number seems to be wrong !", 400);
}
$accid = DB::table('acc_status')->where('cardno','=',$cardno)->first()->accid;
$pdetails = DB::table('acc_personaldetails')->where('accid','=',$accid)->first();
if($pdetails->mobileno != $mobileno){
return response()->json("This mobile number seems to be not registered !", 400);
}
$otp = mt_rand(100000, 999999);
return response()->json($otp, 200);
}

HTTP Status Code 500 is a server side error (all 5xx are server side)
https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
There could be a number of things that could be wrong, it should be basic debugging:
Does input cardno exists in the request? If it doesn't, boom, error
Does input mobileno exists in the request? If it doesn't, boom, error
Do you have use DB; on the top of the page? If it doesn't, boom, error
Do you have use Illuminate\Http\Request on the top of the page? If it doesn't, boom, error
From this piece of code only, I'm guessing it's one of these (assuming the queries are correct and the tables exist). You should try to validate the data you're receiving, otherwise you'll get unexpected results/errors.
To detect this error, you can either:
Access your log files, located in projectdir/storage/logs/laravel.log (or depending on your custom configuration)
Request it with your browser and make sure you have in your .env file, APP_DEBUG = true, so you can see the error.
Wrap the content in a try-catch and on the catch, response()->json($$exception, 200); and check the error on your android studio end
Check with Postman if you want to use POST, PUT, or any other. (that I usually use https://www.getpostman.com/)

Related

call recording using twilio proxy api

I am doing communication between two people using Twilio proxy when any customer replies to my Twilio proxy reserved number, then the session will create and the session will handle all communication "SMS as well as call" how can I record call in this scenario.
When i am adding Twilio number to proxy pool, the "call comes in" and "message comes in" URL is changed to proxy service name.
Thanks
I found a pretty good project that examples that! And the best part is that really works very well!
Basically, you only need to set up the webhooks when a call is made and on this webhook you call the processRecordCall :D
The method is here:
async function processRecordCall(req){
let callSID = req.body.inboundResourceSid;
console.log(req.body.inboundResourceSid);
console.log(req.body.inboundResourceStatus);
console.log(req.body.outboundResourceStatus);
//The only Proxy callback we care about is the one that provides us context for the initiated outbound dial. We will ignore all other callbacks (including those with context for SMS). Alternatively and depending on the use case, we could use the Proxy "Intercept" callback, but this has additional requirements for handling error status.
if(req.body.outboundResourceStatus == "initiated")
{
//Get all recordings for a given call.
let recordings = await client.recordings.list({callSid: callSID});
console.log(recordings.length);
//We only want to start recording if there are no existing recordings for this callSid. *This may be overkill as I haven't hit this edge case. Consider it preventitive for now*
if(recordings.length == 0)
{
let recordingSet = false;
let callStatus = "";
//Self-invoking function to facilitate iterative attempts to start a recording on the given call. See example here: https://stackoverflow.com/a/3583740
(function tryRecord (i) {
setTimeout(async function () {
if(!recordingSet && i > 0)
{
console.log(`I is ${i}`);
//Fetch the call to see if still exists (this allows us to prevent unnecessary attempts to record)
//Prod code probably needs callback or async added to ensure downstream execution is as expected
let call = await client.calls(callSID).fetch();
callStatus = call.status;
//Only attempt to create the recording if the call has not yet completed
if(callStatus != "completed")
{
//Try to create the recording
try{
let result = await axios.post(`https://api.twilio.com/2010-04-01/Accounts/${accountSid}/Calls/${callSID}/Recordings.json`, {},
{
auth: {
username: accountSid,
password: authToken
}
});
//This code assumes an HTTP 201 *Created* status and thus sucessful creation of recording. Production code may need to explicitly ensure HTTP 201 (eg. handle any other possible status')
console.log(`statusCode: ${result.status}`);
recordingSet = true; //This isn't entirely necessary (eg. could just set i=1 to force stop iteration), but I'm making an assumption that most use cases will prefer having this for reporting purposes
} catch(err){
//TODO(?) - There may be specific errors that should be explicitly handeled in a production scenario (eg. 21220)
}
}
else //The call is completed, so there's no need to loop anymore
{
console.log("Force stop iteration");
i = 1; //Set i = 1 to force stop the iteration
}
}
if (--i || !recordingSet) tryRecord(i); // decrement i and call myLoop again if i > 0 or if recording is not set
}, 1000) //NOTE: 1 second time delay before retry (this can be whatever works best --responsibly-- for the customer)
})(15); //NOTE: 15 attempts to record by default (unless forced to stop or recording already started. This can be whatever works best --responsibly-- for the customer)
}
else
{
console.log("recording exists already");
}
}
else
{
console.log(`We ignored callback with outgoing status '${req.body.outboundResourceStatus}'`);
}
}
I'm linking the full project below
https://github.com/Cfee2000/twilio-proxy-admin-app

Laravel GET route error MethodNotAllowedHttpException

I have a very simple web app created in Laravel 5.5:
There is a database with a list of coupon codes that have either not been redeemed or been redeemed. 0 is not redeemed and 1 is redeemed.
When someone enters a string into a HTML form input and submits it, Laravel goes to a route with that string as a variable.
The Controller code is as follows:
public function redeemCoupon ($coupon_code)
{
$coupon = Coupon::where('coupon_code', $coupon_code)->first();
if ($coupon === null) {
return view ('pages.no-coupon');
}
else if ($coupon->redeemed == 1) {
return view ('pages.used-coupon');
}
else {
$coupon->redeemed = 1;
$coupon->update();
return view('pages.redeemed-coupon', compact('coupon') );
}
}
Route:
Route::post('/redeem-coupon/{coupon_code}', 'CouponController#redeemCoupon');
You can try it out here:
http://178.62.4.225
Everything works fine when done normally, tested on the code "code01". When I enter it and it hasn't been redeemed, it says so, and redeeming it changes the column in the database from 0 to 1. If I try the process again it tells me it has already been redeemed.
The issue is when I'm on the page that tells me it's been redeemed:
http://178.62.4.225/redeem-coupon/code01
If I refresh it with CTRL + R, it just reloads and says it's already been redeemed. But if I paste the URL into a new tab or click into it and refresh by clicking enter, it gives " MethodNotAllowedHttpException" and the resulting debug screen, from what I can tell, offers nothing of use.
Help!
Changing
Route::post('/redeem-coupon/{coupon_code}', 'CouponController#redeemCoupon');
to
Route::any('/redeem-coupon/{coupon_code}', 'CouponController#redeemCoupon');
Did the trick
You are doing a GET request and define a post route change
Route::post('/redeem-coupon/{coupon_code}', 'CouponController#redeemCoupon');
to:
Route::get('/redeem-coupon/{coupon_code}', 'CouponController#redeemCoupon');
Is redeemed set as protected? Also displaying app_debug true displays all your DB connection info (user and pass)
More than likely to be due to the _method.
What page is _method = "POST" on?

Google+ login api problems

I'm trying to implement google+ oauth2 login in my app and I am currently running into a few issues.
I am mainly following what is written here
It seems like the example is using a lot of libraries like twig, but I'm using maining pure php, and I don't think that part is causing any errors
The first issue I faced was that Google_HTTPRequest was not found.
I read somewhere that composer names it Google_HTTP_Request, so I changed that and it seemed to have fixed that problem.
Then php was complaining that I was making a static call on a nonstatic function getIo().
So I changed to :: to -> because that was what made sense to me.
Then I am getting the error
PHP Fatal error: Call to undefined method Google_IO_Curl::authenticatedRequest()
Which probably has something to do with what I changed.
The code I am running is
$google = new Google_Client();
$google->setApplicationName('Hamster Weebly');
$google->setClientId('CLIEnTID');
$google->setClientSecret('himitsudesuyo');
$google->setRedirectUri('postmessage');
$google->authenticate($_POST['AUTH_CODE']);
$token = json_decode($google->getAccessToken());
//$attrbutes = $google->verifyIdToken($token->id_token, '375022219321-us60lmg2cmeoj1aqpl784t7pbl1kg3jv.apps.googleusercontent.com')->getAttributes();
//error_log($attrbutes['payload']['sub']);
$reqUrl = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=' . $token->access_token;
$req = new Google_Http_Request($reqUrl);
$tokenInfo = json_decode($google->getIo()->authenticatedRequest($req)->getResponseBody());
if ($token->error)
{
http_response_code(500);
exit;
}
// Make sure the token we got is for the intended user.
if ($tokenInfo->userid != $gPlusId) {
http_response_code(401);
echo json_encode("Token's user ID doesn't match given user ID");
exit;
}
// Make sure the token we got is for our app.
if ($tokenInfo->audience != CLIENT_ID)
{
http_response_code(401);
echo json_encode("Token's client ID does not match app");
exit;
}
What is my issue?
In the line:
$tokenInfo = json_decode($google->getIo()->authenticatedRequest($req)->getResponseBody());
getIo() should be changed to getAuth() due to (I think) a migration within the api.
After that, I encountered another error in which I changed:
if ($token->error) to if ( isset($tokenInfo->error) )
Good Luck!

Check if Azure Queue exists using REST proxy (PHP)

I'm trying to interact with an Azure Queue using a REST proxy courtesy of the Windows Azure SDK for PHP. Whilst there are plenty of code samples here, I want to check whether a queue exists so that I can create it if necessary, before adding a message to it.
try {
// setup connection string for accessing queue storage
$connectionString = 'DefaultEndpointsProtocol=' . PROTOCOL . ';AccountName=' . ACCOUNT_NAME . ';AccountKey=' . ACCOUNT_KEY;
// create queue REST proxy
$queueRestProxy = ServicesBuilder::getInstance()->createQueueService($connectionString);
// create message
$queueRestProxy->createMessage(QUEUE_NAME, 'Hello World!');
} catch(ServiceException $e){
// Handle exception based on error codes and messages.
// Error codes and messages are here:
// http://msdn.microsoft.com/en-us/library/windowsazure/dd179446.aspx
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message."<br />";
}
Creating a queue is as simple as this...
$queueRestProxy->createQueue(QUEUE_NAME);
Should I simply include the queue creation code prior to creating a message or is there a more efficient way to ascertain whether the queue exists before interacting with it?
Normally in other Windows Azure SDKs I have seen methods like createQueueIfNotExists and I'm surprised that this method is missing from PHP SDK. Basically the way this function works is that it tries to create a queue. If the queue by the same name exists in storage, storage service throws a Conflict (409) error.
Since this function is not there, you could do the same i.e. try to create the queue inside its own try/catch block and check the error code. If the error code is 409, you continue otherwise you rethrow the exception. Something like the code below:
try {
// setup connection string for accessing queue storage
$connectionString = 'DefaultEndpointsProtocol=' . PROTOCOL . ';AccountName=' . ACCOUNT_NAME . ';AccountKey=' . ACCOUNT_KEY;
// create queue REST proxy
$queueRestProxy = ServicesBuilder::getInstance()->createQueueService($connectionString);
try {
// now try to create the queue.
$queueRestProxy->createQueue(QUEUE_NAME);
} catch(ServiceException $e){
$code = $e->getCode();
//Now check if the $code is 409 - Conflict. If the error code is indeed 409, you continue otherwise throw the error
}
// create message
$queueRestProxy->createMessage(QUEUE_NAME, 'Hello World!');
} catch(ServiceException $e){
// Handle exception based on error codes and messages.
// Error codes and messages are here:
// http://msdn.microsoft.com/en-us/library/windowsazure/dd179446.aspx
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message."<br />";
}
P.S. I have not tried to execute the code, so it may throw errors. This is just to give you an idea.
I've posted an answer below for completeness and to make it easy for people to see the answer at a glance.
Should I simply include the queue creation code prior to creating a
message or is there a more efficient way to ascertain whether the
queue exists before interacting with it?
There are two ways to approach this...
Include the createQueue statement prior to creating a message, but wrap this statement in a try-catch block as directed by Guarav Mantri's answer i.e. ignore 409 errors, but throw an exception for any other types of error.
For information, when you include a createQueue statement prior to creating a message...
if a queue of the same name already exists and the metadata
associated with the existing queue is the same as that passed to the
createQueue statement then the queue will not be created and the
Queue REST Proxy will internally receive a 204 (No Content) status code, but this
response code is not made available to the programmer. So,
essentially, the createQueue statement doesn't cause an
error/exception to be raised in this scenario.
if a queue of the same name already exists and the metadata
associated with the existing queue isn't the same as that passed
to the createQueue statement then the queue will not be created and
the Queue REST Proxy will receive a 409 (Conflict) status code and will raise an
exception which allows the programmer to access this response code and the associated QueueAlreadyExists message.
Source: Create Queue (REST API) - see Remarks section
Create a queueExists function and call it to decide whether or not queue creation is necessary. Here is one way to implement such a function...
public function queueExists($queueRestProxy, $queueName) {
$result = FALSE;
$listQueuesResult = $queueRestProxy->listQueues();
$queues = $listQueuesResult->getQueues();
foreach($queues as $queue) {
if ($queue->getName() === $queueName) {
$result = TRUE;
break;
}
}
return $result;
}
Hope this helps someone!

help with php and xml for yahoo service

I am working on a PHP code for my social network, what I am planning to do is on user signup or profile update
I will take there zipcode that they enter and use yahoo to lookup there lattitude and logitude from there zipcode
I will then save these value to there user mysql table, this will be used later on to find users located within X amount
of miles from them.
Here is my code so far to get this info before storing into DB
<?PHP
function yahoo_geo($location) {
$q = 'http://api.local.yahoo.com/MapsService/V1/geocode';
q .= '?appid=rlerdorf&location='.rawurlencode($location);
echo $q;
libxml_use_internal_errors(true);
$xml = simplexml_load_file($q);
if(!is_object($xml)) return false;
$ret['precision'] = (string)$xml->Result['precision'];
foreach($xml->Result->children() as $key=>$val) {
if(strlen($val)){
$ret[(string)$key] = (string)$val;
}
return $ret;
}
$_REQUEST['location'] = 32744; // my zip code
$a = yahoo_geo($_REQUEST['location']);
// set retunred data to some variables for storage into MySQL
$latitude = $a[Latitude];
$longitude = $a[Longitude];
// MySQL code will go here
// Output for demo
echo 'Lattitude' .$latitude. '<BR><BR>';
echo 'Longitude' .$longitude. '<BR><BR>';
?>
This works great except if a long. and lat. is not found it returns an error to the browser
Warning: simplexml_load_file(http://api.local.yahoo.com/MapsService/V1/geocode?appid=rlerdorf&location=some non zipcode) [function.simplexml-load-file]: failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in C:\webserver\htdocs\test\geolocation\index.php on line 16
Note; I could make sure that zipcode is numeric only but I would rather not as yahoo will let me search with other fields as well, so If a user does not enter a zipcode I will make it use a city or state or even country at the worse case so every user should have some sort of longitude and lat. saved
Is there a good way to avoid the error showing or even better is there a way to detect id there is an error and if an error occurs I could insert a default value for that user?
Not exactly sure what your question is, but I think you're looking for the error control operator #
xml = #simplexml_load_file($q);
Your function will then return false as normal.
You need to check that later though (and add some quotes):
if (!$a)
{
// Do something
}
else
{
$latitude = $a['Latitude'];
$longitude = $a['Longitude'];
}
With the # operator :
you have to use it everytime you need it
when you want to debug, you have to remove it from everywhere (or use the scream extension -- which you cannot always install, depending on your hosting service)
if there is an error somewhere you didn't put #, it will still be displayed to the user.
Another solution would be to use something like this at the beginning of your script, when you are on the production server :
ini_set('display_errors', 'Off');
That way, no error is ever displayed to the end-user (they don't need to see those, and probably wouldn't understand), even in situations you didn't think about ; and it's easy to get all the errors displayed on your development machine : just on line to comment ;-)
Note : in production, if you can set the configuration like you want, there is the possibility to log errors to a file ; that way, you can check those, and not have them displayed.

Categories