Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 days ago.
This post was edited and submitted for review 3 days ago.
Improve this question
I got so problems to use the Uipath api with php.
I want to create a php api which put value in queue(I already sucess in typescript with the same value), i can’t/don’t want to do it with cURL.
But when I call it, there is an error : failed to open stream: HTTP request failed! HTTP/1.1 401 Unauthorized.
And on My IIS there is this error : Abp.Authorization.AbpAuthorizationException: Current user did not login to the application!.
this is my php call :
$app->post('/test', function (Request $request) use ($app) {
$postdata2 = json_encode(
array(
'itemData'=> array('Name'=>'testeur',
'Priority'=> 'High',
'DeferDate'=> '2023-02-15T09:33:19.667Z',
'DueDate'=> '2023-02-15T09:33:19.667Z',
'RiskSlaDate'=> '2023-02-15T09:33:19.667Z'
)
)
);
// var_dump($token);
$test=56;
$opts2 = array(‘http’ =>
array(
'method' => 'POST',
'header' => 'Content-Type: application/json\r\n'.
'accept : application/json\r\n'.
'X-UiPath-OrganizationUnitId:'.$test.'\r\n'.
'Authorization:Bearer '.$token.'\n',
'content' => $postdata2
)
);
$context2 = stream_context_create($opts2);
$result = file_get_contents('xxxxxxxxx/odata/Queues/UiPathODataSvc.AddQueueItem', false, $context2,-1, 40000);
return $result ;
}
$app->after(function (Request $request, Response $response) {
$response->headers->set('Access-Control-Allow-Origin', $request->headers->get('Origin'));
$response->headers->set('Access-Control-Allow-Methods', 'HEAD, OPTIONS, GET, POST, PUT, PATCH, DELETE');
$response->headers->set('Access-Control-Allow-Credentials', 'true');
$response->headers->set("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With,X-UIPATH-OrganizationUnitId,accept");
});
there is my call in typescript :
headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded'
}),
responseType: 'text' as 'text'
};
public test() {
return this.http.post(`${environment.variables.urlApiSite}/test`, this.httpOptions)
.toPromise()
.then((response) => {
//console.log(response);
return response;
})
.catch(err => this.handleError(err));
}```
I succesfully make the other api post in php to have the token. And the same function in Typescript work.
Related
This question already has answers here:
PHP: How to send HTTP response code?
(8 answers)
Closed 1 year ago.
I am tasked with connecting to an old php login api which simply returns a success or error message response object.
When I connect with the correct credentials I receive the success object and when do not I receive the error. Great!
However, httpClient does not seem to be recognizing the error object. Therefore, the object is accepted as a successful response object regardless of whether it is or it isn't.
The two relevant lines of php code:
$response = array("error" => "Combinación user-pass errónea", "success" => false, "status" => 500, "message" => "Error");
echo $json_response = safe_json_encode($response);
I then added a couple more properties to the error response in the hope of it being recognized:
$response = array("error" => "Combinación user-pass errónea", "success" => false, "status" => 403, "message" => "Error");
No luck...
I have then converted the observable into a promise so as to make the process as close as possible to the code used on an AngularJS app which uses the same login api:
let httpOptions = {
headers: new HttpHeaders(
{ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }),
};
let params = new HttpParams({
fromObject: { action: "login", username: credentials.username, password: credentials.password },
});
this.httpClient.post(`http://xxxxxxxxxxx/user_controller.php`, params.toString(), httpOptions).toPromise()
.then( data => console.log(data),
err => console.log(err) );
Still no luck...
The $http.error handler is triggered by server errors like 500 or 401;
If you wish to trigger a 401 error (unauthorized) for a bad login, do this:
if ($loginFailed) {
header("HTTP/1.1 401 Unauthorized");
exit;
}
Your angular code will pick that up as an error.
If you want to go on sending errors back the way you are currently, pick them up in the success callback, since the call was actually successful according to the server.
this.httpClient.post(`http://xxxxxxxxxxx/user_controller.php`, params.toString(), httpOptions).toPromise()
.then( data => {
console.log(data);
if (JSON.parse(data).error) this.triggerErrorResponse(data.error);
}, err => console.log(err) );
I am trying to call a certain service provider's API and it has public and secret API keys.
However, I am currently using Laravel, but there are only JavaScript, NodeJS, Python implementation on how to send the post request.
My issue is that, How do I send the post request on Laravel/PHP to avoid publicizing the API keys?
They have this specific format that should be followed:
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: 'Basic some_base64_encrypted_key'
},
body: JSON.stringify({
data: {
attributes: {
amount: 10000,
redirect: {success: 'https://www.test1.com/', failed: 'https://www.test2.com/'},
type: 'some_paymenth_method',
currency: 'SOME_CURRENCY'
}
}
})
};
fetch('https://api.serviceprovider.com/v1/sources', options)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err));
Something like this should help you:
$response = Http::withBasicAuth('keys', 'secret')
->withHeaders([
'Content-Type' => 'application/json',
'Authorization' => 'Basic some_base64_encrypted_key'
])
->post('https://api.serviceprovider.com/v1/sources', [
'amount' => '1000',
'type' => 'some_paymenth_method',
'currency' => 'SOME_CURRENCY'
]);
if( $response->successful() ){
//do some logic
//redirect https://www.test1.com/
}elseif( $response->failed() ){
//do some logic
//redirect https://www.test2.com/
}
You can play around with it, try the documentation.
https://laravel.com/docs/8.x/http-client#authentication
Using HTTPS, your authorization header is ALSO encrypted. So that if anyone intercept the message, they cannot read the actual content of the token. However, the header is still visible to both client and server. In your case, you are the client side to the service provider.
With that said, as previous anwser explained well, you can use Laravel HTTP client. This solution is available on laravel 7+. You need to install Guzzle package like this:
composer require guzzlehttp/guzzle
and make the request like this with Http facade:
use Illuminate\Support\Facades\Http;
$response = Http::withToken('place api key')->withHeaders([
'Content-Type' => 'application/json',
])->post('https://api.serviceprovider.com/v1/sources', [
// your data array
]);
// Determine if the status code is >= 200 and < 300...
if ($response->successful()) {
// todo i.e get the response body save the date etc.
} else {
// todo i.e schedule to try again later etc.
}
if your are running older version of laravel, after installing guzzlehttp/guzzle package with composer, you can make the request like this:
$headers = [
'Authorization' => 'place api key',
'Accept' => 'application/json',
];
$body = [
// your data array
];
$client = new \GuzzleHttp\Client();
$url = "https://api.serviceprovider.com/v1/sources";
$response = $client->request('POST', $url, [
'headers'=> $headers,
'body'=> $body
]);
// check response here
// don't forget error handling
I have an API built with PHP Slim Framework 3 and testing the API with Postman everything is working great but when I put the app on the server and tried to make an Ajax Call I've got this message:
Failed to load https://api.mydomain.net/usuario/autenticar?xAuthClienteID=2&xAuthChaveApi=3851b1ae73ca0ca6e3c24a0256a80ace&login=admin&senha=teste: Redirect from 'https://api.maydomain.net/usuario/autenticar?xAuthClienteID=2&xAuthChaveApi=3851b1ae73ca0ca6e3c24a0256a80ace&login=admin&senha=teste' to 'https://api.mydomain.net/404.html' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
I've looked up Slim docs on how to enable CORS on my server and applied it on the function I use to return JSON. It looks like this:
public function withCustomJson($meta = null, $data = null)
{
if (isset($data)) {
$finalResponse['data'] = $data;
}
$finalResponse['meta'] = array(
'status' => (isset($meta['status']) ? $meta['status'] : null),
'message' => (isset($meta['message']) ? mb_convert_encoding($meta['message'], "UTF-8", "auto") : null)
);
$response = $this->withBody(new Body(fopen('php://temp', 'r+')));
$response->body->write($json = json_encode($finalResponse));
// Ensure that the json encoding passed successfully
if ($json === false) {
throw new \RuntimeException(json_last_error_msg(), json_last_error());
}
//Allowing CORS as Slim docs states
$responseWithJson = $response->withHeader('Content-Type', 'application/json;charset=utf-8')
->withHeader('Access-Control-Allow-Origin', '*')
->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
if (isset($meta['codStatus'])) {
return $responseWithJson->withStatus($meta['codStatus']);
}
return $responseWithJson;
}
And here's what my Ajax call looks like:
<script type="text/javascript">
try {
$.ajax({
url: 'https://api.mydomain.net/usuario/autenticar',
type: 'GET',
dataType: 'json',
data: {
xAuthClienteID:'2',
xAuthChaveApi: '3851b1ae73ca0ca6e3c24a0256a80ace',
login: 'admin',
senha: 'teste'
},
ContentType: 'application/json',
success: function(response){
console.log(response);
},
error: function(err){
console.log(err);
}
});
}
catch(err) {
alert(err);
}
</script>
So, what am I doing wrong? Appreciate any help.
I am working on a Hybrid application I want to sent json data to laravel php server using Ionic 2.
I am continuously getting error as
XMLHttpRequest cannot load http://192.168.0.101:8000/SaveUsers.
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:8100' is therefore not allowed
access.
Ionic Code:
register-recipient-page.ts
this.registrationService.sendData(this.donarDetails,this.recipientDetails).subscribe(
response => console.log(response), // success
error => console.log(error), // error
() => console.log('completed') // complete
);
Ionic Code:
registration.service.ts
sendData(recipient,donar): Observable<Object> {
let encoded_data = JSON.stringify({recipientDetails:recipient, donarDetails:donar});
let headers = new Headers();
headers.append('Content-Type', 'application/json;charset=utf-8');
headers.append('Access-Control-Allow-Origin', '*');
headers.append('Access-Control-Allow-Methods', 'GET, POST, PUT,DELETE, OPTIONS');
//let headers = new Headers({ 'Content-Type': 'application/json;charset=utf-8' });
let options = new RequestOptions({ headers: headers });
console.log(encoded_data);
return this.http.post( 'http://192.168.0.101:8000/SaveUsers',encoded_data, options).map(
(res: Response) => res.json() || {}
);
}
laravel: web.php
Route::group(['middleware' => 'cors'], function(){
Route::get('/SaveUsers', 'UserController#saveUser');
});
Cors.php
public function handle($request, Closure $next){
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT,DELETE, OPTIONS');
}
I tried to do testing using simple get on the same url without sending any data, it was working fine.
Please help!!!!
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am using codeigniter for my site. Now I am working to get captcha. For refreshing captcha image, I use Jquery Ajax. When Jquery is calling my captcha_refresh function in controller, I get Internal server error.
Here is my controller:
class Register extends CI_Controller {
function __construct(){
parent::__construct();
//start session
session_start();
$this->load->model('model_users');
$this->load->helper('captcha');
}
function index() { ...}
//here goes some code
// For new image on click refresh button.
function captcha_refresh(){
header('Content-type: application/json');
$values = array(
'word' => '',
'word_length' => 8,
'img_path' => './images/images/',
'img_url' => base_url() .'images/images/',
'font_path' => base_url() . 'system/fonts/texb.ttf',
'img_width' => '150',
'img_height' => 50,
'expiration' => 3600
);
$data= create_captcha($values);
$_SESSION['captchaWord'] = $data['word'];
echo json_encode($data);
exit;
}
}
And here is my js function:
function refresh_captcha() {
new Ajax.Request(baseURL + 'Register/captcha_refresh', {
method: 'get',
evalJSON: true,
parameters: {},
onSuccess: function (transport) {
var answer = JSON.parse(transport.responseText);
},
onError: function () {
alert('Error');
},
onComplete: function () {
}
});
}