How to create an addon domain using xmlapi-php? - php

I am trying to create an addon domain using xmlapi-php. I have a shared hosting account.
This sample code is from github
<?php
include '../xmlapi.php';
$ip = getenv('REMOTE_HOST');
$root_pass = getenv('REMOTE_PASSWORD');
$domain = "somedns.com";
$xmlapi = new xmlapi($ip);
$xmlapi->password_auth("root",$root_pass);
$xmlapi->set_http_client('curl');
$xmlapi->set_port(2086);
$xmlapi->set_debug(1);
print $xmlapi->adddns($domain,$ip);
?>
I am having trouble getting this code to work to create an addon domain. How can it be done?

Well I've figured it out to the best of my ability and here is the solution for all the lost souls out there:
Authentication
You need run the following code at least once for authentication and xml api wrapper:
// AUTHENTICATION -------------------------
include("xmlapi.php");
$host = "Host ip address or Site.com";
$my_user = "Your cPanel user ID";
$my_pass = "Your cPanel password";
$xmlapi = new xmlapi($host);
$xmlapi->set_port(2083);
$xmlapi->password_auth($my_user, $my_pass);
$xmlapi->set_output('json');
$xmlapi->set_debug(1);
Now you can start using the functions provided in the xmlapi.php but you are not limited to them.
Email Creation Example
// Calling on the function "addpop" "email_user#email_domain" -------------------------
$email_user = "apitest";
$email_password = "adfm90f";
$email_domain = "somesite.com";
$email_query = '10';
$email_quota = '600';
//$result will be set equal to the JSON output returned by the call
//api1_query is the function
//in the array is where you pass the required parameters
$result = $xmlapi->api1_query($my_user, "Email", "addpop",
array($email_user, $email_password, $email_quota, $email_domain));
Displaying the results
$result = json_decode($result, true); //Decoding the JSON results to PHP
print_r($result); //Printing the array onto the page
//example of displaying a particular array key, in this example its "result"
echo $result['data']['result'];

Related

How to "see" json response from POST request (webhook)

