set soapclient HTTP_METHOD - php

Im trying to consume a webserivce usnig soapclient.
The instructions for the connection is to use:
request method = "POST";
request ContentType = "application/soap+xml";
This is the code im using to create the client
public function init_client(){
if( $this->env == 'dev'){
$api_url = self::$test_url;
}else{
$api_url = self::$production_url;
}
try{
$options = array(
'soap_version' => SOAP_1_2
);
$this->client = new SoapClient( $api_url , $options );
return true;
}catch(Exception $e){
return $e->getMessage();
}
}
How can i set the client's method and content type ?

Related

Soap body-signing to Envelope header

I have problem with Osuuspankki Webservice. I managed to get Certificate but when i need to get data from Bank there is few problems.
function getArgumentsToDownload($customerid=null,$private_key=null, $public_key=null,$status="NEW",$action=null,$start_date=null,$end_date=null) {
$xml = $this->createDocument();
$ApplicactionRequest = $xml->createElement("ApplicationRequest");
$ApplicactionRequest->setAttribute("xmlns", "http://bxd.fi/xmldata/");
$CustomerId = $xml->createElement("CustomerId",$customerid);
$ApplicactionRequest->appendChild($CustomerId);
$Timestamp = $xml->createElement("Timestamp",date("c"));
$ApplicactionRequest->appendChild($Timestamp);
$Status = $xml->createElement("Status",$status);
$ApplicactionRequest->appendChild($Status);
$Environment = $xml->createElement("Environment",$this->Environment);
$ApplicactionRequest->appendChild($Environment);
$SoftwareId = $xml->createElement("SoftwareId",$this->SoftwareId);
$ApplicactionRequest->appendChild($SoftwareId);
$xml->appendChild($ApplicactionRequest);
$objDSig = new XMLSecurityDSig();
$objDSig->setCanonicalMethod(XMLSecurityDSig::EXC_C14N_COMMENTS);
$objDSig->addReference($xml, XMLSecurityDSig::SHA1, array('http://www.w3.org/2000/09/xmldsig#enveloped-signature'));
$objKey = new XMLSecurityKey(XMLSecurityKey::RSA_SHA1, array('type'=>'private'));
//$objKey->loadKey($private_key,true);
$objKey->loadKey($private_key,true);
$objDSig->sign($objKey);
$objDSig->add509Cert(file_get_contents($public_key),false);
$objDSig->appendSignature($xml->documentElement);
$signed_XML = $xml->saveXML();}
`
I Can sign Env body but it needed to sign again to Env-header.
https://www.op.fi/media/liitteet?cid=151240134&srcpl=4 (page 22/44).
public function getFileList($username=null, $private_key=null, $public_key=null,$status='NEW',$start_date=null, $end_date=null) {
// Alustetaan muuttujat joita käytetään SOAP Clientissä datan lataamisessa Webservicestä.
$arguments = $this->CI->getArgumentsToDownload($username,$private_key,$public_key);
$client = new SoapClient($this->wsdl_test, array('trace' => true, 'exceptions' => false));
// Asetetaan salainen avain
$client->setPrivateKey($private_key);
// Asetetaan julkinen avain
$client->setPublicKey($public_key);
$soap_header = new SoapHeader($this->ws_ns, "Timestamp",array("expires"));
$client->__setSoapHeaders($soap_header);
$return = $client->__soapCall('downloadFileList', array($arguments));
}
What should i do that i get signed Envelope?

Sample PHP code to programmatically check SOAP connection in Magento 2

I tried the below code though I am not sure whether these are the required set of scripts, but it didn't work and gives
SOAP-ERROR: Parsing WSDL: Couldn't load from : Start tag expected, '<' not found
$wsdlUrl = 'http://localhost/magento20_0407/soap/default?wsdl_list=1';
$apiUser = 'testUser';
$apiKey = 'admin123';
$token = 'xioxnuuebn7tlh8ytu7781t14w7ftwmp';
$opts = array('http' => array('method' => "GET", 'header' => "Accept-language: en\r\nConnection: close\r\n"));
$context = stream_context_create($opts);
stream_context_set_option($context, "http", "protocol_version", 1.1);
fpassthru(fopen($wsdlUrl, 'r', false, $context));
$opts = array('http'=>array('header' => 'Authorization: Bearer '.$token));
$serviceArgs = array("id"=>1);
try{
$context = stream_context_create($opts);
$soapClient = new SoapClient($wsdlUrl, array('version' => SOAP_1_2, 'context' => $context));
$soapResponse = $soapClient->customerCustomerAccountServiceV1($serviceArgs);
}catch(Exception $e){
$e->getMessage();
}
var_dump($soapResponse);exit;
Can anyone share the code to make SOAP connection in Magento2.x
In Magento1.x the below code works fine to connect SOAP
$apiUrl = 'http://localhost/magento_28_03/index.php/api/soap?wsdl';
$apiUser = 'testUser';
$apiKey = 'admin123';
ini_set("soap.wsdl_cache_enabled", "0");
try{
$client = new SoapClient($apiUrl, array('cache_wsdl' => WSDL_CACHE_NONE));
} catch (SoapFault $e) {
echo 'Error in Soap Connection : '.$e->getMessage();
}
try {
$session = $client->login($apiUser, $apiKey);
if($session) echo 'SOAP Connection Successful.';
else echo 'SOAP Connection Failed.';
} catch (SoapFault $e) {
echo 'Wrong Soap credentials : '.$e->getMessage();
}
But the above doesn't work for Magento 1. Can anyone say, what changes the above code needs to work fine for Magento 2?
For SOAP API call follow the below
test.php
<?php
$token = 'YOUR_ACCESS_TOKEN';
require('vendor/zendframework/zend-server/src/Client.php');
require('vendor/zendframework/zend-soap/src/Client.php');
require('vendor/zendframework/zend-soap/src/Client/Common.php');
$addArgs = array('num1'=>2, 'num2'=>1);// Get Request
$sumArgs = array('nums'=>array(2,1000));// Post request
//$wsdlUrl = YOUR_BASE_URL."soap?wsdl&services=customerAccountManagementV1,customerCustomerRepositoryV1,alanKentCalculatorWebServiceCalculatorV1";//To declar multiple
$wsdlUrl = YOUR_BASE_URL."soap?wsdl&services=alanKentCalculatorWebServiceCalculatorV1";
try{
$opts = ['http' => ['header' => "Authorization: Bearer " . $token]];
$context = stream_context_create($opts);
$soapClient = new \Zend\Soap\Client($wsdlUrl);
$soapClient->setSoapVersion(SOAP_1_2);
$soapClient->setStreamContext($context);
}catch(Exception $e){
echo 'Error1 : '.$e->getMessage();
}
try{
$soapResponse = $soapClient->alanKentCalculatorWebServiceCalculatorV1Add($addArgs);print_r($soapResponse);
$soapResponse = $soapClient->alanKentCalculatorWebServiceCalculatorV1Sum($sumArgs);print_r($soapResponse);
}catch(Exception $e){
echo 'Error2 : '.$e->getMessage();
}
?>
http://YOUR_BASE_URL/test.php
SOAP-ERROR: Parsing WSDL: Couldn't load from : Start tag expected, '<' not found
Tells you all you need to know; the URL you're trying to load isn't a proper WSDL.
What are the contents of: http://localhost/magento20_0407/soap/default?wsdl_list=1

Setting proxy in Goutte

I've tried using Guzzle's docs to set proxy but it's not working. The official Github page for Goutte is pretty dead so can't find anything there.
Anyone know how to set a proxy?
This is what I've tried:
$client = new Client();
$client->setHeader('User-Agent', $user_agent);
$crawler = $client->request('GET', $request, ['proxy' => $proxy]);
I have solved this problem =>
$url = 'https://api.myip.com';
$client = new \Goutte\Client;
$client->setClient(new \GuzzleHttp\Client(['proxy' => 'http://xx.xx.xx.xx:8080']));
$get_html = $client->request('GET', $url)->html();
var_dump($get_html);
You thinking rigth, but in Goutte\Client::doRequest(), when create Guzzle client
$guzzleRequest = $this->getClient()->createRequest(
$request->getMethod(),
$request->getUri(),
$headers,
$body
);
options are not passed when create request object. So, if you want to use a proxy, then override the class Goutte\Client, the method doRequest(), and replace this code on
$guzzleRequest = $this->getClient()->createRequest(
$request->getMethod(),
$request->getUri(),
$headers,
$body,
$request->getParameters()
);
Example overriding class:
<?php
namespace igancev\override;
class Client extends \Goutte\Client
{
protected function doRequest($request)
{
$headers = array();
foreach ($request->getServer() as $key => $val) {
$key = implode('-', array_map('ucfirst', explode('-', strtolower(str_replace(array('_', 'HTTP-'), array('-', ''), $key)))));
if (!isset($headers[$key])) {
$headers[$key] = $val;
}
}
$body = null;
if (!in_array($request->getMethod(), array('GET','HEAD'))) {
if (null !== $request->getContent()) {
$body = $request->getContent();
} else {
$body = $request->getParameters();
}
}
$guzzleRequest = $this->getClient()->createRequest(
$request->getMethod(),
$request->getUri(),
$headers,
$body,
$request->getParameters()
);
foreach ($this->headers as $name => $value) {
$guzzleRequest->setHeader($name, $value);
}
if ($this->auth !== null) {
$guzzleRequest->setAuth(
$this->auth['user'],
$this->auth['password'],
$this->auth['type']
);
}
foreach ($this->getCookieJar()->allRawValues($request->getUri()) as $name => $value) {
$guzzleRequest->addCookie($name, $value);
}
if ('POST' == $request->getMethod() || 'PUT' == $request->getMethod()) {
$this->addPostFiles($guzzleRequest, $request->getFiles());
}
$guzzleRequest->getParams()->set('redirect.disable', true);
$curlOptions = $guzzleRequest->getCurlOptions();
if (!$curlOptions->hasKey(CURLOPT_TIMEOUT)) {
$curlOptions->set(CURLOPT_TIMEOUT, 30);
}
// Let BrowserKit handle redirects
try {
$response = $guzzleRequest->send();
} catch (CurlException $e) {
if (!strpos($e->getMessage(), 'redirects')) {
throw $e;
}
$response = $e->getResponse();
} catch (BadResponseException $e) {
$response = $e->getResponse();
}
return $this->createResponse($response);
}
}
And try send request
$client = new \igancev\override\Client();
$proxy = 'http://149.56.85.17:8080'; // free proxy example
$crawler = $client->request('GET', $request, ['proxy' => $proxy]);
You can directly use in Goutte or Guzzle Request
$proxy = 'xx.xx.xx.xx:xxxx';
$goutte = new GoutteClient();
echo $goutte->request('GET', 'https://example.com/', ['proxy' => $proxy])->html();
Use Same method in Guzzle
$Guzzle = new Client();
$GuzzleResponse = $Guzzle->request('GET', 'https://example.com/', ['proxy' => $proxy]);
You can set a custom GuzzleClient and assign it to Goutte client.
When Guzzle makes the request through Goutte uses the default config. That config is passed in the Guzzle construct.
$guzzle = new \GuzzleHttp\Client(['proxy' => 'http://192.168.1.1:8080']);
$goutte = new \Goutte\Client();
$goutte->setClient($guzzle);
$crawler = $goutte->request($method, $url);
For recent versions use:
Goutte Client instance (which extends Symfony\Component\BrowserKit\HttpBrowser)
use Symfony\Component\HttpClient\HttpClient;
use Goutte\Client;
$client = new Client(HttpClient::create(['proxy' => 'http://xx.xx.xx.xx:80']));
...

Trouble creating web service with PHP NuSOAP

I'm trying to set up a simple web service but I'm having trouble. The service seems to be available, but I can't seem to return a response. Var_dump on $client shows a connection to the web service, but nothing comes back in response. No errors are caught either.
Any help would be greatly appreciated.
server.php
<?php
require_once ("lib/nusoap.php");
$URL = "https://www.domain.com";
$namespace = $URL . '?wsdl';
$server = new soap_server;
$server->debug_flag = false;
$server->configureWSDL('Test', $namespace);
$server->wsdl->schemaTargetNamespace = $namespace;
function get_message($your_name)
{
if(!$your_name)
{
return new soap_fault('Client','','Put Your Name!');
}
$result = "Welcome to ".$your_name .". Thanks for Your First Web Service Using PHP with SOAP";
return $result;
}
$server->register('get_message');
// create HTTP listener
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
exit();
?>
client.php
<?php
$wsdl = "https://www.domain.com/webservice/server.php?wsdl";
require_once ('lib/nusoap.php');
$param = array("your_name" => "Liam");
$client = new SoapClient($wsdl, array("trace" => true));
$response = $client->get_message($param);
if($client->fault)
{
echo "FAULT: <p>Code: (".$client->faultcode."</p>";
echo "String: ".$client->faultstring;
}
else
{
echo $response;
}
?>
There were bugs in the code of client and server files, I have updated the code
server.php
<?php
require_once ("lib/nusoap.php");
$URL = "http://www.domian.com/server.php";
$namespace = $URL . '?wsdl';
$server = new soap_server(); //added ()
$server->debug_flag = false;
$server->configureWSDL('Test', $namespace);
//$server->wsdl->schemaTargetNamespace = $namespace;
function get_message($your_name)
{
if(!$your_name)
{
return new soap_fault('Client','','Put Your Name!');
}
$result = "Welcome to ".$your_name .". Thanks for Your First Web Service Using PHP with SOAP";
return $result;
}
$server->register('get_message',
array('request' => 'xsd:ArrayReq'), // ArrayReq is type for your parameters
array('return' => 'xsd:String'),
'urn:Test',
'urn:Test#get_message',
'rpc',
'encoded',
'show message'); // added request return array
// create HTTP listener
//$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service(file_get_contents('php://input'));
exit();
?>
Client.php
<?php
$wsdl = "http://www.domian.com/server.php?wsdl";
require_once ('lib/nusoap.php');
$param = array("your_name" => "Liam");
$client = new nusoap_client($wsdl); // user nusoap_client() for creating client object
//$client = new SoapClient($wsdl, array("trace" => true));
$response = $client->call('get_message', $param); // use call() to call the server functions
if($client->fault)
{
echo "FAULT: <p>Code: (".$client->faultcode."</p>";
echo "String: ".$client->faultstring;
}
else
{
echo $response;
}
?>
it's working!

How to POST via Reddit API (addcomment)

I've been able to successfully log a user in and return their details. The next step is to get them to post a comment via my app.
I tried modifying code from the reddit-php-sdk -- https://github.com/jcleblanc/reddit-php-sdk/blob/master/reddit.php -- but I can't get it to work.
My code is as follows:
function addComment($name, $text, $token){
$response = null;
if ($name && $text){
$urlComment = "https://ssl.reddit.com/api/comment";
$postData = sprintf("thing_id=%s&text=%s",
$name,
$text);
$response = runCurl($urlComment, $token, $postData);
}
return $response;
}
function runCurl($url, $token, $postVals = null, $headers = null, $auth = false){
$ch = curl_init($url);
$auth_mode = 'oauth';
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_TIMEOUT => 10
);
$headers = array("Authorization: Bearer {$token}");
$options[CURLOPT_HEADER] = false;
$options[CURLINFO_HEADER_OUT] = false;
$options[CURLOPT_HTTPHEADER] = $headers;
if (!empty($_SERVER['HTTP_USER_AGENT'])){
$options[CURLOPT_USERAGENT] = $_SERVER['HTTP_USER_AGENT'];
}
if ($postVals != null){
$options[CURLOPT_POSTFIELDS] = $postVals;
$options[CURLOPT_CUSTOMREQUEST] = "POST";
}
curl_setopt_array($ch, $options);
$apiResponse = curl_exec($ch);
$response = json_decode($apiResponse);
//check if non-valid JSON is returned
if ($error = json_last_error()){
$response = $apiResponse;
}
curl_close($ch);
return $response;
}
$thing_id = 't2_'; // Not the actual thing id
$perma_id = '2daoej'; // Not the actual perma id
$name = $thing_id . $perma_id;
$text = "test text";
$reddit_access_token = $_SESSION['reddit_access_token'] // This is set after login
addComment($name, $text, $reddit_access_token);
The addComment function puts the comment together according to their API -- http://www.reddit.com/dev/api
addComment then calls runCurl to make the request. My guess is that the curl request is messed up because I'm not receiving any response whatsoever. I'm not getting any errors so I'm not sure what's going wrong. Any help would really be appreciated. Thanks!
If you are using your own oAuth solution, I would suggest using the SDK as I said in my comment, but extend it to overwrite the construct method.
class MyReddit extends reddit {
public function __construct()
{
//set API endpoint
$this->apiHost = ENDPOINT_OAUTH;
}
public function setAuthVars($accessToken, $tokenType)
{
$this->access_token = $accessToken;
$this->token_type = $tokenType;
//set auth mode for requests
$this->auth_mode = 'oauth';
}
}
You just need to make sure that you call setAuthVars before running any api calls.

Categories