xmpphp XMPP, send message from php script - php

Hi
I have a jabberserver and i would like to be able to push messages out to users from a php script.
F.x. if i call script.php from my browser, it sends a message to a user.
I've tried both with jaxl and xmpphp which are xmp frameworks, but i cant get it to work. Not with my own server, and neither with facebooks server.
I have the following ind my script.php:
error_reporting(E_ALL);
include("lib/xmpphp/XMPPHP.php");
$conn = new XMPP('chat.facebook.dk', 5222, 'username', 'password', '', 'chat.facebook.com', true, XMPPHP_Log::LEVEL_VERBOSE);
$conn->connect();
$conn->processUntil('session_start');
$conn->message('someusername#chat.facebook.com', 'This is a test message!');
$conn->disconnect();
But nothing happends and no errors either.
I've followed this guide to set up an echobot, and it works with both my server and facebook. The script is here: http://abhinavsingh.com/blog/2010/02/writing-your-first-facebook-chat-bot-in-php-using-jaxl-library/ <-- and is run on the server commandline, and waiting for a message, and then replys.
What do i have to do ?

<?php
set_time_limit(0); // some time connection take while
require_once 'xmpp-lib/XMPPHP/XMPP.php';
$host = 'you Host name'; // ex.192.168.2.1
$port = '5222'; // its defauls xmpp port
$username = 'name#host' // ex vivek#host
$pass = 'userpass';
$conn = new XMPPHP_XMPP(host , $port, $username, $pass, 'xmpphp','yourhost', $printlog=false, $loglevel=XMPPHP_Log::LEVEL_INFO);
try {
$conn->connect();
$conn->processUntil('session_start');
$conn->presence();
$conn->message('anotherusername#host', 'Hello!');
$conn->disconnect();
} catch(XMPPHP_Exception $e) {
die($e->getMessage());
}
?>

<?php
$command = 'send_message';
$requestParams = array('type' => 'chat',
'to' => '919999999999#127.0.0.0',
'from' => '919999999991#127.0.0.0',
'body' => 'Hi vivek patel',
'subject' => 'test',
);
$request = xmlrpc_encode_request($command, $requestParams, (array('encoding' => 'utf-8')));
$context = stream_context_create(array('http' => array('method' => "POST",
'header' => "User-Agent: XMLRPC::Client mod_xmlrpc\r\n" .
"Content-Type: text/xml\r\n" .
"Content-Length: " . strlen($request),
'content' => $request
)
)
);
try {
$file = file_get_contents("http://127.0.0.0:4560/RPC2", false, $context);
$response = xmlrpc_decode($file);
} catch (Exception $e) {
echo $e->getMessage();
exit;
}
if (xmlrpc_is_fault($response)) {
trigger_error("xmlrpc: $response[faultString] ($response[faultCode])");
}
echo '<pre>';
echo print_r($response);
echo '</pre>';
?>

Related

Why does execution stop at wordpress_remote_post() function call?

I am trying to write an SSO plugin for my WordPress multisite and MemberSuite. I'm in the beginning steps, just trying to have the user sign in and get the MemberSuite sign-in token.
Here's the code I have so far:
define("MS_API_URL", "http://rest.membersuite.com/swagger/platform/v2/");
define("TENANT_ID", "00000");
define("USER_POOL", "placeholder");
define("CLIENT_ID", "placeholder");
function send_request() {
$username = $_POST[portalusername];
$password = $_POST[portalpassword];
return ms_sign_in($username, $password, USER_POOL, CLIENT_ID);
}
function ms_sign_in($un, $pw, $up, $cid) {
$url = MS_API_URL . 'storeJWTTokenForUser/' . TENANT_ID;
$data = array(
'username' => $un,
'password' => $pw,
'userPool' => $up,
'clientID' => $cid
);
$arguments = array(
'method' => 'POST',
'headers' => array(
'Content-Type' => 'application/json',
'Accept' => 'application/json'
),
'body' => json_encode($data)
);
echo "before post";
$response = wp_remote_post($url, $arguments);
echo "after post";
if ( is_wp_error( $response ) ) {
$error_message = $response->get_error_message();
echo "Something went wrong: $error_message";
}
echo $response;
echo $response['body'];
return $response['body'];
}
?>
<html>
<body>
<p>body 1</p>
<?php echo send_request();?>
<p>body 2</p>
</body>
</html>
My form calls the send_request() function. As far as I can tell, I've implemented everything the way the MemberSuite documentation indicates it should be implemented. I've included all the necessary values for verification.
However, it appears execution just stops when I reach the line that says $response = wp_remote_post($url, $arguments);. The output displays:
body 1
before post
but nothing else. I'd like to know why this happening, if there is any way to fix it, and/or if there is a different way I should go about making the POST request.

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

