How to read body of message send by stomp - php

I'm trying to create a json that I wish to send from one producer to another, which later needs to break it down and work with it.
So I am using activemq, and stomp, since I am programming in php.
I have the following program for my producer:
<?php
namespace Stomp;
require __DIR__ . '/../vendor/autoload.php';
use Stomp\Client;
use Stomp\StatefulStomp;
use Stomp\Network\Connection;
use Stomp\Transport\Message;
header('Content-Type: application/json');
//namespace buttoncall\Model;
$provider=''; //colocar provider
$data1= array(
'provider' => $provider
);
(...)
$data=array($data1,$data2, $data3, $data4);
$json = json_encode($data, true);
$destination = '/queue/nexmo';
$messages = 1;
$size = 1024;
$DATA = "calls";
//$body = $data;
$body = $json;
for($i=0; $i< $size; $i++) {
$body .= $DATA[ $i % 26];
}
try {
$connection = new Connection('tcp://192.168.64.2:61613');
$con1 = new StatefulStomp(new Client($connection));
$con1->send($destination, new Message($body));
echo "Message sent $body \n" ;
$con1->send($destination, new Message("SHUTDOWN"));
} catch(StompException $e) {
echo $e->getMessage();
}
}
}
And then the following consumer:
<?php
//Nexmo
namespace Stomp;
require __DIR__ . '/../vendor/autoload.php';
include 'generate_jwt.php';
use Stomp\Client;
use Stomp\StatefulStomp;
use Stomp\Network\Connection;
use Stomp\Transport\Message;
$user = getenv("ACTIVEMQ_USER");
if( !$user ) $user = "admin";
$password = getenv("ACTIVEMQ_PASSWORD");
if( !$password ) $password = "admin";
/*$host = getenv("ACTIVEMQ_HOST");
if( !$host ) $host = "localhost";
$port = getenv("ACTIVEMQ_PORT");
if( !$port ) $port = 61613; */
$destination = '/queue/nexmo';
try {
$connection = new Connection('tcp://192.168.64.2:61613');
$stomp = new StatefulStomp(new Client($connection));
$stomp->subscribe($destination);
echo "Waiting for messages...\n";
while(true) {
$frame = $stomp->read();
echo "message received";
$json = $frame->$body;
//echo($stomp);
//echo($frame);
//echo($body);
echo $json ;
}
} catch(StompException $e) {
echo $e->getMessage();
}
I've tried several combinations to print the body, but nothing seems to work... They both comunicate, and I can see them in the ActiveMQ broker, but I can't extract the body...
Any clues?
Thank you in advance

I figured it out, just had:
$frame = $stomp->read();
$body = $frame->getBody();
echo "message received $body \n";
There is a function for it, in the Stomp library.

Related

how to use dreamscape api in nodejs for check domain name

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

List Azure files and folders from File share snapshots with php

To list the files and folders from Azure Files can be done with this code:
function ListFolder($shareName, $path)
{
global $fileRestProxy;
$vMaxResultados = 5000;
$vNextMarker = "";
$listResult = null;
try
{
do
{
$options = new ListDirectoriesAndFilesOptions();
$options->setMaxResults($vMaxResultados);
$options->setMarker($vNextMarker);
$listResult = $fileRestProxy->ListDirectoriesAndFiles($shareName,$path,$options);
$vNextMarker = $listResult->getNextMarker();
} while ($vNextMarker != "");
}
catch (Exception $e)
{
$code = $e->getCode();
$error_message = $e->getMessage();
return "ERROR:$code:$error_message";
}
return $listResult;
}
But how is the sintaxis or method to the same with a snapshot from these Share?
This doesn't work:
function ListSnapshotFolder($shareName, $path, $snapshot)
{
global $fileRestProxy;
$vMaxResultados = 5000;
$vNextMarker = "";
$listResult = null;
try
{
do
{
$options = new ListDirectoriesAndFilesOptions();
$options->setMaxResults($vMaxResultados);
$options->setMarker($vNextMarker);
$shareFull = $shareName . "?snapshot=" . $snapshot;
$listResult = $fileRestProxy->ListDirectoriesAndFiles($shareFull,$path,$options);
$vNextMarker = $listResult->getNextMarker();
} while ($vNextMarker != "");
}
catch (Exception $e)
{
$code = $e->getCode();
$error_message = $e->getMessage();
return "ERROR:$code:$error_message";
}
return $listResult;
}
Is there any parameter in the $option object to add?
Or maybe the $shareFull must be created in some format?
$shareFull = $shareName . "?snapshot=" . $snapshot;
Thanks in advance.
I believe you have found a bug in the SDK. I looked up the source code here and there's no provision to provide sharesnapshot query string parameter in the options as well as the code does not even handle it.
public function listDirectoriesAndFilesAsync(
$share,
$path = '',
ListDirectoriesAndFilesOptions $options = null
) {
Validate::notNull($share, 'share');
Validate::canCastAsString($share, 'share');
Validate::canCastAsString($path, 'path');
$method = Resources::HTTP_GET;
$headers = array();
$postParams = array();
$queryParams = array();
$path = $this->createPath($share, $path);
if (is_null($options)) {
$options = new ListDirectoriesAndFilesOptions();
}
$this->addOptionalQueryParam(
$queryParams,
Resources::QP_REST_TYPE,
'directory'
);
$this->addOptionalQueryParam(
$queryParams,
Resources::QP_COMP,
'list'
);
$this->addOptionalQueryParam(
$queryParams,
Resources::QP_PREFIX_LOWERCASE,
$options->getPrefix()
);
$this->addOptionalQueryParam(
$queryParams,
Resources::QP_MARKER_LOWERCASE,
$options->getNextMarker()
);
$this->addOptionalQueryParam(
$queryParams,
Resources::QP_MAX_RESULTS_LOWERCASE,
$options->getMaxResults()
);
$this->addOptionalQueryParam(
$queryParams,
Resources::QP_TIMEOUT,
$options->getTimeout()
);
$dataSerializer = $this->dataSerializer;
return $this->sendAsync(
$method,
$headers,
$queryParams,
$postParams,
$path,
Resources::STATUS_OK,
Resources::EMPTY_STRING,
$options
)->then(function ($response) use ($dataSerializer) {
$parsed = $dataSerializer->unserialize($response->getBody());
return ListDirectoriesAndFilesResult::create(
$parsed,
Utilities::getLocationFromHeaders($response->getHeaders())
);
}, null);
}
You may want to open up an issue here: https://github.com/Azure/azure-storage-php/issues and bring this to SDK team's attention.

