Facebook Instant Articles PHP SDK debug line - php

I'm trying to transform my html page to Facebook Instant Articles format.
I keep getting on the screen
"DEBUG - =========================== DEBUG -"
When Im calling "$transformer->transformString" or "
$transformer->transform( $header, $document );"
Why that? I don't echo anything.
(This isn't wordpress site)
$header =
Header::create()
->withPublishTime(
Time::create( Time::PUBLISHED )->withDatetime(
\DateTime::createFromFormat(
'j-M-Y G:i:s',
date('j-M-Y G:i:s', strtotime($published_date))
))
)
->withModifyTime(
Time::create( Time::MODIFIED )->withDatetime(
\DateTime::createFromFormat(
'j-M-Y G:i:s',
date('j-M-Y G:i:s', strtotime($last_modified_date))
))
);
// Loads the rules configuration file
$rules_file_content = file_get_contents("rules-configuration.json", true);
// Load html content from a file.
//$content = file_get_contents("sample-html.html", true);
$content = get_the_content();
// Create a transformer object and load the rules
$transformer = new Transformer();
$transformer->loadRules($rules_file_content);
$document = new DOMDocument();
libxml_use_internal_errors(true);
$document->loadHTML( '<?xml encoding="' . $charset . '" ?><h1>' . $title . '</h1>' );
libxml_use_internal_errors(false);
$transformer->transform( $header, $document );
if($subtitle) {
$header->withSubTitle ($subtitle);
}
if ( $kicker ) {
$header->withKicker( $kicker );
}
define( 'IA_PLUGIN_VERSION', '4.0.5' );
$instant_article =
InstantArticle::create()
->withCanonicalUrl( $cannonical_link )
->withHeader( $header )
->addMetaProperty( 'op:generator:application', 'facebook-instant-articles' )
->addMetaProperty( 'op:generator:application:version', IA_PLUGIN_VERSION );
$instant_article->withStyle( 'default' );
$transformer->transformString( $instant_article, $content, $charset );
// Instantiate an API client
$client = Client::create(
$APP_ID,
$APP_SECRET,
$ACCESS_TOKEN,
$PAGE_ID,
$is_development
);
// Import the article
try {
$client->importArticle($instant_article, $is_published);
} catch (Exception $e) {
echo 'Could not import the article: '.$e->getMessage();
}

Add these lines :)
\Logger::configure(
[
'rootLogger' => [
'appenders' => ['facebook-instantarticles-traverser']
],
'appenders' => [
'facebook-instantarticles-traverser' => [
'class' => 'LoggerAppenderConsole',
'threshold' => 'INFO',
'layout' => [
'class' => 'LoggerLayoutSimple'
]
]
]
]);
Source: https://github.com/facebook/facebook-instant-articles-sdk-extensions-in-php/blob/master/examples/quiet_logger.php

Related

