SugarCRM - how to populate some field with web service response? - web-services

I have my index.php file which is calling web service out of sugar and it returns me as response when I run it on my local Apache this result which is OK:
<soapenv:Envelope <soapenv:Body> <ns:CommandResponseData>
<ns:Operation name="BalanceAdjustment"> </ns:Operation>
</ns:CommandResponseData> </soapenv:Body> </soapenv:Envelope>
I created one additional button within Detail View which I plan to call this web service but I do not know how to bind that button, my index.php file and result from that web service to pack in some field.
For testing purposes I would like to put this whole response on example in field Comment of Contact module: so that field Comment should Contain above whole response (I will later parse it).
I created new button (which does not do anything currently )
I created button in view.detail.php.
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
require_once('include/json_config.php');
require_once('include/MVC/View/views/view.detail.php');
class ContactsViewDetail extends ViewDetail
{
function ContactsViewDetail()
{
parent::ViewDetail();
}
function display()
{
$this->dv->defs['templateMeta']['form']['buttons'][101] = array (
'customCode' => '<input title="Call" accesskey="{$APP.LBL_PRINT_PDF_BUTTON_KEY}" class="button" onClick="javascript:CustomFunctionHere();" name="tckpdf" value="Call" type="button">');
parent::display();
}
}
?>
I will appreciate help with this. So to recapitulate : With this my button I want to call my index.php file which will call web service and I want to set web service response in my field Comment (I am getting response in index.php file as htmlspecialchars($client->__getLastResponse())
this is the whole index.php file that I am using currently to call some web service.
<?php
include_once 'CommandRequestData.php';
include_once 'CommandResponseData.php';
$client = new SoapClient("http://127.0.0.1:8181/TisService?WSDL", array(
"trace" => 1, // enable trace to view what is happening
"exceptions" => 1, // disable exceptions
"cache_wsdl" => 0) // disable any caching on the wsdl, encase you alter the wsdl server
);
$req = new CommandRequestData();
$req->Environment->Parameter[0]->name = "ApplicationDomain";
$req->Environment->Parameter[0]->value = "CAO_LDM_00";
$req->Environment->Parameter[1]->name = "DefaultOperationNamespace";
$req->Environment->Parameter[1]->value = "CA";
$req->Command->Operation->namespace = "CA";
$req->Command->Operation->name = "BalanceAdjustment";
$req->Command->Operation->ParameterList->StringParameter[0]->name = "CustomerId";
$req->Command->Operation->ParameterList->StringParameter[0]->_ = "387671100009";
$req->Command->Operation->ParameterList->IntParameter[0]->name = "AmountOfUnits";
$req->Command->Operation->ParameterList->IntParameter[0]->_ = "1000";
$req->Command->Operation->ParameterList->IntParameter[1]->name = "ChargeCode";
$req->Command->Operation->ParameterList->IntParameter[1]->_ = "120400119";
try {
$result = $client->ExecuteCommand($req);
$result->CommandResult->OperationResult->Operation->name . "<br /><br />";
}
catch(SoapFault $e){
echo "<br /><br />SoapFault: " . $e . "<br /><br />";
}
catch(Exception $e){
}
echo "<p>Response:".htmlspecialchars($client->__getLastResponse())."</p>";
?>

Related

Cross domain cookie - shared data between domains

I have been looking for any solution for my case, but I haven't found it. Therefore I decided to share my solution.
CASE
I want to share some user information between domains. It means I want to get all collected info about user who already visited my web1.com last week and come to web2.com right now. The user is for first time at web2.com but I already know who he is.
SOLUTION:
Requirements:
PHP server - central server whose generate cookies and serve user data
Database server (optionally) - keep cookies and user data (you can use file etc.) I'm using Postgres.
Possibility to include part of JS code into webs.
PHP server http://cookie-server.local index.php:
<?php
$hash = array_key_exists('my-cookie', $_COOKIE) ? $_COOKIE["my-cookie"] : NULL;
try {
$connection = new PDO("pgsql:dbname=cookie;host=localhost", 'postgres', 'postgres');
$data = findHash($connection, $hash);
if ($data) {
setcookie('my-cookie', $data['hash'], strtotime("+1 year"));
sendResponse($data);
} else {
$hash = generateHash();
$data = storeHash($connection, $hash);
setcookie('my-cookie', $hash, strtotime("+1 year"));
}
} catch (PDOException $e) {
echo $e->getMessage();
die();
}
function findHash($connection, $hash) {
$sql = 'SELECT * from cookie WHERE hash = :hash';
$stm = $connection->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$stm->execute(array(':hash' => $hash));
$result = $stm->fetchAll(PDO::FETCH_ASSOC);
if ($result === FALSE) {
printError($stm->errorInfo());
}
return count($result) > 0 ? $result[0] : NULL;
}
function sendResponse($data) {
header('Content-Type: text/javascript; charset=utf8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Max-Age: 3628800');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
echo 'showData('. json_encode($data) .');';
}
function printError($error) {
echo 'SQL error: ' . $error[2];
die();
}
function generateHash() {
return $hash = md5(uniqid(mt_rand(), TRUE));
}
function storeHash($connection, $hash) {
$sql = "INSERT INTO cookie (id, hash) VALUES (nextval('cookie_id_seq'), :hash)";
$stm = $connection->prepare($sql);
$result = $stm->execute(['hash' => $hash]);
if ($result === FALSE) {
printError($stm->errorInfo());
}
return [
'id' => $connection->lastInsertId(),
'hash' => $hash,
'name' => ''
];
}
?>
Basic web page on web1.com (The JS code hast to be everywhere you need to know info about user)
<html>
<body>
WEB 1:<br> <span id="hash"></span>
</body>
<script type="text/javascript">
function showData(data) {
document.getElementById('hash').innerHTML = "<br>ID: " + data.id + "<br>Hash: " + data.hash + "<br>Jmeno: " + data.name;
}
var script = document.createElement("script");
script.type = 'application/javascript';
script.src = "http://cookie-server.local";
document.getElementsByTagName("head")[0].appendChild(script);
</script>
<script type="text/javascript" src="http://cookie-server.local">
</html>
Database:
How it works?
When user visit web1.com, the JS code execute and include
<script type="text/javascript" src="http://cookie-server.local"> to page head element. The browser try to download content of file and it execute PHP code on server. The server look at passed cookies and find out there is no my-cookie. Therefore it generate cookie hash, store it in database, set it to user (cookie with name "my-cookie" for domain cookie-server.local) and send user data with JSONP. For another request to server it find previously generated hash in database and only extends expiration and sends user data for sure. Since now, when this user open any other web page (web2.com...) with the JS code, you know who it is.

PowerShell webservice query

There is PS script for verifying webservice and it works:
$SiteURL = "http://wsf.cdyne.com/WeatherWS/Weather.asmx?op=GetCityWeatherByZIP"
$request = [Net.HttpWebRequest]::Create($SiteURL)
try
{
#Get the response from the requst
$response = [Net.HttpWebResponse]$request.GetResponse()
Write-Host "The service is running."
$request.Abort()
}
Catch
{
Write-Warning "The service of site does not run or maybe you don't have the Credential"
}
But how I can specify query parameter, ZIP?
add a $zip parameter to get zip as an input
param($zip)
update your url to include zip when sending request
$siteURL="http://wsf.cdyne.com/WeatherWS/Weather.asmx/GetCityWeatherByZIP?ZIP=$zip"

Not Sure If Session Is Initiated Using Facebook PHP SDK

I'm trying to use Facebook's PHP SDK. The code that makes a call to Facebook to retrieve user's information is saved in a file called fbcall.php. The fbcall.php page is called through an href link from another page called index.php
The Entire Code (index.php):
<?php
echo "Login Here";
?>
Index.php is also my FacebookRedirectLoginHelper redirect url.
The question I have is that I'm not seeing an output for the following statement in the fbcall.php file and I'm not sure why?
echo "Name: " . $user_profile->getName();
I get the sense that my sessions isn't initiated but I'm sure how to validate this. And if it isn't initiated then I'm not sure what i'm doing wrong considering I'm following Facebook's guidelines here (or atleast I think I am).
The Entire Code (fbcall.php):
<?php
session_start();
// Make sure to load the Facebook SDK for PHP via composer or manually
require_once 'autoload.php';
//require 'functions.php';
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\Entities\AccessToken;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\HttpClients\FacebookHttpable;
// add other classes you plan to use, e.g.:
// use Facebook\FacebookRequest;
// use Facebook\GraphUser;
// use Facebook\FacebookRequestException;
FacebookSession::setDefaultApplication('AM USING MY APP ID HERE','AM USING MY SECRET KEY HERE');
$helper = new FacebookRedirectLoginHelper('http://localhost/facebook/index.php');
$params = array('email','public_profile', 'user_status', 'user_friends');
$loginUrl = $helper->getLoginUrl($params);
try {
$session = $helper->getSessionFromRedirect();
// var_dump($session);
} catch(FacebookRequestException $ex) {
} catch(\Exception $ex) {
}
if (isset($session)) {
var_dump($session);
}
else
{
$loginUrl = $helper->getLoginUrl();
header("location:".$loginUrl);
exit;
}
$request = new FacebookRequest($session, 'GET', '/me');
$response = $request->execute();
$graphObject = $response->getGraphObject();
if(isset($session)) {
try {
$user_profile = (new FacebookRequest(
$session, 'GET', '/me'
))->execute()->getGraphObject(GraphUser::className());
echo "Name: " . $user_profile->getName();
} catch(FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
}
}
?>
Once the user grant your permissions, he/she will be redirected to index.php (because of your redirect_uri).
So there is two solutions:
- change you're redirect_uri to be fbcall.php
- move all fbcall.php logic to index.php, and change header("location:".$loginUrl); by echo "Login Here";

How to create Instagram type message when posting photo to users timeline?

If you share a photo on Instagram you see the following message above the photo on your timeline.
"FB User took a photo with Instagram."
My test currently just shows:
"FB User 3 seconds ago via AppName"
My image Post code is:
$args = Array(
'url' => 'http://www.mySiteName.com/imageName.png',
'message' => 'Made on SiteName http://www.mySiteName.com',
);
$post_id = $this->facebook->api("/me/photos", "post", $args);
I think I need to set OpenGraph Actions and Objects, which I've done, but I'm not sure I've set them up correctly or how to test them.
I've created an Action "Make" and an Object "Collection" and tried the following:
$post_id = $this->facebook->api("/me/Namespace:make", "post", $args);
but get error:
"The action you're trying to publish is invalid because it does not specify any reference objects. At least one of the following properties must be specified: collection."
Collection Get Code gives:
<head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# collection: http://ogp.me/ns/collection#">
<meta property="fb:app_id" content="appId" />
<meta property="og:type" content="collection" />
<meta property="og:url" content="Put your own URL to the object here" />
<meta property="og:title" content="Sample Collection" />
<meta property="og:image" content="https://s-static.ak.fbcdn.net/images/devsite/attachment_blank.png" />
Action Get Code gives:
curl 'https://graph.facebook.com/me/nameSpace:make?access_token=TOKEN'
I've managed to get it working and have posted below an image of resulting Post, reference URLs and Codeigniter code.
Make is my OpenGraph Action and Collection is my OpenGraph Object.
Reference:
http://developers.facebook.com/docs/tutorials/ios-sdk-tutorial/publish-open-graph-story/
http://developers.facebook.com/docs/opengraph/usergeneratedphotos/
$userId = $this->facebook->getUser();
// If user is not yet authenticated, the id will be zero
if($userId == 0){
// Generate a login url
$url = $this->facebook->getLoginUrl(array('scope'=>'email,user_photos,friends_photos,publish_stream'));
echo "<h2><a href='" . $url . "'>Login</a></h2>";
} else {
// Make Logout URL
$logoutUrl = $this->facebook->getLogoutUrl(array(
'next' => 'http://www.myUrl.com/logout/',
// URL to which to redirect the user after logging out
));
echo "<h2><a href='" . $logoutUrl . "'>Logout</a></h2>";
// Get User's data
$user = $this->facebook->api('/me');
echo "<p>Welcome <b>" . $user["name"] . '</b></p>';
echo("<p><b>User Details: </b>");
print_r($user);
echo("</p>");
// Get user's Permissions
$permissions = $this->facebook->api('/me/permissions');
echo("<p><b>User Permissions: </b>");
print_r($permissions);
echo("</p>");
if (isset($permissions['data'][0]['publish_stream'])) {
echo "<h3>Permission to Post</h3>";
} else {
$url = $this->facebook->getLoginUrl(array('scope'=>'email,user_photos,friends_photos,publish_stream'));
echo "<h3>NO Permission to Post: ";
echo "<a href='" . $url . "'>Get extra permissions</a></h3>";
}
// Upload an via OpenGraph Collection Object
$og_type = 'collection'; // Your Opengraph Object
$og_title = urlencode('This is my Title');
$og_description = urlencode('This is my Description');
$og_image = 'http://www.myUrl.com/big.png'; // At least 480px by 480px
$object_url = 'http://www.myUrl.com/fb_object_meta.php?fb:app_id=398917983475605&og:type='.$og_type.'&og:title='.$og_title.'&og:description='.$og_description.'&og:image='.urlencode($og_image);
// See this URL if you need the code for the dynamic meta data page
// http://developers.facebook.com/docs/tutorials/ios-sdk-tutorial/publish-open-graph-story/
$args = Array(
'collection' => $object_url,
'image[0][url]' => $og_image, // Possible to upload more than one user gen image e.g. image[1][url]
'image[0][user_generated]' => 'true',
//'message' => 'Made on myUrl http://www.myUrl.com', // This shows above the large pic
);
try {
$post_id = $this->facebook->api("/me/myUrl:make", "post", $args);
print_r($post_id);
}
catch (Exception $e)
{
print_r($e);
}
}
To the right of where you added your OG actions in the App console there will be a link that says "Get Code". This will show you the information you need to include.
In your case, you should have a parameter in your args which is collection which contains the URL of the page containing the OG markup for your photo.
You can find this markup by clicking on the "Get Code" link next to the collection object you created in the app console.
Update
Open graph works by adding meta tags to the head of an accessible web page. You need to add the colleation meta to some page and then in the collection parameter in the request you're making, add the URL of the page.

Adding a tab to a fan page does not work... error: (#210) Subject must be a page

I'm trying to add a tab to a fanpage using the graph api/PHP SDK and I'm receiving an error :
(#210) Subject must be a page I've tried using both the user access_token AND the page access_token but neither work. I've tried using the page id of numerous accounts and still no go. Here is my code:
<?php
$path="/PAGE_ID/tabs/";
$access_token="ACCESS_TOKEN";
$params = array(
'app_id' => "APP_ID",
'access_token' => $access_token
);
try{
$install = $facebook->api($path, "POST", $params);
}catch (FacebookApiException $o){
print_r($o);
}
?>
And here is the error I get:
FacebookApiException Object
(
[result:protected] => Array
(
[error] => Array
(
[message] => (#210) Subject must be a page.
[type] => OAuthException
)
)
[message:protected] => (#210) Subject must be a page.
[string:Exception:private] =>
[code:protected] => 0
Thanks for any help you can provide!
If you are not limited to using the API to add your application to your page then you can follow the instructions provided by Facebook at this link :
https://developers.facebook.com/docs/reference/dialogs/add_to_page/
Essentially you can use a dialog ( see the link above ) or this direct URL to add tab apps to your page :
https://www.facebook.com/dialog/pagetab?app_id=YOUR_APP_ID&display=popup&next=YOUR_URL
Dont forget to substitute APP_ID for your app id and next for a different URL
API Call is atm bugged: https://developers.connect.facebook.com/bugs/149252845187252?browse=search_4f31da351c4870e34879109
But here is a solution for JS: OAuthException "(#210) Subject must be a page." - just do not use the library and do your own call.
I did it with PHP:
<?php
$url = 'https://graph.facebook.com/<PAGE ID>/tabs?app_id=<APP ID>&method=POST&access_token=<PAGE ACCESS TOKEN>&callback=test';
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
?>
Echo value should be something like "test(true)".