square payment form php check customer exists in directory and make payment

Am new to Square Payment Form using PHP and trying to do following steps
Check If customer Exists in Directory
If Customer Does not exist - create new customer and collect CUSTOMER_ID
MAKE PAYMENT & get Payment ID
Couple of time this script worked by started getting Maximum execution time of 30 seconds exceeded AND created multiple customer entries in directory and payment failed
PS : am using GOTO to loop and ENV file for credentials
Any help will be appreciated in advance
print_r($_POST);
$booknow = $_POST;
require 'vendor/autoload.php';
use Dotenv\Dotenv;
use Square\Models\Money;
use Square\Models\CreatePaymentRequest;
use Square\Exceptions\ApiException;
use Square\SquareClient;
use Square\Environment;
use SquareConnect\ApiClient;
use Square\Models\CreateCustomerRequest;
$idem = UUID::v4();
$sname = explode(' ', $_POST["cname"]);
$sname0 = $sname[0];
$sname1 = $sname[1];
$cphone = $_POST["cphone"];
//$cphone = '9848848450';
$cemailid = $_POST["cemailid"];
$ifare = ($_POST["ifare"] * 100);
$xnote = $_POST["note"];
//echo '<br><br>fare : ' . $ifare . '<br><br>';
$dotenv = Dotenv::create(__DIR__);
$dotenv->load();
$upper_case_environment = strtoupper(getenv('ENVIRONMENT'));
$access_token = getenv($upper_case_environment.'_ACCESS_TOKEN');
//print_r($access_token);
//echo '<br><br><br>';
$client = new SquareClient([
'accessToken' => $access_token,
'environment' => getenv('ENVIRONMENT')
]);
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
error_log('Received a non-POST request');
echo 'Request not allowed';
http_response_code(405);
return;
}
$nonce = $_POST['nonce'];
if (is_null($nonce)) {
echo 'Invalid card data';
http_response_code(422);
return;
}
searchCustomers: ///search customers
$phone_number = new \Square\Models\CustomerTextFilter();
$phone_number->setFuzzy($cphone);
$filter = new \Square\Models\CustomerFilter();
$filter->setPhoneNumber($phone_number);
$query = new \Square\Models\CustomerQuery();
$query->setFilter($filter);
$body = new \Square\Models\SearchCustomersRequest();
$body->setQuery($query);
$api_response = $client->getCustomersApi()->searchCustomers($body);
if ($api_response->isSuccess()) {
$rmn = $api_response->getBody();
$stx = json_decode($rmn,true);
echo '<br><br>';
echo '# of arrays : ' . count($stx);
if(count($stx) != 0){
//echo '<br><br>';
$cust_id = $stx["customers"][0]["id"];
//echo "Customer ID : " . $cust_id;
goto makePayment;
//goto end;
} else {
//echo 'user do not exists';
/// new customer - start
$body1 = new \Square\Models\CreateCustomerRequest();
$body1->setIdempotencyKey($idem);
$body1->setGivenName($sname0);
$body1->setFamilyName($sname1);
$body1->setEmailAddress($cemailid);
$body1->setPhoneNumber($cphone);
$api_response = $client->getCustomersApi()->createCustomer($body1);
if ($api_response->isSuccess()) {
$result = $api_response->getResult();
goto searchCustomers;
} else {
$errors = $api_response->getErrors();
}
/// new customer - end
}
} else {
echo '<br><br>sorry not found!<bR><br>';
}
goto end;
makePayment:
$amount_money = new \Square\Models\Money();
$amount_money->setAmount($ifare);
$amount_money->setCurrency('USD');
$body = new \Square\Models\CreatePaymentRequest(
'cnon:card-nonce-ok',
$idem,
$amount_money
);
$body->setCustomerId($cust_id);
$body->setNote($xnote);
$api_response = $client->getPaymentsApi()->createPayment($body);
if ($api_response->isSuccess()) {
$result = $api_response->getResult();
$srt = json_encode($result);
echo '<br><br>';
echo "PAYEMNT SUCCESSUFLL <BR><br><br>";
//print_r($srt);
goto end;
} else {
$errors = $api_response->getErrors();
echo 'payment FAILEDDDDDDDDDD';
}
goto end;
end:

