Ajax with Authentication - ajax

I need to create the same request in AJAX.
Can somebody advice me how to include authentication?
i tried user/pass as GET Parameters and change URL to
https://user:pwd#www.example.com/token
i use vue-resource but can also use jQuery.ajax or axios
$username = 'user';
$password = 'pwd';
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, 'https://www.example.com/token');
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl_handle, CURLOPT_USERPWD, $username . ':' . $password);
curl_setopt($curl_handle, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$buffer = curl_exec($curl_handle);
curl_close($curl_handle);

try to use jQuery's beforeSend callback to add HTTP header with your authentication load:
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(username + ":" + password));
},

Related

reCaptcha V2 is now timing out during valication

I have been using reCaptcha V2 for awhile now and all of a sudden the validation is timing out on the file_get_contents line.
I can copy the URL from the error and paste it into a new window and the JSON object comes back immediately.
$url = 'https://www.google.com/recaptcha/api/siteverify?secret='. urlencode($secret) .'&response='. urlencode($captcha);
$response = file_get_contents($url);
$responseKeys = json_decode($response,true);
I fixed this timeout problem with the File_get_contents by changing to using $curl instead.
Like this:
$url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($secret) . '&response=' . urlencode($captcha);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
// file get contents not used any more
//$response = file_get_contents($url,0,stream_context_create(["http"=>["timeout"=>120]]) );
$responseKeys = json_decode($response,true);
// should return JSON with success as true

ngenius-payment not able inegrate, i followed by DOCS but giving me error. It should go to payment page of

public function payment(Request $request){
//===============Getting Access Token from N-Genius Platform Network===============================================
$apikey = "api-key"; // enter your API key here
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api-gateway.sandbox.ngenius-payments.com/identity/auth/access-token");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"accept: application/vnd.ni-identity.v1+json",
"authorization: Basic ".$apikey,
"content-type: application/vnd.ni-identity.v1+json"
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"realmName\":\"ni\"}");
$output = json_decode(curl_exec($ch));
$access_token = $output->access_token;
//===============END Getting Access Token from N-Genius Platform Network=============================================
//===============N-Genius Payment Gateway will redirect to the pay page =============================================
$postData = new StdClass();
$postData->action = 'Sale';
$postData->amount = new StdClass();
$postData->amount->currencyCode = 'AED';
$postData->amount->value = 1 * 100;
$postData->language = 'en';
$postData->emailAddress = 'form user email';
$postData->billingAddress['firstName'] = 'form first name';
$postData->billingAddress['lastName'] = 'form last name;
$postData->merchantAttributes['redirectUrl'] = 'redirection page route';
$token = $access_token;
$json = json_encode($postData);
$outlet = "outlet-id";
$token = $access_token;
$json = json_encode($postData);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api-gateway.sandbox.ngenius-payments.com/transactions/outlets/'.$outlet.'/orders');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer '.$token,
'Content-Type: application/vnd.ni-payment.v2+json',
'Accept: application/vnd.ni-payment.v2+json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
$output = json_decode(curl_exec($ch));
$order_reference = $output->reference;
$order_paypage_url = $output->_links->payment->href;
header("Location: ".$order_paypage_url); // execute redirect
//die();
curl_close ($ch);
//===============END N-Genius Payment Gateway will redirect to the pay page =============================================
}
Anyone can help me Please. Please Guide me How to integrate ngenius-payment gateway to laravel app Their documentation not enough to integrate with laravel. i am planing to choose with making payments from their websites, and return back to us with a return URL.
did you get the accessToken?
if yes then try with this post data
{
"action": "SALE",
"amount": {
"currencyCode": "AED",
"value": 1700
},
"merchantAttributes" : {
"redirectUrl" : "url",
"skipConfirmationPage": true,
"cancelText": "Go to Homepage"
},
"emailAddress": "test11#order.com",
"merchantOrderReference": "test-12"
}

Mock Curl response for testing in laravel

