How to consume 3rd Party wsdl in magento2 - soap

I need to fetch Customer Information from a third party http://91.209.142.215:2803/SXYMAGENTO/?wsdl. I can connect it using SOAPUI and get desired response, but I am not able to connect it via Magento2. So far I tried
$requestData = [
'pageSize' => 1,
'pageNumber' => 1
];
$webservice_url = 'http://xx.xxx.xxx.xx:xxxx/MAGENTO/?wsdl';
$token = 'm31oix12hh6dfthmfmgk7j5k5dpg8mel';
$opts = array(
'http'=>array(
'header' => 'Authorization: Bearer '.$token)
);
$context = stream_context_create($opts);
$soapClient = new \SoapClient($webservice_url, ['version' => SOAP_1_2, 'context' => $context]);
$collection = $soapClient->RetrieveCollection($requestData);
print_r($collection);
die();
but this outputs Product data(maybe this is set as default), not customer data. Can anyone please point me in the right direction?

Finally, I figure this out and posting the answer so that it may help anyone craving a solution or fighting with a deadline.
Extend SoapClient and you can change Action, Request, and location
namespace Namespace\SoapModule\Api;
class CustomSoap extends \SoapClient
{
public function __doRequest($request, $location, $action, $version, $one_way = 0)
{
$action = 'Your/Action/Obtainedfrom/SOAPAction';
$this->__last_request = $request; //Optional. You should do this if you dont want to get confused when print $request somewhere else in the module
return parent::__doRequest($request, $location, $action, $version, $one_way);
}
}
construct an object of above class wherever required
public function getCustomersDetails($page_size, $page_number)
{
$requestData = [
'pageSize' => $page_size,
'pageNumber' => $page_number
];
$data = $this->client->__soapCall('RetrieveCollection', [$requestData]);
return $this->client->__getLastResponse();
}
public function statementBalance()
{
$responsexml = $this->getCustomersDetails(1, 1);
$xml = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $responsexml);
#$xml = simplexml_load_string($xml);
$json = json_encode($xml);
$responseArray = json_decode($json, true);
echo '<pre>';
print_r($responseArray);
}
Happy coding!

Related

Slim 3: How to access user information from request headers

I am using Slim 3.1 and able to authenticate correctly i.e. able to generate the token and use it for another POST request. Now I want to parse the request header to extract the user information so I can identify which user have sent the request.
Here is my code to get the token.
$app->post('/login/token', function (Request $request, Response $response,
array $args) {
$input = $request->getParsedBody();
$now = new DateTime();
$future = new DateTime("+10 minutes");
$server = $request->getServerParams();
$jti = (new Base62)->encode(random_bytes(16));
$payload = [
"iat" => $now->getTimeStamp(),
"exp" => $future->getTimeStamp(),
"jti" => $jti,
"sub" => $input['username']
];
$sql = "SELECT * FROM user WHERE User_Name= :username";
$sth = $this->db->prepare($sql);
$sth->bindParam("username", $input['username']);
$sth->execute();
$user = $sth->fetchObject();
// verify email address.
if(!$user) {
return $this->response->withJson(['error' => true, 'message' => 'These credentials do not match our records.']);
}
// verify password.
if (!password_verify($input['password'],$user->User_Password)) {
return $this->response->withJson(['error' => true, 'message' => 'These credentials do not match our records.']);
}
$settings = $this->get('settings'); // get settings array.
//$token = JWT::encode(['User_ID' => $user->User_ID, 'username' => $user->User_Name], $settings['jwt']['secret'], "HS256");
$token = JWT::encode($payload, $settings['jwt']['secret'], "HS256");
return $this->response->withJson(['token' => $token, 'ACL' => $user->User_ACL]);
});
This returns me a token that I send in the following POST request
$app->group('/api', function(\Slim\App $app) {
$app->post('/createuser', function (Request $request, Response $response,
array $args) {
$headerValueArray = $request->getHeader('HTTP_AUTHORIZATION');
return $this->response->withJson(['success' => true, $token]);
});
});
The above POST request gives the following output
{
"success": true,
"0": ["Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1MzU4Mjk0OTUsImV4cCI6MTUzNTgzNjY5NSwianRpIjoiMWc5ZFM3dUNLbzl1blRQZzBmYjU2diIsInN1YiI6InN5c2FkbWluIn0.vo3FBPhBkhfA2y7AG-afmjfeEhygIYY7lIaaVNX5i5k"]
}
I need to parse this token to extract the user information to see if its the valid user to perform this operation.In other words, how I can decode the above token.
Any help here will be much appreciated!

How to Retrieve HTTP Status Code with Guzzle?