php : System.NullPointerException: Attempt to de-reference a null object

Please help me to sort out this problem
I am getting this error.
[faultstring] => System.NullPointerException: Attempt to de-reference a null object
I am using custom object integration for Sales force.
require_once ('soapclient/SforcePartnerClient.php');
require_once ('soapclient/SforceHeaderOptions.php');
try {
$mySforceConnection = new SforcePartnerClient();
$mySforceConnection->createConnection("soapclient/partnerwsdl-sb.xml");
$mySforceConnection->login(USERNAME, PASSWORD.SECURITY_TOKEN);
// Define constants for the web service. We'll use these later
$parsedURL = parse_url($mySforceConnection->getLocation());
define ("_SFDC_SERVER_", substr($parsedURL['host'],0,strpos($parsedURL['host'], '.')));
define ("_WS_NAME_", 'WebToLeadServices');
define ("_WS_WSDL_", 'soapclient/WebToLeadServices-SB-V1.1.xml');
define ("_WS_ENDPOINT_", 'https://' . _SFDC_SERVER_ . '.salesforce.com/services/wsdl/class/' . _WS_NAME_);
define ("_WS_NAMESPACE_", 'http://soap.sforce.com/schemas/class/' . _WS_NAME_);
// SOAP Client for Web Service
$client = new SoapClient(_WS_WSDL_);
$sforce_header = new SoapHeader(_WS_NAMESPACE_, "SessionHeader", array("sessionId" => $mySforceConnection->getSessionId()));
$client->__setSoapHeaders(array($sforce_header));
$sObject = new stdclass();
$sObject->fullName = 'Sunil';
$sObject->country = 'India';
$sObject->budget = '1';
$sObject->type = 'Contact';
$sObject->dialingCode = '91';
$sObject->emailAddress = "XXXX";
$sObject->mobileNumber = "XXXXXXXX";
$sObject->source = "google";
$sObject->projectInterested = "Project";
$sObject->capturePoint = "XXXX.php";
$sObject->IPAddress = "XXXX";
$sObject->webbannerSource = "google";
$sObject->webbannerSize = "twitter";
$createResponse = $client->createLeadFromWeb(array($sObject));
} catch (Exception $e) {
echo '<pre>';
print_r($e);
echo '</pre>';
}
?>
</pre>
I have got the solution for it
We need to pass the variable like this with required field.
and its working
$lead = new StdClass();
$lead->fullName = 'sunil';
$lead->mobileNumber = "1234567896";
$lead->emailAddress = "sunil#example.in";
$lead->source = "DIGITAL MARKETING";
$leadData = array('wl'=>$lead);
$response = $client->createLeadfromWeb($leadData);

Using ZeroMQ (PHP-ZMQ) for loop operations

