I am learning how to create and consume a webservice in PHP using SOAP. My client.php file is like this:
require_once "lib/nusoap.php";
$client = new nusoap_client("http://localhost/ehsanashar/webservice/service.php?wsdl");
$book_name = "xyz";
$response = $client->call("price", array("name" => "$book_name"));
if ($response == null) {
echo "Nothing Found";
} else {
echo "Book Data: ". $response;
}
and my service.php is like this:
require_once "lib/nusoap.php";
require_once "function.php";
$server = new nusoap_server();
$server->configureWSDL('webservice', 'urn:webservice');
$server->register(
"price",
array("name" => "xsd:string"),
array("return" => "xsd:integer")
);
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
It requires a file called function.php that is like this:
function price($name) {
$details = array(
'abc' => 100,
'xyz' => 200
);
foreach ($details as $n => $p) {
if ($name == $n) {
$price = $p;
}
return $price;
}
}
When I run the file client.php, theresponse is null, but it shouldn't be, where is the problem? any help?
Try this
FOR WAMP
in client.php
require_once ('lib/nusoap.php');
$client = new soapclient('http://localhost/SOAP/server.php');
//Call a function at server and send parameters too
//$response = $client->call('get_message',$param);
$param = array( 'name' => 'xyz');
$response = $client->call('price',$param);
//Process result
if($client->fault)
{
echo "FAULT: <p>Code: (".$client->faultcode."</p>";
echo "String: ".$client->faultstring;
}
else
{
echo $response;
}
and in server.php
<?php
//call library
require_once ('lib/nusoap.php');
//using soap_server to create server object
$server = new soap_server;
//register a function that works on server
$server->register('get_message');
$server->register('price');
// create the function
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;
}
function price($name){
if(!$name){
return new soap_fault('Client','','Put Book name!');
}
$details=array(
'abc' => 100,
'xyz' => 200
);
foreach($details as $n => $p){
if($name == $n){
$price = $p;
}
}
return "price is ". $price;
}
// create HTTP listener
$server->service($HTTP_RAW_POST_DATA);
exit();
?>
FOR XAMP
in server.php
<?php
//call library
require_once ('lib/nusoap.php');
$URL = "www.your-url.com";
$namespace = $URL . '?wsdl';
//using soap_server to create server object
$server = new soap_server;
$server->configureWSDL('pricetesting', $namespace);
//register a function that works on server
$server->register('hello');
// create the function
function price($name){
if(!$name){
return new soap_fault('Client','','Put Book name!');
}
$details=array(
'abc' => 100,
'xyz' => 200
);
foreach($details as $n => $p){
if($name == $n){
$price = $p;
}
}
return "price is ". $price;
}
// create HTTP listener
$server->service($HTTP_RAW_POST_DATA);
exit();
?>
in client.php
<?php
require_once ('lib/nusoap.php');
$client = new soapclient("http://localhost/soap/server.php?wsdl");
//Call a function at server and send parameters too
//$response = $client->call('get_message',$param);
$param = array( 'name' => 'abc');
$response = $client->call('price',$param);
//Process result
if($client->fault)
{
echo "FAULT: <p>Code: (".$client->faultcode."</p>";
echo "String: ".$client->faultstring;
}
else
{
echo $response;
}
?>
Related
I'm fairly new to all of this, but I have created a simple telegram bot to test their functionality. I have set the webhook and I'm using ngrok for the "host". However when I type a command the bot just doesn't do anything.
Does anyone know how to fix this?
Here is the index.php file:
<?php
require('token.php');
require('config.php');
try{
$ngrokUrl = "ngrok url";
$bot = new TelegramBot($token);
$jH = new jsonHandler($token);
var_dump($bot->setWebhook($ngrokUrl));
$webhookJson = $jH->getWebhookJson();
$chatId = $jH->getChatId($webhookJson);
$msg = $jH->getText($webhookJson) !== "" ? $jH->getText($webhookJson) : "";
switch($msg){
default:{
if ($msg[0] == '/')
$bot->sendMessage($chatId, 'The command does not exist');
break;
}
case '/test':{
$msg = 'test test';
$bot->sendMessage($chatId, $msg);
break;
}
case '/help':{
$msg = 'Help!';
$bot->sendMessage($chatId, $msg);
break;
}
}
}catch(ErrorException $e){
echo $e->getMessage();
}
?>
And the config.php file:
<?php
function fetchApi($url){
$req = curl_init($url);
$resp = curl_exec($req);
if($resp == false){
$error = curl_error($req);
curl_close($req);
throw new ErrorException($error);
}
else{
curl_close($req);
//return $resp;
}
}
class TelegramBot{
protected $tUrl;
function __construct($token){
$this->tUrl = "https://api.telegram.org/bot".$token;
}
function setUrl($method){
return $this->tUrl."/".$method;
}
function sendMessage($chatId, $msg){
$data = [
'chat_id' => $chatId,
'&text' => $msg
];
$url = $this->setUrl("sendMessage?".http_build_query($data));
fetchApi($url);
file_get_contents($url);
}
class jsonHandler extends TelegramBot{
function getWebhookJson(){
$json = file_get_contents("php://input");
return json_decode($json, true);
}
function getChatId($jsonDecoded){
return $jsonDecoded["message"]["chat"]["id"];
}
function getText($jsonDecoded){
return $jsonDecoded["message"]["text"];
}
}
?>
I am trying to validate the request received from the plivo to my application server.
For this I am using the sample code provided by the plivo in the documentation.
<?php
require 'vendor/autoload.php';
use Plivo\Exceptions\PlivoValidationException;
use Plivo\Util\v3SignatureValidation;
use Plivo\XML\Response;
if (preg_match('/speak/', $_SERVER["REQUEST_URI"])) {
$auth_token = "<auth_token>";
$signature = #$_SERVER["X-Plivo-Signature-V3"] ?: 'signature';
$nonce = #$_SERVER["X-Plivo-Signature-V3-Nonce"] ?: 'nonce';
$url = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
$method = $_SERVER['REQUEST_METHOD'];
$SVUtil = new v3SignatureValidation();
if ($method == "GET") {
try {
$valid = $SVUtil->validateV3Signature($method, $url, $nonce, $auth_token, $signature);
} catch (PlivoValidationException $e) {
echo("error");
}
} else {
$body = file_get_contents("php://input");
$params = json_decode($body, true);
try {
$valid = $SVUtil->validateV3Signature($method, $url, $nonce, $auth_token, $signature, $params);
} catch (PlivoValidationException $e) {
echo("error");
}
}
echo $valid;
$body = 'Hi, Calling from Plivo';
$attributes = array(
'loop' => 3,
);
$r = new Response();
$r->addSpeak($body, $attributes);
echo($r->toXML());
} else {
echo "<p>Welcome to Plivo</p>";
}
But I am getting this error
Invalid argument supplied for foreach() in code/plivo/vendor/plivo/plivo-php/src/Plivo/Util/v3SignatureValidation.php on line 13
I am debugging, but not able to find the solution.
One thing I noticed that nothing is being received in json from the PLIVO server.
Can anyone help, as There is not enough documentation available for Plivo Request Validation.
Plivo's Developer Evangelist here. Please try the below code instead.
<?php
require 'vendor/autoload.php';
use Plivo\Exceptions\PlivoValidationException;
use Plivo\Util\v3SignatureValidation;
use Plivo\XML\Response;
if (preg_match('/speak/', $_SERVER["REQUEST_URI"]))
{
$auth_token = "<auth_token>";
$signature = #$_SERVER["HTTP_X_PLIVO_SIGNATURE_V3"] ? : 'signature';
$nonce = #$_SERVER["HTTP_X_PLIVO_SIGNATURE_V3_NONCE"] ? : 'nonce';
$url = $_SERVER['HTTP_REFERER'];
$method = $_SERVER['REQUEST_METHOD'];
$SVUtil = new v3SignatureValidation();
if ($method == "GET")
{
try
{
$valid = $SVUtil->validateV3Signature($method, $url, $nonce, $auth_token, $signature);
}
catch(PlivoValidationException $e)
{
echo ("error");
}
}
else
{
$body = file_get_contents("php://input", true);
parse_str($body, $get_array);
try
{
$valid = $SVUtil->validateV3Signature($method, $url, $nonce, $auth_token, $signature, $get_array);
}
catch(PlivoValidationException $e)
{
echo ("error");
}
}
error_log(print_r($valid, true));
$body = 'Hi, Calling from Plivo';
$attributes = array(
'loop' => 3,
);
$r = new Response();
$r->addSpeak($body, $attributes);
echo ($r->toXML());
}
else
{
echo "<p>Welcome to Plivo</p>";
}
And run the below command
php -S localhost:5000
In case if you still face any issues, please free to contact our support team
src: https://www.plivo.com/docs/voice/concepts/signature-validation#code
I have already work this in php. Here is my working code:
$request = array(
'DomainNames' => $domain_names
);
$response = dreamScapeAPI('DomainCheck', $request);
$available = false;
$alt_domains = array(); // Alternative to user's expected domain names
if (!is_soap_fault($response)) {
// Successfully checked the availability of the domains
if (isset($response->APIResponse->AvailabilityList)) {
$availabilityList = $response->APIResponse->AvailabilityList;
foreach ($availabilityList as $list) {
if ($list->Available){
if ($domain == $list->Item) {
$available = true; // user prefered domain found
}
else {
$alt_domains[] = $list->Item;
}
}
}
}
else {
$error = $response->APIResponse->Errors;
foreach ($error as $e) {
$api_error = $e->Message;
//echo $e->Item . ' - ' . $e->Message . '<br />';
}
}
}
function dreamScapeAPI($method, $data = null) {
$reseller_api_soap_client = "";
$soap_location = 'http://soap.secureapi.com.au/API-2.1';
$wsdl_location = 'http://soap.secureapi.com.au/wsdl/API-2.1.wsdl';
$authenticate = array();
$authenticate['AuthenticateRequest'] = array();
$authenticate['AuthenticateRequest']['ResellerID'] = '**';
$authenticate['AuthenticateRequest']['APIKey'] = '**';
//convert $authenticate to a soap variable
$authenticate['AuthenticateRequest'] = new SoapVar($authenticate['AuthenticateRequest'], SOAP_ENC_OBJECT);
$authenticate = new SoapVar($authenticate, SOAP_ENC_OBJECT);
$header = new SoapHeader($soap_location, 'Authenticate', $authenticate, false);
$reseller_api_soap_client = new SoapClient($wsdl_location, array('soap_version' => SOAP_1_2, 'cache_wsdl' => WSDL_CACHE_NONE));
$reseller_api_soap_client->__setSoapHeaders(array($header));
$prepared_data = $data != null ? array($data) : array();
try {
$response = $reseller_api_soap_client->__soapCall($method, $prepared_data);
} catch (SoapFault $response) { }
return $response;
}
I tried with this : https://github.com/dan-power/node-dreamscape
But domain search can not work properly. Mainly, I want it on nodejs using nodejs dreamscape api but this method is not available on nodejs.
Here is my working demo: click here
Using the SoundCloud PHP wrapper, I can successfully update a song’s title, privacy, genre, tags. But I can't figure out what I'm doing wrong with regard to the streamable property. When I send a true value to track[streamable], it remains false.
Here’s what I’m working with:
<?php
require_once 'Soundcloud.php';
require './globaldatabase.php';
$access_token = $_POST['access_token'];
$trackid = $_POST['trackid'];
$title = $_POST['title'];
$genre = $_POST['genre'];
$tag_list = $_POST['tag_list'];
$privacy = $_POST['privacy'];
$release = $_POST['release'];
$streamable = true;
if($privacy=='disabled'){
$streamable = false;
$privacy = 'private';
}
$client = new Services_Soundcloud($sc_clientid, $sc_clientsecret);
$client->setAccessToken($access_token);
try {
$track = json_decode($client->get('tracks/'.$trackid));
$client->put('tracks/' . $track->id, array(
'track[title]' => $title,
'track[genre]' => $genre,
'track[tag_list]' => $tag_list,
'track[sharing]' => $privacy,
'track[release]' => $release,
'track[streamable]' => $streamable
));
$return = $client->get('tracks/' . $track->id);
$return_array[] = json_decode($return);
echo json_encode($return_array);
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
exit($e->getMessage());
}
?>
Try setting the track attribute api_streamable to true.
I am trying to post on behalf of user. I have used tutorial given on this page: http://25labs.com/updated-post-to-multiple-facebook-pages-or-groups-efficiently-v2-0/ .
I could successfully perform authentication but could not post on behalf.
Here is the source code : https://github.com/karimkhanp/fbPostOnBehalf
Testing can be done here: http://ec2-54-186-110-98.us-west-2.compute.amazonaws.com/fb/
Does any one experienced this?
I'm not familiar with the batch process that the tutorial is using but below is a code sample that posts to a Facebook group
<?php
# same this file as
# test.php
include_once "src/facebook.php";
$config = array(
'appId' => "YOURAPPID",
'secret' => "YOURAPPSECRET",
'allowSignedRequest' => false, // optional, but should be set to false for non-canvas apps
);
class PostToFacebook
{
private $facebook;
private $pages;
public function initialise($config){
$this->name = "Facebook";
// current necessary configs to set
// $config = array(
// 'appId' => FB_APP_ID,
// 'secret' => FB_APP_SECRET,
// 'allowSignedRequest' => false, // optional, but should be set to false for non-canvas apps
// );
$this->facebook = new Facebook($config);
try{
// if user removes app authorization
$this->hasAccess = $this->has_permissions();
if($this->hasAccess){
$this->groups = $this->getGroupData();
}
}
catch(Exception $err){
}
}
public function postMessageToGroup($message, $groupid){
$messageResponse = array(
'STATUS' => 0
);
$fbMessageObj = array(
"message" => strip_tags($message),
);
try
{
$user_page_post = $this->facebook->api("/$groupid/feed", 'POST', $fbMessageObj);
if($user_page_post && !empty($user_page_post['id'])){
$messageResponse['STATUS'] = 200;
$messageData = array(
'id' => $user_page_post['id'],
'link' => 'http://facebook.com/' . $user_page_post['id'],
);
$messageResponse['data'] = $messageData;
}
else{
$messageResponse['STATUS'] = 302;
}
}
catch(Exception $err){
$messageResponse['STATUS'] = 500;
$messageResponse['data'] = array($err);
}
return $messageResponse;
}
// TODO: should read a template somewhere
function show_login() {
$login_url = $this->facebook->getLoginUrl( array( 'scope' => implode(",",$this->permissions()) ));
return 'Login to Facebook and Grant Necessary Permissions';
}
// TODO: should read a template somewhere
public function toString()
{
if($this->hasAccess){
if($this->groups){
$msg = "";
$msg .= '<select name="group_id"><option value=""></option>';
foreach($this->groups as $group) {
$msg .= '<option value="' .
'' . urlencode($group['id']) .
'">' .
$group['name'] .
'</option>' .
'';
}
$msg .= '</select>';
return $msg;
}
else
return "No Groups";
}
else{
return $this->show_login();
}
}
function getGroupData(){
$raw = $this->facebook->api('/me/groups', 'GET');
$data = array();
if (null != $raw && array_key_exists('data', $raw))
return $raw['data'];
return null;
}
// check if current instance has access to facebook
function has_permissions() {
$user_id = #$this->facebook->getUser();
#print_r($user_id);
if($user_id == null) return false;
$permissions = $this->facebook->api("/me/permissions");
foreach($this->permissions() as $perm){
if( !array_key_exists($perm, $permissions['data'][0]) ) {
return false;
}
}
return true;
}
// permissins needed to post
function permissions(){
return array('manage_pages', 'user_groups');
}
}
$fb = new PostToFacebook();
$fb->initialise($config);
if(!$fb->has_permissions())
{
echo $fb->show_login();
}
else{
?>
<form method="post" action="test.php">
<textarea name='message'></textarea>
<?php echo $fb->toString(); ?>
<input type='submit'>
</form>
<?php
}
if(!empty($_POST)){
$response = $fb->postMessageToGroup($_POST['message'], $_POST['group_id']);
if($response['STATUS'] == 200)
print_r("<a href='" . $response['data']['link'] . "'>" . $response['data']['id'] ."</a>");
else
{
echo "ERROR!";
print_r($response);
}
}
?>