I've got a project in front of me that requires me to build a Soap Client in PHP and pass with the call/request a basic authorization. The client's WSDL doesn't specify a header. This is throwing me off because the basic authorization is needed to access the API in order to use the webservice (a simple user lookup).
This is my code:
<?php
try {
$fullname = "Joe Smith";
$zipcode = "33149";
$session = "1a2b3c4d5e6f";
$client = new SoapClient('example.wsdl', array('location'=>'https://webservice/location', 'username'=>"Green", 'password'=>"tearocks"));
$search = $client->userSearch($session, $fullname, $zipcode);
print $search;
} catch (SoapFault $e) {
echo $e->faultstring;
}
?>
The result displays "Unauthorized Request", a 401 error. I've gone through the php.net manual and various ebooks without avail. Any thoughts?
Try passing "login" instead of "username" according to the docs that's what is used.
Related
When I send a request in postman, it returns a html body and it says 404 not found. Does this mean my php server is not running? I am trying to run my php code in visual studio code as a php server.
This is the php file:
<?php
// Headers
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
include_once '../../config/Database.php';
include_once '../../models/Login.php';
// Instantiate DB & connect
$database = new Database();
$db = $database->connect();
// Instantiate blog post object
$login = new Login($db);
//$login->email=isset($_GET['username']) ? $_GET['username']:die();
$login->password=isset($_GET['phoneNumber']) ? $_GET['phoneNumber']:die();
$result = $login->read_single();
$num = $result->rowCount();
if($num > 0) {
// Post array
$posts_arr = array();
$posts_arr['data2'] = array();
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
extract($row);
$post_item = array(
//'username' => $username,
'phoneNumber' => $phoneNumber,
'token' =>$token,
'tokencreatedat'=>$tokencreatedat,
'expTime'=>$expTime
);
// Push to "data"
//array_push($posts_arr, $post_item);
array_push($posts_arr['data2'], $post_item);
}
// Turn to JSON & output
echo json_encode($posts_arr);
} else {
// No Posts
echo json_encode(
array('message' => 'No Posts Found')
);
}
?>
Plus, how do you run php as a web server for RESTful API?
UPDATE: when I put localhost:3000/path in the url in postman, it return 200 which mean its okay. But when I input the IP address, it returns 404.
404 means the url you are trying to get is not found !
as per your html,I think your api endpoints ( if you created any or not in both case) has an issue so its showing 404.
I assume you are trying to create an api for user login right ?
at first you should learn about the RESTful Api concept and how to create api endpoints.
this might help
For a quick learning:
create a login_api.php file which will contain php code only. it will take your username / password etc from _POST[], validate your user and redirect you to your home.php
This means that the api which you are hitting have some issues.
So in your case most probably you have some issues with your php laravel code, that's why whenever you are calling that api then html code was returned on behalf of that.
Moreover 404 means that api is not found but then your service is running
Please check your code for syntactical bugs.
For Restful Api's using php, you can refer this and this
I'm beginning to learn how to properly use REST API's following a popular tutorial here
When trying to create a simple POST api I keep running into a 400 error and I haven't found any answers online as of yet.
API is as follows:
$app->post('/test', function() use ($app) {
// check for required params
verifyRequiredParams(array('email'));
echo "Success";
});
Which attempts to verify the 'email' parameter with this block of code, unchanged from the tutorial:
function verifyRequiredParams($required_fields) {
$error = false;
$error_fields = "";
$request_params = array();
$request_params = $_REQUEST;
// Handling PUT request params
if ($_SERVER['REQUEST_METHOD'] == 'PUT') {
$app = \Slim\Slim::getInstance();
parse_str($app->request()->getBody(), $request_params);
}
foreach ($required_fields as $field) {
if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) {
$error = true;
$error_fields .= $field . ', ';
}
}
if ($error) {
// Required field(s) are missing or empty
// echo error json and stop the app
$response = array();
$app = \Slim\Slim::getInstance();
$response["error"] = true;
$response["message"] = 'Required field(s) ' . substr($error_fields, 0, -2) . ' is missing or empty';
echoRespnse(400, $response);
$app->stop();
}
}
The code always fails with a 400 error code because it seems that the $_REQUEST function is returning an empty array. Any idea's what could be going wrong? I'm developing on an ubuntu server running apache.
The Slim API framework is set up correctly as I can call a very simple call through Google's Advanced Rest Client which echos a response correctly. And I am definitely passing the correct parameters into the api.
UPDATE: I've also tried running the $_REQUEST and $_GET functions directly from the api and it just returns an empty string like this:
Array
(
)
I wonder if there's some sort of apache config file that's blocking data to these functions or something?
Possible Problem:
Have you double checked that your selected Content-Type in the request headers is right?
I suspect the client is perceiving a malformed markup language being sent from the server side.
Possible Solution:
Change Content-Type: application/x-www-form-urlencoded to application/JSON or vice versa.
For the tutorial to receive
$name = $app->request->post('name');
the POST parameters have to be in Payload data
name=yourname&password=pass&email=me#mail.com
application/x-www-form-urlencoded
If you provide the parameters after the URL but not in the payload data, that is for a GET request. In such a case the tutorial partly works (it sees the parameters to verify required parameters are present) but it is looking for the parameters "anywhere" when it should only be looking in the payload parameters for POST.
I am implementing twilio outgoing call with wordpress woocommerce. As soon as the order is placed the site owner will receive a call. However i couldn't find a way to handle if the person didn't answer the call for some reason. The documentation is going above my head.
What i want is to make twilio recall if the call isn't answered. Or i am open to suggestion how else would be the good way to handle. Please note that i have not created any application at Twilio yet. Just using the PHP SDK as the account id and token is provided by default.
here is the code
function send_order_Call($order_id) {
try {
$file = plugin_dir_path(__FILE__) . "order.xml";
$twiML = simplexml_load_file($file);
$twiML->Say = "Hello, You have received a new order. The order id is {$order_id}. Kindly check you fax for details";
file_put_contents($file, $twiML->asXML());
require_once 'Twilio.php';
//Initializing Twilio Rest
$sid = "ACcbd06f8e73asdfsdaf1";
$token = "32ccf4bdcasdfsafc";
$client = new Services_Twilio($sid, $token);
$call = $client->account->calls->create("+12asfsaf", "+1ssd8777asfsf7", site_url()."/wp-content/plugins/woocommerce-twilio/order.xml", array());
// echo $call->sid;
} catch (Exception $e){
$error = $e->getMessage();
die($error);
}
}
TL;DR; You need to set the statusCallBack parameter for the options array.
Please see https://stackoverflow.com/a/24482140/1751451
Using php for Reddit api for submitting a story returns bad captcha as error.
I am able to login using the api and get usermod and captcha perfectly using api.
Ideally if the reddit_session cookie is passed it should post and not return bad captcha can someone shed me some light on this..
reference link:
https://github.com/reddit/reddit/wiki/API
<?php
$user = "";
$passwd = "";
$url = "http://www.reddit.com/api/login/".$user;
$r = new HttpRequest($url, HttpRequest::METH_POST);
$r->addPostFields(array('api_type' => 'json', 'user' => $user, 'passwd' => $passwd));
try {
$send = $r->send();
$userinfo = $send->getBody();
} catch (HttpException $ex) {
echo $ex;
}
$arr = json_decode($userinfo,true);
$modhash = $arr['json']['data']['modhash'];
$reddit_session = $arr['json']['data']['cookie'];
$post = array('uh'=>$modhash,
'kind'=>'link',
'url'=>'yourlink.com',
'sr'=>'funny',
'title'=>'omog-asdfasf',
'id'=>'newlink',
'r'=>'funnyier',
'renderstyle'=> 'html'
);
$url = "http://www.reddit.com/api/submit";
// Upvote RoboHobo's comment :)
// Add user cookie data
$r->addCookies(array("reddit_session" => $reddit_session));
// Set URL to vote
$r->setUrl($url);
// Add vote information, found at http://wiki.github.com/talklittle/reddit-is-fun/api-all-functions
$r->setPostFields($post);
// Send request blindly
try {
$userinfo = $r->send();
} catch (HttpException $ex) {
echo $ex;
}
pre($userinfo);
exit;
function pre($r){
echo "<pre />";
print_r($r);
}
?>
For anyone else that stumbled onto this question lately and is still having that issue:
The above issue was fixed and works correctly however if you created a new account for your reddit bot and try to submit a story you will recieve a bad_captcha error. New accounts have to submit captchas until they gain a certain amount of karma so this is the error you are seeing. Try the request with an older account and this should solve your problem.
From what I can tell, at the moment CAPTCHA is broken in the Reddit API. They originally were using an outdated PyCAPTCHA and were migrating to reCAPTCHA. Since then, there has been an issue with using api_type:json which has a work around and someone on github is currently working it. He also offered an explanation/solution:
Quite simply, the json (though not jquery) result should contain the captcha_id when a >captcha is required. By captcha_id I mean the part to complete a url like the followng: >http://www.reddit.com/captcha/(captcha_id).png
The use case I encountered is when trying to submit a story via the api using >api_type:json. I am nicely notified that my non-existent captcha is incorrect, however, I >then have to make a request to http://www.reddit.com/api/new_captcha in order to get the >captcha_id. This last round trip seems unnecessary.
I'm using php-foursquare library for Foursquare API calls.
This is my index.php
require_once("FoursquareAPI.class.php");
$client_key = "blabla";
$client_secret = "blabla";
$redirect_uri = "http://localhost/4kare/index.php";
// ($redirected_uri equals to registered callback url)
// Load the Foursquare API library
$foursquare = new FoursquareAPI($client_key,$client_secret);
// If the link has been clicked, and we have a supplied code, use it to request a token
if(array_key_exists("code",$_GET)){
// example $_GET['code'] = FJRW1Z5TZ3H0E3Y2WN4Q0UPSH1PEIDADTZDHYKVG32DJTH2E
$token = $foursquare->GetToken($_GET['code'],$redirect_uri);
}
// If we have not received a token, display the link for Foursquare webauth
if(!isset($token)){
echo "<a href='".$foursquare->AuthenticationLink($redirect_uri)."'>Connect to this app via Foursquare</a>";
// Otherwise display the token
}else{
echo "Your auth token: $token";
}
But GetToken() method returning 500 server error . THis is source code of GetToken () method :
public function GetToken($code,$redirect){
$params = array("client_id"=>$this->ClientID,
"client_secret"=>$this->ClientSecret,
"grant_type"=>"authorization_code",
"redirect_uri"=>$redirect,
"code"=>$code);
$result = $this->GET($this->TokenUrl,$params);
$json = json_decode($result);
$this->SetAccessToken($json->access_token);
return $json->access_token;
}
I'm not using php-foursquare, but I faced a similar problem when using Guzzle to connect to 4sq REST endpoints.
It turns out that a request will result in an unhandled exception if you don't wrap it in a try catch block and it gets anything different than a 200 header. I couldn't understand why I was getting error 500, but when I captured and printed the exception it showed Foursquare returning a 401 with a much more informative msg. In my case, the redirecting URL had a typo.
try {
$result = $this->GET($this->TokenUrl,$params);
} catch (Exception $e) {
echo $e->getMessage();
}
Well, here is the problem. You don't have any control over 4square's servers, so you don't have enough information to go about this without guessing. I would do two things:
Google the API call you are using and see if it's a common problem with a commmon answer
Email 4square - it's their server spitting out an error message with no useful information.