404 Error connecting to the API (https://developer.api.autodesk.com/modelderivative/v2/designdata/job) when i use php-client-forge autodesk api

i want to use the autodesk forge viewer api in my php application in order to view ifc files so i used the forge-php-client sdk.everything works fine but the translating job doesn't and i'm getting this error : [404] Error connecting to the API (https://developer.api.autodesk.com/modelderivative/v2/designdata/job
here the code:
/step1
Configuration::getDefaultConfiguration()
->setClientId('xxxxxxxxxxxxxxxxxxxxxx')
->setClientSecret('xxxxxxxxxxxxxxxxxx');
$twoLeggedAuth = new TwoLeggedAuth();
$twoLeggedAuth->setScopes( [ 'bucket:create' ] );
$twoLeggedAuth->fetchToken();
$tokenInfo = [
'accessToken' => $twoLeggedAuth->getAccessToken(),
'expiry' => time() + $twoLeggedAuth->getExpiresIn(),
];
//step2
$twoLeggedAuth->setScopes( [ 'bucket:create' ] );
$twoLeggedAuth->fetchToken();
$apiInstance = new BucketsApi( $twoLeggedAuth );
$bucket_info = array(
'bucket_key' => 'nebnibim5'.time(),
'policy_key' => 'transient'
);
$post_buckets = new PostBucketsPayload( $bucket_info );
$result = $apiInstance->createBucket( $post_buckets, null );
$twoLeggedAuth = new TwoLeggedAuth();
$twoLeggedAuth->setScopes( [ 'data:write' ] );
$twoLeggedAuth->fetchToken();
$apiInstance = new ObjectsApi( $twoLeggedAuth );
$bucket_key = $bucket_info['bucket_key'];
$filename = 'C:\wamp\www\nebnibim\storage\app\bibliothequeObjets\user69\13111006_IFCR2_Geo_Openings_1.ifc ';
$body = $filename;
$file = new SplFileObject( $body );
$content_length = $file->getSize();
$object_name = $file->getFilename();
//try {
$result2 = $apiInstance->uploadObject( $bucket_key, $object_name, $content_length, $body, null, null );
//step4
$urn = 'urn:adsk.objects:os.object:nebnibim51548575979/13111006_IFCR2_Geo_Openings_1.ifc';
$base64Urn = rtrim( strtr( base64_encode( $urn ), '+/', '-_' ), '=' );
$twoLeggedAuth->setScopes( [ 'data:read', 'data:write' ] );
$twoLeggedAuth->fetchToken();
$apiInstance2 = new DerivativesApi( $twoLeggedAuth );
$jobInput = array(
'urn' => 'dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6bmVibmliaW01MTU0ODU3NTk3OS8xMzExMTAwNl9JRkNSMl9HZW9fT3BlbmluZ3NfMS5pZmM'
);
$jobPayloadInput = new JobPayloadInput( $jobInput );
$jobOutputItem = array(
'type' => 'svf',
'views' => array( '2d', '3d' )
);
$jobPayloadItem = new JobPayloadItem( $jobOutputItem );
$jobOutput = [
'formats' => array( $jobPayloadItem )
];
$jobPayloadOutput = new JobPayloadOutput( $jobOutput );
$job = new JobPayload();
$job->setInput( $jobPayloadInput );
$job->setOutput( $jobPayloadOutput );
$x_ads_force = false;
$resultat= $apiInstance2->translate( $job,$x_ads_force );
Looks like you are still uploading to a bucket named after system time, only to call job on a hard coded urn pointing an object that’s uploaded to another bucket earlier - this would always result in a 404 error as the urn is incorrect.
Follow the code sample and docs here to fetch a list of the contents of an existing bucket, verify the objects really exist at the time of query in your bucket, take the objectId returned that’s guaranteed to be current and correct, and go from there.
You will need to upload the files again after 24 hours as the bucket you created is transient. See here for more on this - and that should be the reason for the error we are seeing now.

How do you create an API that connects a form on a site to a CRM using PHP

I'm rather new to Gravity Forms and building API's using PHP. I need to create a script that whenever a Gravity Form is completed the API sends this as JSON data to a POST URL. They gave me the security key name and value, how do I do this using PHP? Do I need Jquery and/or AJAX?
EDIT:
This is what I have so far but I have no idea if I'm on the right path: (I omitted some fields with "X's" due to obvious potential security reasons)
<?php
function calculate_signature( $string, $private_key ) {
$hash = hash_hmac( 'sha1', $string, $private_key, true );
$sig = rawurlencode( base64_encode( $hash ) );
return $sig;
}
//set API keys
$api_key = 'XXXXXXX';
$private_key = 'XXXXXXXXXX';
//set route
$route = '/XXXXXXX.php';
//creating request URL
$expires = strtotime( '+60 mins' );
$string_to_sign = sprintf( '%s:%s:%s:%s', $api_key, 'POST', $route, $expires );
$sig = calculate_signature( $string_to_sign, $private_key );
$url = 'XXXXXXX.com' . $route . '?api_key=' . $api_key . '&signature=' . $sig . '&expires=' . $expires;
// $form = array(
// array(
// 'title' => 'API Generated Form',
// 'description' => 'This is the description for the form generated by the API',
// 'labelPlacement' => 'top_label',
// 'button' => array(
// 'type' => 'text'
// ),
// 'confirmations' => array(
// array(
// 'id' => 0,
// 'name' => 'Default Confirmation',
// 'type' => 'message',
// 'message' => 'Thanks for contacting us! We will get in touch with you shortly.',
// 'isDefault' => true,
// ),
// ),
// 'fields' => array(
// array(
// 'id' => '1',
// 'label' => 'My Text',
// 'type' => 'text'
// )
// ),
// ),
// );
$form = array(
'age' => NULL
);
//json encode array
$form_json = json_encode( $form );
//retrieve data
$response = wp_remote_request( $url, array( 'method' => 'POST', 'body' => $form_json ) );
if ( wp_remote_retrieve_response_code( $response ) != 200 || ( empty( wp_remote_retrieve_body( $response ) ) ) ){
//http request failed
die( 'There was an error attempting to access the API.' );
}
//result is in the response "body" and is json encoded.
$body = json_decode( wp_remote_retrieve_body( $response ), true );
if( $body['status'] > 202 ){
$error = $body['response'];
//form insert failed, get error information
$error_code = $error['code'];
$error_message = $error['message'];
$error_data = isset( $error['data'] ) ? $error['data'] : '';
$status = "Code: {$error_code}. Message: {$error_message}. Data: {$error_data}.";
die( "Could not post forms. {$status}" );
}
$form_id = $body['response'][0];
echo 'The following form id was created: ' . $form_id . '</br>';
?>

how to integrate Assently api for e-signature transaction in PHP

In my wp project, I am using Assently for e-signature implementation. Though I have an account and created a pdf form file to be filled by the user I just am not able to proceed a bit. I am finding documentation not clear.
Also, I am not clear about what needs to be done so that the user will be shown form to process the transaction.
So, any help/suggestions to proceed forward is appreciated.
I have tried the following based on assently-laravel. But it's asking me to login. What is an error here?
Code:
define('ASSENTLY_DEBUG', true);
define('ASSENTLY_KEY', 'key');
define('ASSENTLY_SECRET', 'secret-generated');
include_once('assently/Assently.php');
$assently = new Assently();
$assently->authenticate(ASSENTLY_KEY, ASSENTLY_SECRET);
$url = 'https://test.assently.com/api/v2/createcasefromtemplate';
$default = array(
'Id' => '5a0e0869-' . rand(1111, 9999) . '-4b79-' . rand(1111, 9999) . '-466ea5cca5ce'
);
$data = array(
'auth' => $assently->auth(),
'templateId' => '0e004e2b-b192-4ce2-8f47-d7a4576d7df6',
'newCaseId' => '5a0e0869-' . rand(1111, 9999) . '-4b79-' . rand(1111, 9999) . '-466ea5cca5ce',
'agentUsername' => ''
);
$data = array(
'json' => $data
);
$options = array(
'http' => array(
'header' => "Content-type: application/json; charset=utf-8\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
echo '<pre>';
print_r($result);
die;
create this class inside assently folder
use Assently\AssentlyCase;
use Exception;
class CustomAssentlyCase extends AssentlyCase
{
public function createFromTemplate($data)
{
$default = [
'newCaseId' => '5a0e0869-'.rand(1111, 9999).'-4b79-'.rand(1111, 9999).'-466ea5cca5ce'
];
$json = array_merge($default, $data);
try{
$response = $this->client->post($this->url('createcasefromtemplate'), [
'auth' => $this->assently->auth(),
'json' => $json
]);
}catch(Exception $e){
print_r($e->getMessage());
}
return $response;
}
}
Use
define('ASSENTLY_DEBUG', true);
define('ASSENTLY_KEY', 'key');
define('ASSENTLY_SECRET', 'secret-generated');
include_once('assently/Assently.php');
include_once('assently/CustomAssentlyCase.php');
$assently = new Assently();
$assently->authenticate(ASSENTLY_KEY, ASSENTLY_SECRET);
$data = array(
'templateId' => '0e004e2b-b192-4ce2-8f47-d7a4576d7df6',
'newCaseId' => '5a0e0869-'.rand(1111, 9999).'-4b79-'.rand(1111, 9999).'-466ea5cca5ce',
'agentUsername' => 'agentUsername' // PUT your agent username here it is required
);
$customAssentlyCase = new CustomAssentlyCase($assently);
$result = $customAssentlyCase->createFromTemplate($data);
print_r($result);
Try this, though not tested but should work. Good luck.

REST API connected to Facebook

I'm currently developing a REST API on my webserver for handling calls towards a Facebook application. This way I can check if the user has a valid license in our license database before allowing him/her to post to Facebook.
I'm using two separate calls at the moment, one to authorize the client with Facebook and store his/her access token in our license database. And another to actually publish to Facebook (and also other social platforms).
The Authorization seems to work. But the publishing always returns
{
"success": false,
"error": {
"message": "(#200) User must have accepted TOS",
"type": "FacebookRequestAppException",
"code": 200
}
}
I am currently working with a development app (on Facebook), without the proper permissions submitted, would this be the issue? And if so, how can I test it if I'm not allowed to use it?
The PHP code that triggers the Exception:
try {
$app = ( new FacebookRequest($app_session, 'POST', $post_url, array( 'appsecret_proof' => $appsecret_proof ) ) )->execute()->getGraphObject();
$output = array_merge( array( 'success' => true ), $output );
} catch(FacebookRequestException $e) {
$output = array_merge( $output, array( 'success' => false, 'error' => array( 'message' => $e->getMessage(), 'type'=> 'FacebookRequestAppException', 'code' => $e->getCode() ) ) );
}
Edit:
The call:
$app_id = '1503912413161954';
$app_secret = '<app_secret_censored>';
$user_access_token = (string)$this->getIdentity()->facebook_token;
$app_access_token = (string)$this->getIdentity()->facebook_app_token;
$license_id = (int)$this->getIdentity()->license_id;
$user_account_type = (string)$this->getIdentity()->user_account_type;
$redirect_url = 'http://api.example.com/authorize';
include 'lib/fb_authorize.php';
The authorization code - have in mind that it's not yet complete, and that I'm using Yii Framwork as well to add connectivity to our database:
<?php
$http_session = new CHttpSession;
$http_session->setTimeout(60);
$http_session->setSessionName('fb_session');
$http_session->open();
require( 'vendor/autoload.php' );
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphUser;
use Facebook\FacebookHttpable;
use Facebook\FacebookCurl;
use Facebook\FacebookCurlHttpClient;
FacebookSession::setDefaultApplication($app_id, $app_secret);
$helper = new FacebookRedirectLoginHelper($redirect_url, $app_id, $app_secret);
if ( isset( $user_access_token ) ) {
$user_session = new FacebookSession( $user_access_token );
try {
if ( !$user_session->validate() ) {
$user_session = null;
}
} catch ( Exception $e ) {
$user_session = null;
$output = array_merge( $output, array( 'success' => false, 'error' => array( 'message' => $e->getMessage(), 'type'=> 'ExxicaUserSessionException', 'code' => $e->getCode() ) ) );
}
} else {
try {
$user_session = $helper->getSessionFromRedirect();
} catch( Exception $e ) {
$user_session = null;
$output = array_merge( $output, array( 'success' => false, 'error' => array( 'message' => $e->getMessage(), 'type'=> 'ExxicaUserSessionException', 'code' => $e->getCode() ) ) );
}
}
if( isset( $user_session ) ) {
$appsecret_proof= hash_hmac('sha256', $user_session->getToken(), $app_secret);
if( isset( $http_session['getpages'] ) ) {
try {
// Get Page ID
$user = ( new FacebookRequest($user_session, 'GET', '/me/accounts', array( 'appsecret_proof' => $appsecret_proof ) ) )->execute()->getGraphObject();
$output = array( 'success' => true, 'user' => $user );
} catch(FacebookRequestException $e) {
$output = array( 'success' => false, 'error' => array( 'message' => $e->getMessage(), 'type'=> 'FacebookRequestUserException', 'code' => $e->getCode() ) );
}
}
try {
$app_session = new FacebookSession( $app_access_token );
} catch ( Exception $e ) {
$app_session = null;
$output = array_merge( $output, array( 'success' => false, 'error' => array( 'message' => $e->getMessage(), 'type'=> 'ExxicaAppSessionException', 'code' => $e->getCode() ) ) );
}
$c = new CDbCriteria();
$c->compare( 'id', $license_id );
$l = _Licenses::model()->find( $c );
$l->facebook_token = $user_session->getToken();
$l->facebook_app_token = $app_session->getToken();
$l->save();
$output = array_merge( $output, array( 'success' => true, 'user_token' => $l->facebook_token ) );
} else {
header( 'Location: '.$helper->getLoginUrl( array( 'manage_pages','publish_actions','public_profile' ) ) );
}
?>

Pushwoosh Phonegap notifications PHP method set tags

I am not a professional programmer. I manage with PHP and Javascript, but I am having a hard time converting Pushwoosh methods to functional PHP or Javascript. This is the method that I need help converting:
Method /setTags
Set tags values for device
Request:
{
"request":{
"application":"DEAD0-BEEF0",
"hwid": 'device hardware id',
"tags": {
"tag1": "string value",
"tag2": 42,
"tag3": "string",
"tag4": 3.14
}
}
}
This is how they post their methods. Any help with this?
I wrote a PHP to setTags but I could not verify it yet as I am still working on retrieving the Token. I have a question on that on this link:
Phonegap/Pushwoosh Android retrieving Device id / Token
this is my PHP for setTags. Does this look right using JSON? (I am running late on my project!)
<?php
define('PW_AUTH', 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
define('PW_APPLICATION', 'xxxxxxxxxx');
define('HW_ID', 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
function doPostRequest($url, $data, $optional_headers = null) {
$params = array(
'http' => array(
'method' => 'POST',
'content' => $data
));
if ($optional_headers !== null)
$params['http']['header'] = $optional_headers;
$ctx = stream_context_create($params);
$fp = fopen($url, 'rb', false, $ctx);
if (!$fp)
throw new Exception("Problem with $url, $php_errmsg");
$response = #stream_get_contents($fp);
if ($response === false)
return false;
return $response;
}
function pwCall( $action, $data = array() ) {
$url = 'https://cp.pushwoosh.com/json/1.3/' . $action;
$json = json_encode( array( 'request' => $data ) );
$res = doPostRequest( $url, $json, 'Content-Type: application/json' );
print_r( #json_decode( $res, true ) );
}
pwCall( 'setTags', array(
'application' => PW_APPLICATION,
'auth' => PW_AUTH,
'hwid' => HW_ID,
'tags' => array(
array(
'tag1' => 'string value',
'tag2' => 42,
'tag3' => 'string',
'tag4' => 3.14
)
)
)
);
?>
you do not need to convert this JSON to send tags to Pushwoosh. It's being sent directly from the device to the Pushwoosh server.

Categories