I created a chatbot in Dialogflow which informs the user about the members of my (extended) family and about where they are living. I have created a small database with MySQL which has these data stored and I fetch them with a PHP script (hosted on Heroku) whenever this is appropriate depending on the interaction of the user with the chatbot.
My PHP script which receives the POST request (webhook) from Dialogflow is the following:
<?php
$dbServername = '******************';
$dbUsername = '******************';
$dbPassword = '******************';
$dbName = '******************';
$conn = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);
header('Content-Type: application/json');
$method = $_SERVER['REQUEST_METHOD'];
if($method == 'POST'){
$requestBody = file_get_contents('php://input');
$json = json_decode($requestBody);
$action = $json->result->action;
$first_name = $json->result->contexts[0]->parameters->{'given-name'};
$last_name = $json->result->contexts[0]->parameters->{'last-name'};
$lifespan = $json->result->contexts[0]->lifespan;
$sql = "SELECT * FROM family WHERE name LIKE '%$first_name%$last_name%';";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$person = $row;
}
switch ($action) {
case 'Name':
$speech= "$first_name is my" . $person["name"] . ".";
break;
case 'Location':
$speech = "$first_name is living in {$person["location"]}.";
break;
default:
$speech = "Please ask me something more relevant to my family";
break;
}
}
else {
$speech = "Sorry, $first_name $last_name is not a member of my family.";
}
$response = new \stdClass();
$response->speech = $speech;
$response->displayText = $speech;
$response->source = "agent";
echo json_encode($response);
}
else
{
echo "Method not allowed";
}
?>
I can instantly see on Dialogflow the json response that I am receiving from it in my PHP script. However, Google Assistant does not provide this option. The problem also is that the json response when using Google Assistant is considerably different than the one when using only Dialogflow.
My question is: how can I "see" what JSON is being sent to my PHP script when using the Google Assistant? In other words, how can I "see" the whole of $requestBody variable at once?
For example, I tried to use https://webhook.site/ and I filled in the following information to create the new URL/endpoint:
Default status code -> 200
Content Type -> application/json
Timeout before response -> 0
Response body -> {
"speech": "WEBHOOK",
"displayText": "WEBHOOK",
"source": "agent"
}
The response body has the same structure as in my PHP script. However, for some reason, Google Assistant does not receive the json response from this custom endpoint (while Dialogflow does receive it perfectly). Therefore I cannot exactly move on and see what it is sent by Dialogflow & Google Assistant in the case of intents which are further triggered by context...
Easy solution: add logging
Add some error logging into your code that prints out the formatted JSON. Something like this right after you create $json would log it to your normal HTTP log file:
error_log( json_encode( $json, JSON_PRETTY_PRINT ) );
You can then examine your HTTP error log after each request to see what was sent. (As you've noted in the comments, you can do this with heroku logs on heroku in the terminal in your project directory.)
If you want it sent to a different location, you can examine the documentation for error_log() for details about how to send it to an email address (if your configuration supports that) or to another file. For example, this would log things to a file named /tmp/json.txt:
error_log( json_encode( $json, JSON_PRETTY_PRINT ), 3, "/tmp/json.txt" );
More complicated solution: use a proxy
You could also use a proxy such as ngrok that allows request inspection. This will give you a public hostname that you will set to forward to the hostname where your service is running. You can then use this public hostname for the fulfillment URL in Dialogflow with the path for the webhook. When Dialogflow sends a request, it will go to this proxy which will forward it to your service. Your service replies to the proxy which forwards it back to Dialogflow. You can inspect both the request and the response. (ngrok runs on the same machine as the service and allows inspection by having another URL you can use that views the request and response. Other proxies may work differently. webhook.site looks like it does something similar, but I haven't tested how its proxying works.)

PHP Function - Convert HTML form input into resuable function for multiple inputs

I'm using the Zillow API in order to get some data from user inputs. So far I've been able to correctly use the API to get the desired data from a single input.
The issue I'm running into is when I try and convert my simple block of code into a function that I can reuse multiple times with multiple inputs.Eventually, I want the user to be able to uploaded a CSV file or something and run this function through multiple inputs.
Below is my code that is functioning properly:
HTML
<form action="logic.php" method="post">
<p>Address: <input type="text" name="address"></p>
<p>City/State: <input type="text" name="csz"></p>
<input type="submit">
</form>
PHP
//API Key
$api_key = 'XXXxxXXX';
//User Inputs
$search = $_POST['address'];
$citystate = $_POST['csz'];
//User Inputs Fromatted
$address = urlencode($search);
$citystatezip = urlencode($citystate);
//Get Address ID From API
$url = "http://www.zillow.com/webservice/GetSearchResults.htm?zws-id=".$api_key."&address=".$address."&citystatezip=".$citystatezip;
$result = file_get_contents($url);
$data = simplexml_load_string($result);
$addressID = $data->response->results->result[0]->zpid;
//Get Estimate from API (using adressID)
$estimate_url = "http://www.zillow.com/webservice/GetZestimate.htm?zws-id=".$api_key."&zpid=".$addressID;
$estimate_result = file_get_contents($zurl);
$estimate_data = simplexml_load_string($zresult);
$estimate = $zdata->response->zestimate->amount;
echo $estimate;
Now the issue is when I try and wrap both of these up into two separate functions in order to use them for multiple inputs.
$api_key = 'XXXxxXXX';
//User Inputs
$search = $_POST['address'];
$citystate = $_POST['csz'];
//User Inputs Fromatted
$address = urlencode($search);
$citystatezip = urlencode($citystate);
function getAddressID($ad,$cs){
//Get Address ID From API
$url = "http://www.zillow.com/webservice/GetSearchResults.htm?zws-id=".$api_key."&address=".$ad."&citystatezip=".$cs;
$result = file_get_contents($url);
$data = simplexml_load_string($result);
$addressID = $data->response->results->result[0]->zpid;
return $addressID;
}
$addressID = getAddressID($address, $citystatezip);
function getEstimate($aID){
//Get Estimate from API (using adressID)
$estimate_url = "http://www.zillow.com/webservice/GetZestimate.htm?zws-id=".$api_key."&zpid=".$aID;
$estimate_result = file_get_contents($estimate_url);
$estimate_data = simplexml_load_string($estimate_result);
$estimate = $estimate_data->response->zestimate->amount;
return $estimate;
}
echo getEstimate($addressID); //Calling function doesn't return anything
If essentially I'm doing this same thing as the first PHP example. Why isn't this working from within a function? Did I overlook something?
Ant help on this would be greatly appreciated.
The problem is that you are using the $api_key variable inside both functions, and that variable is not available there. PHP works a bit different then other languages. You can read up on it here: http://php.net/manual/en/language.variables.scope.php
I suggest you extract a function for calling the api. This way you can declare the api key in that function. It also allows you to easier maintain your code (you could improve your api call by adding some error handling or switching to curl or something). The golden rule of a programmer, Don't Repeat Yourself.
The code could look something like this (untested):
//User Inputs
$search = $_POST['address'];
$citystate = $_POST['csz'];
//User Inputs Fromatted
$address = urlencode($search);
$citystatezip = urlencode($citystate);
function callZillow($endpoint, array $params)
{
$params['zws-id'] = 'XXX'; // this would be your api_key
$url = 'http://www.zillow.com/webservice/' . $endpoint . '.htm?' . http_build_query($params);
$result = file_get_contents($url);
return simplexml_load_string($result);
}
function getAddressID($ad, $cs)
{
//Get Address ID From API
$data = callZillow('GetSearchResults', ['address' => $ad, 'citystatezip' => $cs]);
$addressID = $data->response->results->result[0]->zpid;
return $addressID;
}
$addressID = getAddressID($address, $citystatezip);
function getEstimate($aID)
{
//Get Estimate from API (using adressID)
$estimate_data = callZillow('GetZestimate', ['zpid' => $aID]);
$estimate = $estimate_data->response->zestimate->amount;
return $estimate;
}
echo getEstimate($addressID);

PayPal phone number not shown (using PP php sdk)

We have the following code to transfer our buyer's details to the PayPal:
$ShippingAddr = new AddressType;
// more code ...
$ShippingAddr->Phone = $_userdata['user_phone'];
$BillingAddr = new AddressType;
// more code ...
$BillingAddr->Phone = $_userdata['user_phone'];
$setECReqDetails = new SetExpressCheckoutRequestDetailsType();
// more code ...
$setECReqDetails->Address = $ShippingAddr;
$setECReqDetails->BillingAddress = $BillingAddr;
$setECReqType = new SetExpressCheckoutRequestType();
$setECReqType->Version = '104.0';
$setECReqType->SetExpressCheckoutRequestDetails = $setECReqDetails;
$setECReq = new SetExpressCheckoutReq();
$setECReq->SetExpressCheckoutRequest = $setECReqType;
$setECResponse = $paypalService->SetExpressCheckout($setECReq);
Working fine apart from the phone number which remains empty on PayPal checkout site.
Any idea what we did wrong?
I believe you are trying to get users information as per this webservice. https://developer.paypal.com/docs/api/#get-user-information
So you should call it this way according to the paypal doc,
$_userdata['phone_number'];

Signing errors from Withings Rest API

all
I have an app that is successfully getting authorized using Withing's api and OAuth.
I get the auth page from whitings, and I get the resulting token and verifier, however I can not make requests with those - I keep getting a 342 error: The signature (using Oauth) is invalid.
Code:
<?
require("include.php");
require_once("OAuth.php");
$domain = "oauth.withings.com";
$base = "/account/";
$base_url = "https://$domain$base";
$hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
$consumer = new OAuthConsumer("my key goes here :-)", "my key goes here :-)", "http://oauth.corp.withings.com/test.php");
$sig_method = $hmac_method;
$username="mydbusername";
$mySQL=" select * from `healthtokens` where service='WITHINGS' and userid='".$username."'";
$data=mysql_query($mySQL) or die("Died at 2<BR>".mysql_error());
$tokenrow = mysql_fetch_array( $data );
$serviceuserid=$tokenrow['serviceuserid'];
$otoken=$tokenrow['otoken'];
$overifier=$tokenrow['overifier'];
$acc_tok = new OAuthToken($otoken,$overifier);
$req = OAuthRequest::from_consumer_and_token($consumer, $acc_tok, "GET", "http://wbsapi.withings.net/user?action=getbyuserid&userid=".$serviceuserid);
$req->sign_request($sig_method, $consumer, $acc_tok);
$response = file_get_contents($req);
echo $response;
?>
Withings API docs: http://www.withings.com/en/api
An example of my call:
http://wbsapi.withings.net/user?action=getbyuserid&oauth_consumer_key=mybigconsumerkeyishere&oauth_nonce=f57a956d52c7412326fb0577e87addc4&oauth_signature=jiBNvql5r06HysjjVyxCh7C7ZUk%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1381758029&oauth_token=4088d6173b78b71cfd6ddd4245496de4b1f7b3c45bfb49f8e59b1202ccfc&oauth_version=1.0&userid=1234567
I know it sounds silly and it gave me some headaches too, but the "funny" thing with oauth 1 (or at least withings) is, that the order of the parameters is important.
Try using the EXACT order as in the withings oauth sample (http://www.withings.com/en/api/oauthguide):
http://wbsapi.withings.net/measure?
action=getmeas
&oauth_consumer_key=c331c571585e7c518c78656f41582e96fc1c2b926cf77648223dd76424b52b
&oauth_nonce=accbac1b7ee2b86b828e6dc4a5a539b2
&oauth_signature=XfobZMboIg2cRyNKAvyzONHHnKM%3D
&oauth_signature_method=HMAC-SHA1
&oauth_timestamp=1311842514
&oauth_token=887557411788d5120537c6550fbf2df68921f8dd6f8c7e7f9b441941eb10
&oauth_version=1.0
&userid=831

How to export Exchange Web Services Item to a *.eml file? (PHP)

I'm developing a web interface for Exchange Web Services which should be able to save a mail item to eml format. I use PHP-EWS (https://github.com/jamesiarmes/php-ews) to establish a connection to the Exchange Server.
I know how such a file looks like, so I could download a mail item and generate an eml template with the data.
But I found this post: Save mail to msg file using EWS API. Colin talks about a mechanism which directly export a mail item into eml file. Is that possible in PHP, too?
Additionally I found another thing: https://github.com/jamesiarmes/php-ews/wiki/Email:-Set-Extended-MAPI-Properties. In this example somebody generates a mime content and set it to a new item. Is it possible to get the mime type (which looks like an eml file to me) for an existing item?
Thanks for any help!
To save a mail item in eml format you have to set the IncludeMimeContent property to true in the ItemShape element of the GetItem operation.
By doing so, you will get in the GetItem response a MimeContent element:
The MimeContent element contains the native Multipurpose Internet Mail
Extensions (MIME) stream of an object that is represented in
base64Binary format.
As an example, consider the following code:
<?php
function __autoload($class_name) {
$base_path = 'php-ews-master';
$include_file = $base_path . '/' . str_replace('_', '/', $class_name) . '.php';
return (file_exists($include_file) ? require_once $include_file : false);
}
/*
** Adjust these variables before running the script!
*/
$server = 'your_server';
$username = 'your_user';
$password = 'your_password';
$message_id = 'your_message_id';
$ews = new ExchangeWebServices($server, $username, $password);
//print_r($ews);
$request = new EWSType_GetItemType();
$request->ItemShape = new EWSType_ItemResponseShapeType();
$request->ItemShape->BaseShape = EWSType_DefaultShapeNamesType::ALL_PROPERTIES;
$request->ItemShape->IncludeMimeContent = true;
$request->ItemIds = new EWSType_NonEmptyArrayOfBaseItemIdsType();
$request->ItemIds->ItemId = new EWSType_ItemIdType();
$request->ItemIds->ItemId->Id = $message_id;
$response = $ews->GetItem($request);
//echo '<pre>'.print_r($response, true).'</pre>';
if (($response->ResponseMessages->GetItemResponseMessage->ResponseCode == 'NoError') &&
($response->ResponseMessages->GetItemResponseMessage->ResponseClass == 'Success')) {
file_put_contents("test.eml", base64_decode($response->ResponseMessages->GetItemResponseMessage->Items->Message->MimeContent->_));
}
?>

Categories