I have a WCF web service hosted on IIS. It can be called through .net with no problem. but when I try to call it via PHP I get This error
object(SoapFault)#5 "Cannot process the message because the content type 'application/soap+xml; charset=utf-8; action="web service URL"' was not the expected type 'text/xml; charset=utf-8'.
Here is my code
<?php
$X = new X ([
'Card' => '53535',
'Terminal' => '43534534',
'Amount' => '1000',
'OrderId' => '1',
'ReturnUrl' => 'test url',
'Password' => 'D414305754BE7625CA70D',
'MobileNo' => '03003030',
'AdditionalData' => 'test' ]);
$request_key = $X ->request(2, 1000, 'http://');
class WebServicePaymentRequest
{
public $Card = "53535";
public $Terminal = "43534534";
public $Amount = "1000";
public $OrderId = "1";
public $ReturnUrl = "test url";
public $Password = "D414305754BE7625CA70D";
public $MobileNo = "03003030";
}
class X {
private $Card;
private $Terminal;
private $Amount;
private $OrderId;
private $ReturnUrl;
private $Password;
private $MobileNo;
private $AdditionalData;
private $Token;
private $wsdl_url = 'https://XXX/WebServices/PaymentUtils.svc?wsdl';
public function __construct($params)
{
$this->Card = $params['Card'];
$this->Terminal = $params['Terminal'];
$this->Password = $params['Password'];
$this->Amount = $params['Amount'];
$this->OrderId = $params['OrderId'];
$this->ReturnUrl = $params['ReturnUrl'];
$this->MobileNo = $params['MobileNo'];
$this->AdditionalData = $params['AdditionalData'];
}
public function request($order_id, $amount, $callback)
{
$options = array(
"soap_version" => SOAP_1_2,
"cache_wsdl" => WSDL_CACHE_NONE,
"exceptions" => false,
"encoding"=> 'UTF-8'
);
$client = new SoapClient($this->wsdl_url, $options);
$obj = new WebServicePaymentRequest;
$obj->Amount = $amount; // Output the property
$obj->OrderId = $order_id;
$obj->ReturnUrl = $callback;
$result = $client->PaymentRequest($obj);
echo $result;
var_dump($result);
$result = json_decode($result, true);
$this->Token = $result['Token'];
}
}
?>
I tried every solution in stackoverflow and other websites. but it did not work .
Thanks in Advance...
I found out that Soapclient does not support WCF in PHP .I solved the problem by Posting Xml as Body with SoapAction header to The Url. I used SoapUi to get the Xml , and then postman to get the result.
Related
We have several GPS installed in different units and I am trying to retrieve the messages using the Wialon's Remote API but i am getting this error, can someone please help me? Thanks a lot!:
{"error":4, "reason":"VALIDATE_PARAMS_ERROR: {itemId: long, timeFrom: uint, timeTo: uint, flags: uint, flagsMask: uint, loadCount: uint}"}
Below is my script:
<?php
include('wialon.php');
$wialon_api = new Wialon();
$token = '{token here}';
$result = $wialon_api->login($token);
$json = json_decode($result, true);
if(!isset($json['error'])){
echo $wialon_api->messages_load_interval('{"itemId":24611387,"lastTime":1073741831,"lastCount":1,"flags":0,"flagMask":0,"loadCount":1}');
$wialon_api->logout();
} else {
echo WialonError::error($json['error']);
}
?>
Here is the Wialon Class which i downloaded from their site:
<?php
/* Classes for working with Wialon RemoteApi using PHP
*
* License:
* The MIT License (MIT)
*
* Copyright:
* 2002-2015 Gurtam, http://gurtam.com
*/
/** Wialon RemoteApi wrapper Class
*/
class Wialon{
/// PROPERTIES
private $sid = null;
private $base_api_url = '';
private $default_params = array();
/// METHODS
/** constructor */
function __construct($scheme = 'https', $host = 'hst-api.wialon.com', $port = '', $sid = '', $extra_params = array()) {
$this->sid = '';
$this->default_params = array_replace(array(), (array)$extra_params);
$this->base_api_url = sprintf('%s://%s%s/wialon/ajax.html?', $scheme, $host, mb_strlen($port)>0?':'.$port:'');
}
/** sid setter */
function set_sid($sid){
$this->sid = $sid;
}
/** sid getter */
function get_sid(){
return $this->sid;
}
/** update extra parameters */
public function update_extra_params($extra_params){
$this->default_params = array_replace($this->default_params, $extra_params);
}
/** RemoteAPI request performer
* action - RemoteAPI command name
* args - JSON string with request parameters
*/
public function call($action, $args){
$url = $this->base_api_url;
if (stripos($action, 'unit_group') === 0) {
$svc = $action;
$svc[mb_strlen('unit_group')] = '/';
} else {
$svc = preg_replace('\'_\'', '/', $action, 1);
}
$params = array(
'svc'=> $svc,
'params'=> $args,
'sid'=> $this->sid
);
$all_params = array_replace($this->default_params , $params);
$str = '';
foreach ($all_params as $k => $v) {
if(mb_strlen($str)>0)
$str .= '&';
$str .= $k.'='.urlencode(is_object($v) || is_array($v) ? json_encode($v) : $v);
}
/* cUrl magic */
$ch = curl_init();
$options = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $str
);
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
if($result === FALSE)
$result = '{"error":-1,"message":'.curl_error($ch).'}';
curl_close($ch);
return $result;
}
/** Login
* user - wialon username
* password - password
* return - server response
*/
public function login($token) {
$data = array(
'token' => urlencode($token),
);
$result = $this->token_login(json_encode($data));
$json_result = json_decode($result, true);
if(isset($json_result['eid'])) {
$this->sid = $json_result['eid'];
}
return $result;
}
/** Logout
* return - server responce
*/
public function logout() {
$result = $this->core_logout();
$json_result = json_decode($result, true);
if($json_result && $json_result['error']==0)
$this->sid = '';
return $result;
}
/** Unknonwn methods hadler */
public function __call($name, $args) {
return $this->call($name, count($args) === 0 ? '{}' : $args[0]);
}
}
/** Wialon errorCode to textMessage converter
*/
class WialonError{
/// PROPERTIES
/** list of error messages with codes */
public static $errors = array(
1 => 'Invalid session',
2 => 'Invalid service',
3 => 'Invalid result',
4 => 'Invalid input',
5 => 'Error performing request',
6 => 'Unknow error',
7 => 'Access denied',
8 => 'Invalid user name or password',
9 => 'Authorization server is unavailable, please try again later',
1001 => 'No message for selected interval',
1002 => 'Item with such unique property already exists',
1003 => 'Only one request of given time is allowed at the moment'
);
/// METHODS
/** error message generator */
public static function error($code = '', $text = ''){
$code = intval($code);
if ( isset(self::$errors[$code]) )
$text = self::$errors[$code].' '.$text;
$message = sprintf('%d: %s', $code, $text);
return sprintf('WialonError( %s )', $message);
}
}
?>
I am trying to pull data from API, and getting this error. I have searched same file_get_contents(): php_network_getaddresses: getaddrinfo failed: Name or service not known
but did't understand how to fix
file_get_contents(): php_network_getaddresses: getaddrinfo failed:
Name or service not known
Here is my code
<?php namespace AdClass;
use stdClass;
class AdInfo{
private $domain;
private $widget_id;
private $api_key;
private $pub_id;
public function __construct($domain, $widget_id, $api_key, $pub_id)
{
$this->domain = $domain;
$this->widget_id = $widget_id;
$this->api_key = $api_key;
$this->pub_id = $pub_id;
}
public function getDomain()
{
return $this->domain;
}
public function getWidgetId()
{
return $this->widget_id;
}
public function getApiKey()
{
return $this->api_key;
}
public function getPubId()
{
return $this->pub_id;
}
public function getAdContent()
{
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://api.revcontent.com/api/v1',
CURLOPT_USERAGENT => 'Codular Sample cURL Request',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array(
'api_key' => $this->api_key,
'pub_id' => $this->pub_id,
'widget_id' => $this->widget_id,
'domain' => $this->domain,
'format' => 'json',
'sponsored_offset' => '0',
'internal_count' => '3',
'internal_offset' => '2'
)
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
return $resp;
}
}
?>
index.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include(dirname(__FILE__).'/AdClass/AdInfo.php');
$domain = "realtimepolitics.com";
$widget_id = XXXX;
$api_key = "XXXXXX";
$pub_id = XXXX;
$adobj = new AdClass\AdInfo($domain, $widget_id, $api_key, $pub_id);
$response = $adobj->getAdContent();
echo "<pre>";
print_r($response);
Issue Fixed with cURL request:
<?php namespace AdClass;
use stdClass;
class AdInfo{
private $domain;
private $widget_id;
private $api_key;
private $pub_id;
private $sponsored_offset;
private $sponsored_count;
private $internal_offset;
private $internal_count;
public function __construct($domain,$widget_id,$sponsored_count=1,$internal_offset=1, $sponsored_offset=0,$internal_count=3)
{
$this->domain = $domain;
$this->widget_id = $widget_id;
$this->api_key = "XXXX";
$this->pub_id = xxxx;
$this->sponsored_offset =$sponsored_offset;
$this->sponsored_count = $sponsored_count;
$this->internal_offset = $internal_offset;
$this->internal_count = $internal_count;
}
public function getAdContent()
{
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://trends.revcontent.com/api/v1/?api_key='.$this->api_key.'&pub_id='.$this->pub_id.'&widget_id='.$this->widget_id.'&domain='.$this->domain.'&format=json&sponsored_count='.$this->sponsored_count.'&sponsored_offset='.$this->sponsored_offset.'&internal_count='.$this->internal_count.'&internal_offset='.$this->internal_offset ,
CURLOPT_USERAGENT => 'cURL Request'
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
return $resp;
}
}
?>
Main.php
<?php namespace MainApi;
include(dirname(__FILE__).'/../AdClass/AdInfo.php');
use AdClass\AdInfo;
class Main{
private $adObj;
public function __construct($domain,$widget_id,$sponsored_count,$internal_offset, $sponsored_offset,$internal_count)
{
$this->domain = $domain;
$this->widget_id = $widget_id;
$this->sponsored_offset =$sponsored_offset;
$this->sponsored_count = $sponsored_count;
$this->internal_offset = $internal_offset;
$this->internal_count = $internal_count;
$this->adObj = new AdInfo($this->domain,$this->widget_id,$this->sponsored_count,$this->internal_offset, $this->sponsored_offset,$this->internal_count);
}
function getResponse()
{
$response = $this->adObj->getAdContent();
return $response;
}
}
getAds.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include (dirname(__FILE__) . '/MainApi/Main.php');
$domain = "realtimepolitics.com";
$widget_id = $_GET['widget_id']; //97862
$weight = $_GET['w'];
$height = $_GET['h'];
$sponsored_count = 2;
$internal_offset = 2;
$sponsored_offset = 0;
$internal_count = 3;
$main = new MainApi\Main($domain, $widget_id, $sponsored_count, $internal_offset, $sponsored_offset, $internal_count);
$response = $main->getResponse();
$ads_data = json_decode($response);
print_r($ads_data);
Can someone please help. I am getting a fatal error on the following PHP script.
I am getting an error "unidentified method Pass::_createpass()" whick relates to the second last line of the code below.
<?php
$engine = Pass::start('xxxxxxxxxxxxxxxx');
$pass = $engine->createPassFromTemplate(xxxxxxxxxxxxxx);
$engine->redirectToPass($pass);
if (!function_exists('curl_init')) {
throw new Exception('Pass needs the CURL PHP extension.');
}
if (!function_exists('json_decode')) {
throw new Exception('Pass needs the JSON PHP extension.');
}
$engine = Pass::start($appKey);
$values = array(
'first' => 'John',
'last' => 'Platinum',
);
$images = array(
'thumbnail' => 'image1.jpg'
);
$pass = $engine->createPassFromTemplate(5688667418918912, $values, $images);
$passData = $engine->downloadPass($pass);
$engine->redirectToPass($pass);
class Pass
{
private $_appKey = null;
private $_endpoint = 'https://pass.center/api/v1';
private $_debug = false;
private static $_instance = null;
private static $_imageTypes = array('icon', 'logo', 'strip', 'thumbnail', 'background', 'footer');
const VERSION = '0.5';
const USER_AGENT = 'PassSDK-PHP/0.5';
public function __construct($appKey = null, $endpoint = null, $debug = false)
{
if (is_null($appKey)) {
throw new Exception('App Key required');
}
$this->_appKey = $appKey;
if ($endpoint !== null) {
$this->_endpoint = $endpoint;
}
$this->_debug = $debug;
}
public static function start($appKey = null, $endpoint = null, $debug = false)
{
if (self::$_instance == null) {
self::$_instance = new self($appKey, $endpoint, $debug);
}
return self::$_instance;
}
public function createPassFromTemplate($templateId, $values = array(), $images = array())
{
$resource = sprintf("https://xxxxxxx/api/v1/templates/names/Test/pass", $templateId);
return $this->_createPass($resource, $values, $images);
}
}
I hope someone can help me as I am not familiar with Functions PHP.
Thanks All
Rob
The function createPass is missing.
You need something like this:
/**
* Prepares the values and image for the pass and creates it
*
* #param string $resource Resource URL for the pass creation
* #param array $values Values
* #param array $images Images
* #return object Pass
*/
private function _createPass($resource, $values, $images)
{
$multipart = count($images) > 0;
if ($multipart) {
$content = array();
foreach ($images as $imageType => $image) {
$this->_addImage($image, $imageType, $content, $imageType);
}
var_dump($content);
// Write json to file for curl
$jsonPath = array_search('uri', #array_flip(stream_get_meta_data(tmpfile())));
file_put_contents($jsonPath, json_encode($values));
$content['values'] = sprintf('#%s;type=application/json', $jsonPath);
} else {
$content = $values;
}
return $this->_restCall('POST', $resource, $content, $multipart);
}
..And full script here
Found this handy little script that uses Curl and PHP to use the Wordpress XML-RPC function to post directly to my Wordpress blog. I think I have figured out where to enter most information, but there are two values I just can't figure out (not with any amount of Google searching either - so far).
Below I put the entire script, which others may use - provided by http://blog.artooro.com/2012/09/03/wordpress-api-xml-rpc-new-easy-to-use-php-class/
The two values I can't figure out are "ch" and "execute". Not sure if this is a Curl value or a PHP value.
class WordPress {
private $username;
private $password;
private $endpoint;
private $blogid;
private $ch;
public function __construct($username, $password, $endpoint, $blogid = 1) {
$this->myusername = $username;
$this->mypassword = $password;
$this->my-site.com/xmlrpc.php = $endpoint;
$this->1 = $blogid;
$this->ch = curl_init($this->my-site.com/xmlrpc.php);
curl_setopt($this->ch, CURLOPT_HEADER, false);
curl_setopt($this->ch, CURLOPT_HTTPHEADER, array("Content-Type: text/xml"));
}
private function execute($request) {
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $request);
$response = curl_exec($this->ch);
$result = xmlrpc_decode($response);
if (is_array($result) && xmlrpc_is_fault($result)) {
throw new Exception($result['faultString'], $result['faultCode']);
}
else {
return $result;
}
}
public function publish_post($title, $content, array $tags, array $categories, $status = 'publish', $date = Null) {
// Set datetime for post
if ($date == Null) {
$post_date = date("Ymd\TH:i:s", time());
}
else {
$post_date = $date;
}
xmlrpc_set_type($post_date, 'datetime');
$params = array(
$this->id,
$this->myusername,
$this->mypassword,
array(
'post_type' => 'post',
'post_status' => $status,
'post_title' => $title,
'post_content' => $content,
'post_date' => $post_date,
'terms_names' => array('category' => $categories, 'post_tag' => $tags)
)
);
$request = xmlrpc_encode_request('wp.newPost', $params);
$response = $this->execute($request);
return $response;
}
}
$this->ch = Curl Handle, its the property that will hold the curl request handle. Its private as it will not be used outside of the class.
$this->execute() = Is the class method that will execute the curl request and return the result. Its private as it will not be used outside of the class.
Both are part of the class and not part of PHP internals.
Also:
I see a couple of problems with the code provided:
$this->my-site.com/xmlrpc.php = $endpoint; should be
$this->endpoint = $endpoint;
$this->1 = $blogid; should be $this->blogid = $blogid;
Plus change references to them properties within the publish_post() method.
Fixed code:
<?php
/*Usage:*/
$wordpress = new WordPress($username, $password, 'my-site.com/xmlrpc.php', 1);
$wordpress->publish_post(...);
class WordPress {
private $username;
private $password;
private $endpoint;
private $blogid;
private $ch;
public function __construct($username, $password, $endpoint, $blogid = 1) {
$this->myusername = $username;
$this->mypassword = $password;
$this->endpoint = $endpoint;
$this->blogid = $blogid;
$this->ch = curl_init($this->endpoint);
curl_setopt($this->ch, CURLOPT_HEADER, false);
curl_setopt($this->ch, CURLOPT_HTTPHEADER, array("Content-Type: text/xml"));
}
private function execute($request) {
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $request);
$response = curl_exec($this->ch);
$result = xmlrpc_decode($response);
if (is_array($result) && xmlrpc_is_fault($result)) {
throw new Exception($result['faultString'], $result['faultCode']);
}
else {
return $result;
}
}
public function publish_post($title, $content, array $tags, array $categories, $status = 'publish', $date = Null) {
// Set datetime for post
if ($date == Null) {
$post_date = date("Ymd\TH:i:s", time());
}
else {
$post_date = $date;
}
xmlrpc_set_type($post_date, 'datetime');
$params = array(
$this->blogid,
$this->myusername,
$this->mypassword,
array(
'post_type' => 'post',
'post_status' => $status,
'post_title' => $title,
'post_content' => $content,
'post_date' => $post_date,
'terms_names' => array('category' => $categories, 'post_tag' => $tags)
)
);
$request = xmlrpc_encode_request('wp.newPost', $params);
$response = $this->execute($request);
return $response;
}
}
?>
hope it helps
I'm trying to fetch all profiles for some Google Analytics account in PHP. I'm using HTTP_Request2 class from PEAR (with cURL adapter, but I've also tried with Socket) and I keep getting "Target feed is read-only" error when I try to fetch data from https://www.google.com/analytics/feeds/accounts/default
I'm using ClientLogin auth method and as far as I can see correct Authorization header is sent with each API request (I've used observer class to test for headers which are being sent).
Here is the code I use (stripped-down, test version):
require 'HTTP/Request2.php';
class GA {
protected $email;
protected $passwd;
protected $auth_code;
public function __construct($email = '', $passwd = '') {
$this->email = $email;
$this->passwd = $passwd;
}
public function authorize($email = '', $password = '', $force = false) {
if (!$force and !empty($this->auth_code) and $email == $this->email and $password == $this->passwd) {
return true;
}
unset($this->auth_code);
!empty($email) or $email = $this->email;
!empty($password) or $password = $this->passwd;
if (empty($email) or empty($password)) {
return false;
}
try {
$response = $this->post(
'https://www.google.com/accounts/ClientLogin',
array(
'accountType' => 'GOOGLE',
'Email' => $this->email = $email,
'Passwd' => $this->passwd = $password,
'service' => 'analytics'
)
);
if ($response->getStatus() == 200 and preg_match('/(?:^|[\n\r])Auth=(.*?)(?:[\n\r]|$)/', $response->getBody(), $match)) {
$this->auth_code = $match[1];
echo $this->auth_code;
return true;
}
} catch (HTTP_Request2_Exception $e) {
return false;
}
}
public function call($url, array $params = array(), array $headers = array()) {
if (!$this->auth_code && !$this->authorize($this->email, $this->passwd, true)) {
return false;
}
$headers['Authorization'] = 'GoogleLogin auth=' . $this->auth_code;
return $this->post($url, $params, $headers);
}
protected function post($url, array $params = array(), array $headers = array()) {
$headers['GData-Version'] = '2';
$request = new HTTP_Request2($url);
$request->setAdapter('curl');
$request->setConfig('ssl_verify_peer', false);
$request->setHeader($headers);
$request->setMethod(HTTP_Request2::METHOD_POST);
$request->addPostParameter($params);
return $request->send();
}
}
$ga = new GA('*********#gmail.com', '*********');
var_dump($ga->call('https://www.google.com/analytics/feeds/accounts/default'));
Thanks in advance!
to answer my own question: https://www.google.com/analytics/feeds/accounts/default must be accessed trough GET method. My code was always using POST.