New to Guzzle/Http.
I have a API rest url login that answer with 401 code if not authorized, or 400 if missing values.
I would get the http status code to check if there is some issues, but cannot have only the code (integer or string).
This is my piece of code, I did use instruction here ( http://docs.guzzlephp.org/en/stable/quickstart.html#exceptions )
namespace controllers;
use GuzzleHttp\Psr7;
use GuzzleHttp\Exception\ClientException;
$client = new \GuzzleHttp\Client();
$url = $this->getBaseDomain().'/api/v1/login';
try {
$res = $client->request('POST', $url, [
'form_params' => [
'username' => 'abc',
'password' => '123'
]
]);
} catch (ClientException $e) {
//echo Psr7\str($e->getRequest());
echo Psr7\str($e->getResponse());
}
You can use the getStatusCode function.
$response = $client->request('GET', $url);
$statusCode = $response->getStatusCode();
Note: If your URL redirects to some other URL then you need to set false value for allow_redirects property to be able to detect initial status code for parent URL.
// On client creation
$client = new GuzzleHttp\Client([
'allow_redirects' => false
]);
// Using with request function
$client->request('GET', '/url/with/redirect', ['allow_redirects' => false]);
If you want to check status code in catch block, then you need to use $exception->getCode()
More about responses
More about allow_redirects
you can also use this code :
$client = new \GuzzleHttp\Client(['base_uri' 'http://...', 'http_errors' => false]);
hope help you

Facebook Php API: RSVP users to public event

I'm trying to use the facebook php api to rsvp users to a public event.
So far I can only get it to work for users who have already been invited.
I've tried:
$path = $event_id.'/attending';
$method = 'POST';
try
{
$this->facebook->api($path, $method);
}
catch(FacebookApiException $e){}
Which does nothing.
My code as it stands is:
function rsvpEvent($event_id)
{
$fb_config = array(
'appId' => APP_ID,
'secret' => APP_SECRET,
'cookie' => true,
);
$this->load->library('facebook', $fb_config);
$me = $this->facebook->api('/me/');
$user_id = $me['id'];
$path = $event_id.'/invited/'.$user_id;
$status = $this->facebook->api($path, 'GET');
$status = $status['data'][0]['rsvp_status'];
if($status === 'not_replied')
{
$path = $event_id.'/attending';
$method = 'POST';
try
{
$this->facebook->api($path, $method);
}
catch(FacebookApiException $e){}
}
}
Has anyone got any ideas how I can get this to work?
$path = $event_id.'/attending?access_token='.$SOME_ACCESS_TOKEN;
You're not using the access token in your code, so I am uncertain of whether you skipped it when you copied it, If it's not in the code, then it may be that.
I retrieved the information here

The server don't receive a Response / SendRequests

Iam new guy for Zend2 framework...I got an error which I didnt trace it...
Iam writing a controller named 'usertask' and in that fir index function i wrote the code like this
public function indexAction()
{
$sendRequest = new SendRequests;
$tableGrid = new DynamicTable();
$prop = array(
'customRequest' => 'GET',
'headerInformation' => array('environment: development', 'token_secret: abc')
);
$returnRequest = $sendRequest->set($prop)->requests('http://service-api/usertask');
$returnData = json_decode($returnRequest['return'],true);
$tableGrid->tableArray = $returnData['result'];
$dynamicTable = $tableGrid->tableGenerate();
$view = new ViewModel(array(
'usertask' => $dynamicTable
));
//print_r($view);exit;
return $view;
}
but it is not listing my usertasks...while Iam printing $returnRequest its giving me error message like
The server don't receive a Response / SendRequests
what it the mistake in my code...could anyone suggest me...please..iam using "zend2"
Sorry guys I found my mistake ...I got big code but I need something like
public function indexAction()
{
$view = new ViewModel(array(
'usertask' => $this->UserTable()->fetchall(),
));
return $view;
}
public function getUserTable()
{
if (!$this->userTable) {
$sm = $this->getServiceLocator();
$this->userTable = $sm->get('User\Model\UserTable');
}
return $this->userTable;
}
that's it...i got it as a list of users

sugarcrm retrieve accounts list in a web page using webservice

I would like to retrieve all accounts datas and contact datas in Sugarcrm database using webservice .
I would like it to show it in a webpage .
How can i go about it?
Modify the below code to your requirements. It uses the SOAP API of SugarCRM.
$user_name = 'admin';
$user_password = 'admin';
$sugarcrm_url = 'http://example.com/'
$options = array(
"uri" => $sugarcrm_url,
"trace" => true
);
$offset = 0;
$limit = 100;
try {
$client = new SoapClient($sugarcrm_url.'service/v4_1/soap.php?wsdl', $options);
$response = $client->__soapCall('login',array(
'user_auth'=>array(
'user_name'=>$user_name,
'password'=>md5($user_password),
'version'=>'.01'
),
'application_name'=>'SoapTest'
));
$session_id = $response->id;
$response = $client->__soapCall('get_entry_list',array(
'session'=>$session_id,
'module_name'=>'Contacts',
'query'=>'',
'order_by'=>'contacts.last_name asc',
'offset'=>$offset,
'select_fields'=>array(),
'max_results'=>$limit)
);
print_r($response);
$response = $client->__soapCall('get_entry_list',array(
'session'=>$session_id,
'module_name'=>'Accounts',
'query'=>'',
'order_by'=>'accounts.name asc',
'offset'=>$offset,
'select_fields'=>array('id', 'name', 'email1'),
'max_results'=>$limit)
);
print_r($response);
$response = $client->__soapCall('logout',array('session'=>$session_id));
} catch (Exception $ex) {
echo $ex->getMessage();
}