Authentication Fail at Functional Test in Symfony 3 - php

I am newbie for Symfony. I am trying do functional test for UserController. But I don't know how can do it. Because response 401 not equals 200. How can I skip authentication. My codes below:
public function testGetAction() {
$expected = array(
'user'=>
array(
'id' => 1,
'tcId' => "23456789415",
'email' => '*********',
'firstName' => '****',
'lastName' => '****'
)
);
$expect = json_encode($expected);
$fixtures = array('AppBundle\DataFixtures\ORM\LoadUserData');
$this->loadFixtures($fixtures);
$users = LoadUserData::$users;
$this->client->request('GET', 'ajax/users/'.$users[0]->getTcId(), array('ACCEPT' => 'application/json'));
$response = $this->client->getResponse();
$content = $response->getContent();
$this->assertJsonResponse($response, 200);
$this->assertEquals($expect , $content);
}
And my problem is here:
3) AppBundle\Tests\Controller\UserControllerTest::testGetAction
{"code":401,"message":"Authentication Required"}
Failed asserting that 401 matches expected 200.

Related

GuzzleHttp\Exception\ConnectException: cURL error 7: Failed to connect - Laravel

I'm trying to post a Third party Api with raw body with my controller , It works fine when I test it from localhost , but when I publish my project on the Server (Cpanel) , I get this Error :
GuzzleHttp\Exception\ConnectException: cURL error 7: Failed to connect.
Here is an example of my code inside the controller :
use Illuminate\Support\Facades\Http;
public function testApi(){
$array = [
'FullName' => 'Full Name',
'PhoneNumber' => '9999999999',
'Date' => '2022-06-26 17:20',
'Note' => '',
];
try {
$response = Http::withBody(json_encode($array) , 'application/json')
->post('https://example');
return $response->status();
} catch (Exception $exception){
return $exception;
}
}
and I also tried using GuzzleHttp and the same thing it works on localhost , and not working when I publish the project on the server.
use GuzzleHttp\Client;
public function testApi(){
$array = [
'FullName' => 'Full Name',
'PhoneNumber' => '9999999999',
'Date' => '2022-06-26 17:20',
'Note' => '',
];
try {
$client = new Client();
$response = $client->request('POST', 'https://example', [
'body' => json_encode($array),
'headers' => [
'Content-Type' => 'application/json',
]
]);
return $response->getStatusCode();
} catch (Exception $exception){
return $exception;
}
}
before disable firewall and test again.
there can be a firewall that blocks your requests

HTTP Guzzle not returning all data

I have created a function that contacts a remote API using Guzzle but I cannot get it to return all of the data available.
I call the function here:
$arr = array(
'skip' => 0,
'take' => 1000,
);
$sims = api_request('sims', $arr);
And here is the function, where I have tried the following in my $response variable
json_decode($x->getBody(), true)
json_decode($x->getBody()->getContents(), true)
But neither has shown any more records. It returns 10 records, and I know there are over 51 available that it should be returning.
use GuzzleHttp\Client;
function api_request($url, $vars = array(), $type = 'GET') {
$username = '***';
$password = '***';
//use GuzzleHttp\Client;
$client = new Client([
'auth' => [$username, $password],
]);
$auth_header = 'Basic '.$username.':'.$password;
$headers = ['Authorization' => $auth_header, 'Content-Type' => 'application/json'];
$json_data = json_encode($vars);
$end_point = 'https://simportal-api.azurewebsites.net/api/v1/';
try {
$x = $client->request($type, $end_point.$url, ['headers' => $headers, 'body' => $json_data]);
$response = array(
'success' => true,
'response' => // SEE ABOVE //
);
} catch (GuzzleHttp\Exception\ClientException $e) {
$response = array(
'success' => false,
'errors' => json_decode($e->getResponse()->getBody(true)),
);
}
return $response;
}
By reading the documentation on https://simportal-api.azurewebsites.net/Help/Api/GET-api-v1-sims_search_skip_take I assume that the server is not accepting your parameters in the body of that GET request and assuming the default of 10, as it is normal in many applications, get requests tend to only use query string parameters.
In that function I'd try to change it in order to send a body in case of a POST/PUT/PATCH request, and a "query" without json_encode in case of a GET/DELETE request. Example from guzzle documentation:
$client->request('GET', 'http://httpbin.org', [
'query' => ['foo' => 'bar']
]);
Source: https://docs.guzzlephp.org/en/stable/quickstart.html#query-string-parameters