I am trying to unit test a function(updateMeeting) in laravel which uses a curl request inside it. I tried many google links but nothing worked. can you guys give me suggestions on this matter.
following are relevant methods. $this->meeting is a MeetingModel
public function updateMeeting($meetingId){
$meeting = $this->meeting->find($meetingId);
$endpoint = \Config::get('api_backend_endpoint');
$response = $this->curlPut($endpoint);
if ($response->http_status_code != 200) {
if(Input::get('source') == 'ajax') {
$apiResponse = app(ApiResponse::class);
$message = 'ERROR Updating Meeting ' . $meeting->name;
return $apiResponse->failed($message);
}
return Redirect::route('meetings.show', $meetingId)
->withInput()
->with('message', 'An error occurred hiding meeting with message: ' . $response->errors);
}
$meeting->save();
}
following is curlPut method
private function curlPut($url, $payload = array())
{
$data_string = json_encode($payload);
$ch = curl_init();
//send through our payload as post fields
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_USERPWD, $this->username . ":" . $this->password);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$buffer = json_decode(curl_exec($ch));
curl_close($ch);
return $buffer;
}
Use a webservice like https://www.mocky.io/. Instead of requesting the real API, you send your requests to their API. You can create mock endpoints which return a response you can define.

Laravel TokenMismatchException with Curl Post

Can someone help with this Token problem?
I think i set the token correct, in the header and in the input post field
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS");
$url = 'http://------My url------/';
foreach ($_POST as $k => $v){
$fields[$k] = $v;
}
// build the urlencoded data
$postvars = http_build_query($fields);
// open connection
$ch = curl_init();
$headers[] = 'X-CSRF-TOKEN:'.$fields['_token'];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
// execute post
$result = curl_exec($ch);
print_r($result);
// close connection
curl_close($ch)
;

AJAX Request returning "Invalid Parameter", Request works without proxy

I am trying to do an ajax request to read xml from a server. I am using a proxy to do so. If i enter the request directly in the browser, it returns the correct XML. When I use my proxy, it returns "Invalid Parameter." Any idea?
Proxy.PHP
<?php
$c = file_get_contents((urldecode($_REQUEST['u'])));
$content_type = 'Content-Type: text/plain';
for ($i = 0; $i < count($http_response_header); $i++) {
if (preg_match('/content-type/i',$http_response_header[$i])) {
$content_type = $http_response_header[$i];
}
}
if ($c) {
header($content_type);
echo $c;
}
else {
header("content-type: text/plain");
echo 'There was an error satisfying this request.';
}
?>
request:
$.ajax({
type: "GET",
url: 'proxy.php?u=' + 'http://192.168.100.147:8080/thredds/sos/cfpoint/timeSeriesProfile-Ragged-MultipeStations-H.5.3/timeSeriesProfile-Ragged-MultipeStations-H.5.3.nc?request=GetObservation&service=SOS&version=1.0.0&responseFormat=text%2Fxml%3B%20subtype%3D%22om%2F1.0.0%22&offering=urn:tds:station.sos:Station1&procedure=urn:tds:station.sos:Station1&observedproperty=temperature&eventTime=1990-01-01T00:00:00Z/1990-01-01T00:00:00Z',
dataType: "xml",
success: parseSOSGetObs,
error: function () {alert("AJAX ERROR for " + capRequest );}
});
Thanks!
From the information you've given, I would guess that the server is expecting more data in your header or cookie data. When scraping data on Ajax pages it is better to use the Curl Library instead of file_get_contents().
When you enter the request directly into the browser, use the Net option in firefox firebug extension to see exactly what is being passed in the headers. Copy those headers and set them in CURL. If that doesn't work, it could be a cookie issue. Have CURL visit the original page, store the cookies and use them for the second request..
Ex:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/COOKIE");
curl_setopt($ch, CURLOPT_URL, "http://originalsite.com/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:9.0a2) Gecko/20111101 Firefox/9.0a2");
$junk = curl_exec($ch);
curl_close($ch);
$headers = array("X-Prototype-Version: 1.6.0", "X-Requested-With: XMLHttpRequest");
$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/COOKIE");
curl_setopt($ch, CURLOPT_COOKIEFILE, "/tmp/COOKIE");
curl_setopt($ch, CURLOPT_URL, "http://originalsite.com/setsomething.sync");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_REFERER, "http://originalsite.com/");
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:9.0a2) Gecko/20111101 Firefox/9.0a2");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$page = curl_exec($ch);
curl_close($ch);
?>
I forgot: You can use the CURLOPT_PROXY option in CURL to set the proxy

Resources