I'm trying to use heavy resource content loop operation with ZeroMQ (PHP-ZMQ) via tcp protocol.
I've got below code so far:
class SJB_Miscellaneous_SendNotifications extends SJB_Function
{
public function execute()
{
try{
set_time_limit(0);
$i18n = SJB_I18N::getInstance();
$lang = $i18n->getLanguageData($i18n->getCurrentLanguage());
$current_date = strftime($lang['date_format'], time());
// Send Search Notifications
$saved_searches = SJB_SavedSearches::getAutoNotifySavedSearches();
// echo "<pre>"; print_r($saved_searches); echo "</pre>"; exit;
$listing = new SJB_Listing();
$notified_saved_searches_sid = array();
$notificationsLimit = (int) SJB_Settings::getSettingByName('num_of_listings_sent_in_email_alerts');
/* ZeroMQ implementation */
$queue = new ZMQSocket(new ZMQContext(), ZMQ::SOCKET_REQ, "MySock1");
$queue->connect("tcp://127.0.0.1:5555");
/* Assign socket 1 to the queue, send and receive */
$time = time();
$queue->send(json_encode($saved_searches));
// echo $queue->recv();
// exit;
$count = 1;
// array_shift($saved_searches);
$server = new ZMQSocket(new ZMQContext(), ZMQ::SOCKET_REP);
$server->bind("tcp://127.0.0.1:5555");
$msg = $server->recv();
$saved_searches = json_decode($msg, true);
// echo "<pre>"; var_dump($saved_searches); echo "</pre>";
// exit;
foreach ($saved_searches as $saved_search) {
$searcher = new SJB_ListingSearcher();
$listing->addActivationDateProperty();
$search_data = unserialize($saved_search['data']);
$search_data['active']['equal'] = 1;
$datearr = explode('-', $saved_search['last_send']);
$saved_search['last_send'] = strftime($lang['date_format'], mktime(0, 0, 0, $datearr[1], $datearr[2], $datearr[0]));
$search_data['activation_date']['not_less'] = $saved_search['last_send'];
$search_data['activation_date']['not_more'] = $current_date;
$listing_type_sid = 0;
if ($search_data['listing_type']['equal']) {
$listing_type_id = $search_data['listing_type']['equal'];
$listing_type_sid = SJB_ListingTypeManager::getListingTypeSIDByID($listing_type_id);
if (SJB_ListingTypeManager::getWaitApproveSettingByListingType($listing_type_sid))
$search_data['status']['equal'] = 'approved';
}
// echo "<pre>"; echo $saved_search['user_sid']; print_r($listing_type_id); echo "</pre>"; exit;
$id_alias_info = $listing->addIDProperty();
$username_alias_info = $listing->addUsernameProperty();
$listing_type_id_info = $listing->addListingTypeIDProperty();
$aliases = new SJB_PropertyAliases();
$aliases->addAlias($id_alias_info);
$aliases->addAlias($username_alias_info);
$aliases->addAlias($listing_type_id_info);
$search_data['access_type'] = array(
'accessible' => $saved_search['user_sid'],
);
$criteria = SJB_SearchFormBuilder::extractCriteriaFromRequestData($search_data, $listing);
$searcher->found_object_sids = array();
$searcher->setLimit($notificationsLimit);
$sorting_fields = array('CityRegion' => 'ASC');
$found_listings_ids = $searcher->getObjectsSIDsByCriteria($criteria, $aliases, $sorting_fields);
// echo "<pre>"; var_dump($found_listings_ids); echo "</pre>";
if (count($found_listings_ids)) {
$saved_search['activation_date'] = $saved_search['last_send'];
if (SJB_Notifications::sendUserNewListingsFoundLetter($found_listings_ids, $saved_search['user_sid'], $saved_search, $listing_type_sid)) {
SJB_Statistics::addStatistics('sentAlert', $listing_type_sid, $saved_search['sid']);
SJB_DB::query('UPDATE `saved_searches` SET `last_send` = CURDATE() WHERE `sid` = ?n', $saved_search['sid']);
}
$notified_saved_searches_sid[] = $saved_search['sid'];
}
echo nl2br($count."\n");
$count++;
}
// To be entered from task_scheduler.php
$expired_contracts_id = null; $expired_listings_id = null;
$template_processor = SJB_System::getTemplateProcessor();
$template_processor->assign('expired_listings_id', null);
$template_processor->assign('deactivated_listings_id', null);
$template_processor->assign('expired_contracts_id', null);
$template_processor->assign('notified_saved_searches_id', $notified_saved_searches_sid);
$scheduler_log = $template_processor->fetch('task_scheduler_log.tpl');
if ($log_file = #fopen('task_scheduler.log', 'a+')) {
fwrite($log_file, $scheduler_log);
fclose($log_file);
}
SJB_DB::query('INSERT INTO `task_scheduler_log`
(`last_executed_date`, `notifieds_sent`, `expired_listings`, `expired_contracts`, `log_text`)
VALUES ( NOW(), ?n, ?n, ?n, ?s)',
count($notified_saved_searches_sid), count($expired_listings_id), count($expired_contracts_id), $scheduler_log);
} catch(Exception $e){
echo $e->getMessage();
}
}
} // END class SJB_Miscellaneous_SendNotifications extends SJB_Function
Is there a good way to utilise ZeroMQ for this type of operation where I want to free loop operations especially when it reaches $saved_searches foreach loop?

Categories