Can't work with live model srmklive-paypal

I'm working with srmk/paypal package 1.0.
Been working with this awesome package for some months in sandbox mode, yet I've been struggling to work with live mode.
I've been all over the issues others had and elsewhere and haven't been able to find a solution for this.
If I remove sandbox credentials I get an infinite loop right after dd($response) from $response = $provider->setExpressCheckout($checkoutData);
I'm using 1.0 so ExpressCheckout should not be the problem
I've tested on live server with same results.
My config
return [
'mode' => 'live', // Can only be 'sandbox' Or 'live'. If empty or invalid, 'live' will be used.
'sandbox' => [
'username' => env('PAYPAL_SANDBOX_API_USERNAME', ''),
'password' => env('PAYPAL_SANDBOX_API_PASSWORD', ''),
'secret' => env('PAYPAL_SANDBOX_API_SECRET', ''),
'certificate' => env('PAYPAL_SANDBOX_API_CERTIFICATE', ''),
'app_id' => 'APP-80W284485P519543T', // Used for testing Adaptive Payments API in sandbox mode
],
'live' => [
'username' => env('PAYPAL_LIVE_API_USERNAME', ''),
'password' => env('PAYPAL_LIVE_API_PASSWORD', ''),
'secret' => env('PAYPAL_LIVE_API_SECRET', ''),
'certificate' => env('PAYPAL_LIVE_API_CERTIFICATE', ''),
'app_id' => '', // Used for Adaptive Payments API
],
'payment_action' => 'Sale', // Can only be 'Sale', 'Authorization' or 'Order'
'currency' => env('PAYPAL_CURRENCY', 'MXN'),
'billing_type' => 'MerchantInitiatedBilling',
'notify_url' => '', // Change this accordingly for your application.
'locale' => env('PAYPAL_LOCALE', 'es_ES'), // force gateway language i.e. it_IT, es_ES, en_US ... (for express checkout only)
'validate_ssl' => false, // Validate SSL when creating api client.
];
env and env.example
#PayPal Setting & API Credentials - sandbox
PAYPAL_SANDBOX_API_USERNAME=sb-tr4z02598960_api1.business.example.com
PAYPAL_SANDBOX_API_PASSWORD=VSYUE32AU7MT7VY4
PAYPAL_SANDBOX_API_SECRET=ACdNh.ieqXXfGzIFBkj6F-fUdA49AIBmvpyOyz5MhLCsLyQVdcB74zVJ
PAYPAL_SANDBOX_API_CERTIFICATE=
#PayPal Setting & API Credentials - live
PAYPAL_LIVE_API_USERNAME=********************api1.gmail.com
PAYPAL_LIVE_API_PASSWORD=**********************K9W
PAYPAL_LIVE_API_SECRET=******************************FCBABE
PAYPAL_LIVE_API_CERTIFICATE= storage_path('cert_key_pem.txt'); // also tested empty
I use the new API credentials provided by PayPal
public function getExpressCheckout ($orderId) {
$checkoutData = $this->checkoutData($orderId);
$provider = new ExpressCheckout();
$response = $provider->setExpressCheckout($checkoutData);
dd($response);
return redirect($response['paypal_link']);
}
private function checkoutData($orderId)
{
$cart = \Cart::getContent();
$cart2 = \Cart::getTotal();
$cartItems = array_map( function($item){
return [
'name' => $item['name'],
'price' => $item['price'],
'qty' => $item['quantity']
];
}, $cart->toarray());
$checkoutData = [
'items' => $cartItems,
'return_url' => route('paypal.success', $orderId),
'cancel_url' => route('paypal.cancel'),
'invoice_id' => uniqid(),
'invoice_description' => 'order description',
'total' => $cart2
];
return $checkoutData;
}
public function getExpressCheckoutSuccess(Request $request, $orderId)
{
$token = $request->get('token');
$payerId = $request->get('PayerID');
$provider = new ExpressCheckout();
$checkoutData = $this->checkoutData($orderId);
$response = $provider->getExpressCheckoutDetails($token);
if (in_array(strtoupper($response['ACK']),['SUCCESS','SUCCESSWITHWARNING'])) {
$payment_status = $provider->doExpressCheckoutPayment($checkoutData,$token,$payerId);
$status = $payment_status['PAYMENTINFO_0_PAYMENTSTATUS'];
if (in_array($status, ['Completed','Processed'])) {
$order = Order::find($orderId);
$order->is_paid = 1;
$order->save();
Mail::to($order->buyer_email)->send(new OrderMail($order));
\Cart::clear();
return view ('newOrder.success', compact('order'));
}
The infinite loop pops when calling this function from the package
private function doPayPalRequest($method)
{
// Setup PayPal API Request Payload
$this->createRequestPayload($method);
try {
// Perform PayPal HTTP API request.
$response = $this->makeHttpRequest();
// dd($response); // I'm stuck here
return $this->retrieveData($method, $response);
} catch (Throwable $t) {
$message = collect($t->getTrace())->implode('\n');
}
return [
'type' => 'error',
'message' => $message,
];
}
Thanks all,

In Laravel How to create subscriber in mailchimp using Guzzle HTTP

I am using guzzle HTTP to send the request and I am getting this error
Client error: POST https://us17.api.mailchimp.com/3.0/batches resulted in a 401 Unauthorized response:
{"type":"http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/","title":"API Key Missing","statu (truncated...)
$userArray = [];
$operations = [];
//used to get the patient that need to sync mailchimp
$getPatientToSync = Patient::select('NameFirst', 'NameLast' , 'Email')
->where([['flag_name' , '=', '1'], ['mailchimp_synced' ,'=' , '0']])->get();
if($getPatientToSync->isEmpty()){
return true;
}
foreach ($getPatientToSync as $patient){
$data = array(
"apikey" => config('mailchimp.api_key'),
"email_address" => $patient->Email,
"status" => "subscribed",
"merge_fields" => array(
'FNAME' => $patient->NameFirst,
'LNAME' => $patient->NameLast,
)
);
$userArray[] = json_encode($data);
}
foreach ($userArray as $userArr){
$temp = array(
"method" => "POST",
"path" => "/lists/".config('mailchimp.list_id')."/members/",
"body" => $userArr
);
$operations['operations'][] =$temp;
}
$json_post = json_encode($operations);
$auth = base64_encode( 'user:'.config('mailchimp.api_key') );
//API URL
$urll="https://".config('mailchimp.data_center').".api.mailchimp.com/3.0/batches";
$headers = array('Content-Type: application/json', 'Authorization: Basic
'.$auth , $userlist);
$client = new Client();
$response = $client->request('POST', $urll , $headers,json_post );
dd($response);
First of all, you use Guzzle's request() method in a wrong way. The right way is:
$client->request('POST', $urll, [
'headers' => $headers,
'json' => $operations
]);
Try it and then pay attention to the error message (it'a also useful).

Object of class GuzzleHttp\Psr7\Request could not be converted to string

I've got an issue for laravel 5.4 when I trying to using guzzleHttp. here is my code.
use GuzzleHttp\Client;
$url = 'http://example.com';
$client = new Client();
$parameter = ['query' => ['name' => 'xxx', 'address' => 'yyy'], 'headers' => [ 'User-Agent' => 'xxxx', 'exceptions' => false, 'timeout' => 10 ]];
$res = $client->request('GET', $url, $parameter);
if ($res->getStatusCode() == 200)
{
$json = (string)$res->getBody();
return $json;
}
and I've got this error on log:
Error Exception: Object of class GuzzleHttp\Psr7\Request could not be converted to string
what is wrong with my code? please kindly help me.
fyi, this error not always happen. sometimes it show this error, sometimes success.
thank you
$json = $res->getBody()->getContents();
try this
Try this.....
try {
$parameter = ['query' => ['name' => 'xxx', 'address' => 'yyy'], 'headers' => [ 'User-Agent' => 'xxxx', 'exceptions' => false, 'timeout' => 10 ]];
$res = $client->request('GET', $url, $parameter);
if ($res->getStatusCode() == 200)
{
return $res->getBody()->getContents();
}
}catch(Exception $e){
echo 'Caught exception: ', $e->getMessage();
}
$response = $client->post('http:yanjye.com3', ['phone' => '00','password' => '5555',]);
if ($response->getStatusCode() == 200){
$json = (string)$response->getBody();
return $json;
}
var_dump( $response);
die();
Hello, brother, I think this is the Good way to which is Working On both laravel 5.2[larave 5.2]
i have removed Httm
[laraver 5.2][1]
and use this code :
[1]: https://laravel.com/docs/7.x/http-client`

Categories