Register user in ejabberd with xmpphp

I have connected ejabberd xmpp server with xmpphp library. Its working fine. I need to create a user in ejabberd xmpp server using xmpphp library.
So i have added following two functions in XMPPHP/XMPP.php file :
public function register($username, $password = null){
if (!isset($password)) $password = $this->genRandomString(15);
$id = 'reg_' . $this->getID();
$xml = "<iq type='set' id='$id'>
<query xmlns='jabber:iq:register'>
<username>" . $username . "</username>
<password>" . $password . "</password>
<email></email>
<name></name>
</query>
</iq>";
$this->addIdHandler($id, 'register_new_user_handler');
$this->send($xml);
}
protected function register_new_user_handler($xml){
switch ($xml->attrs['type']) {
case 'error':
$this->event('new_user_registered', 'error');
break;
case 'result':
$query = $xml->sub('query');
$username='';
$password='';
if(!is_array($query->subs)) {
foreach ($query->sub as $key => $value) {
switch ($value->name) {
case 'username':
$username = $value->data;
break;
case 'password':
$password = $value->data;
break;
}
}
}
$this->event('new_user_registered', array('jid' => $username . "#{$this->server}", 'password' => $password));
default:
$this->event('new_user_registered', 'default');
}
}
and m calling the above functions in sendmessage_example.php as follows :
<?php
// activate full error reporting
//error_reporting(E_ALL & E_STRICT);
include 'XMPPHP/XMPP.php';
$conn = new XMPPHP_XMPP('serverhost', 5222, 'admin#localhost', 'password', 'xmpphp', 'localhost', $printlog=false, $loglevel=XMPPHP_Log::LEVEL_INFO);
try {
$conn->connect();
$conn->processUntil('session_start');
$conn->presence();
$conn->register('uname', 'pass');
$conn->message('vaiju#localhost', 'This is a test message!');
$conn->disconnect();
} catch(XMPPHP_Exception $e) {
die($e->getMessage());
}
I have manually added a user called vaiju. I'm able to connect it and m getting a message in my pidgin client. But user registration is not working properly.
You could do like this. tested and working with me.
define('JABBER_REST_HOST','localhost:5285');
define('JABBER_REST_URL','http://localhost:5285/rest');
$request = "register ketan13 localhost ketan13";
$jabberResponse = sendRESTRequest(JABBER_REST_URL, $request);
echo '<pre>'; print_r($jabberResponse);
function sendRESTRequest ($url, $request) {
// Create a stream context so that we can POST the REST request to $url
$context = stream_context_create (array ('http' => array ('method' => 'POST'
,'header' => "Host: ".JABBER_REST_HOST."\nContent-Type: text/html; charset=utf-8\nContent-Length: ".strlen($request)
,'content' => $request)));
// Use file_get_contents for PHP 5+ otherwise use fopen, fread, fclose
if (version_compare(PHP_VERSION, '5.0.0', '>=')) {
$result = file_get_contents($url, false, $context);
} else {
// This is the PHP4 workaround which is slightly less elegant
// Suppress fopen warnings, otherwise they interfere with the page headers
$fp = #fopen($url, 'r', false, $context);
$result = '';
// Only proceed if we have a file handle, otherwise we enter an infinite loop
if ($fp) {
while(!feof($fp)) {
$result .= fread($fp, 4096);
}
fclose($fp);
}
}
return $result;
}

Paypal use of clientid & clientSecret for PHP

I am using Paypal API for a long time for developing.
Now, my site is on life, and I have problems, of migrating my code to life,
and I presume that I need add clientid+clientSecret, which I didn't have on developing site.
(As I see on https://github.com/paypal/rest-api-sdk-php and by some workarround).
Also, I want minimal changes on the code bellow, even it seems old fashioned to have it worked in life web site.
As developer, I use "setExressCheckout" method like this
(Attention to echo $response - I don't expect that line. What to do instead?)
// =========== START OF CODE
<?php
/*.
require_module 'standard';
require_module 'standard_reflection';
require_module 'spl';
require_module 'mysqli';
require_module 'hash';
require_module 'session';
require_module 'streams';
.*/
require_once __DIR__ . "/stdlib/all.php";
/*. array .*/ $body_data = null;
$body_data_txt = "";
/*. string .*/ $htmlpage = "";
/*. array .*/ $tokenAr = array();
$response = "";
session_start();
$url = trim('https://www.sandbox.paypal.com/cgi-bin/webscr');
$body_data = array( 'USER' => "*******",
'PWD' => "*******",
'SIGNATURE' => "******",
'VERSION' => "95.0",
'PAYMENTREQUEST_0_PAYMENTACTION' => "Sale",
'PAYMENTREQUEST_0_AMT' => (string)$_SESSION["AMOUNT"],
'PAYMENTREQUEST_0_CURRENCYCODE' => 'USD',
'RETURNURL' => "*****",
'CANCELURL' => "******",
'METHOD' => "SetExpressCheckout"
);
$body_data_txt = http_build_query($body_data, '', chr(38));
try
{
//create request and add headers
$params = array(
'http' => array(
'protocol_version' => "1.1",
'method' => "POST",
'header' => "".
"Connection: close\r\n".
"Content-Length: ".strlen($body_data_txt)."\r\n".
"Content-type: "."application/x-www-form-urlencoded"."\r\n",
'content' => $body_data_txt
));
//create stream context
$ctx = stream_context_create($params);
//open the stream and send request
try {
$fp = fopen($url, 'r', false, $ctx);
} catch(ErrorException $e) {
throw new ErrorException("cannot open url" . $url . " error:" . $e->getMessage());
}
//get response
$response = (string)stream_get_contents($fp);
//check to see if stream is open
if ($response === "") {
throw new Exception("php error message = " . "$php_errormsg");
}
//close the stream
fclose($fp);
$key = explode("&", $response);
if (substr($response, 0, 1) === "<") {
echo $response; // ******************************
}
....
// ============ END OF CODE
The code doesn't work as expected, since the line 'echo $response ...' should not run.
It has the contents of a screen titled:
"No buyers or sellers
Sign up for free.
...
"
As I investigated, I need client-id and client-secret. That I made on https://developer.paypal.com.
But how to use it - with minimal changes on my code?
Thanks :)
I have found the solution for my question - No need for clientid and clientsecret.
The code work same for developing mode and life mode.
The url was wrong, and should be: $url = trim('https://api-3t.paypal.com/nvp');
Thanks, anyway :)

CRM dynamic "an error occurred when verifying security for the message"

I am tring to access http://xxxxxxxxxxx/CRM2011/XRMServices/2011/Organization.svc?wsdl
I can able to see functions list. means i can access to webservice. But while i tring to write data using function create it through "an error occurred when verifying security for the message" my code is below
<?php
date_default_timezone_set("Asia/Kolkata");
ini_set("soap.wsdl_cache_enabled", "0");
$location = "http://182.18.175.29/CRM2011/XRMServices/2011/Organization.svc?wsdl";
$config['Username'] = 'xxxxxxx';
$config['Password'] = 'xxxxxx';
$config['soap_version'] = SOAP_1_2;
$config['trace'] = 1; // enable trace to view what is happening
$config['use'] = SOAP_LITERAL;
$config['style'] = SOAP_DOCUMENT;
$config['exceptions'] = 0; // disable exceptions
$config["cache_wsdl"] = WSDL_CACHE_NONE; // disable any caching on the wsdl, encase you alter the wsdl server
$config["features"] = SOAP_SINGLE_ELEMENT_ARRAYS;
include_once 'ntlmSoap.php';
$client = new NTLMSoapClient($location, $config);
print('<pre>');
print_r($client->__getFunctions());
$HeaderSecurity = array("UsernameToken" => array("Username" => 'xxxxxx', "Password" => 'xxxxxx'));
$header[] = new SoapHeader($location, "Security", $HeaderSecurity);
$client->__setSoapHeaders($header);
$params = array(
"bmw_firstname" => "test",
"bmw_lastname" => "test"
);
try {
$response = $client->__soapCall("Create", $params);
var_dump($response);
} catch (Exception $e) {
print_r($e);
}
// display what was sent to the server (the request)
echo "<p>Request :" . htmlspecialchars($client->__getLastRequest()) . "</p>";
// display the response from the server
echo "<p>Response:" . htmlspecialchars($client->__getLastResponse()) . "</p>";

Categories