twinfield API integration with laravel - php

Twinfield is an online financial accounting software package for small and medium enterprises, produced and maintained by Twinfield International, based in The Netherlands. It is used by over 15,000 subscribers in 20 countries.
I want to integrate its API. I have install laravel and create some basic API, but its huge. How and where the integration example links? Please help me.

This is not the full code but gives you the login for the twinfield. I am also stuck because many libraries are given for twinfield but not give any sample code for it. There is no document provide for PHP integration. I am very disappointed with twinfield. Even if you have test account and it will disable than it will permanent disable. Here the jsonresponse is custom made so you can call only $e->getMessage() if you have any error related it.
public function login(\Illuminate\Http\Request $request){
$user = $request->input('user');
$password = $request->input('password');
$org = $request->input('organisation');
$params = array(
'user' => $user,
'password' => $password,
'organisation' => $org
);
// login => Set the param array and send to the logon
try
{
$session = new \SoapClient("https://login.twinfield.com/webservices/session.asmx?wsdl", array('trace' => 1));
$result = $session->logon($params);
// echo '<pre>';print_r($result);
$cluster = $result->cluster;
$qq = new domDocument();
$qq->loadXML($session->__getLastResponse());
$sessionID = $qq->getElementsByTagName('SessionID')->item(0)->textContent;
//echo $sessionID;
$newurl = $cluster . '/webservices/processxml.asmx?wsdl';
try
{
$client = new \SoapClient($newurl);
$data = new \SoapHeader('http://www.twinfield.com/', 'Header', array('SessionID'=> $sessionID));
$jsonResponse = JsonResponse::success($data);
}
catch (SoapFault $e)
{
$jsonResponse = empty($e->getMessage()) ? JsonResponse::error(class_basename($e)) : JsonResponse::error($e->getMessage());
}
}
catch (SoapFault $e)
{
$jsonResponse = empty($e->getMessage()) ? JsonResponse::error(class_basename($e)) : JsonResponse::error($e->getMessage());
}
return $jsonResponse;
}
Some code are given in this link too. You will integrate it via https://github.com/php-twinfield/twinfield but you have to work a lot. I am also working on it, if anything you need plz let me know.

Related

Are all existing endpoints listed in documentation really still working for v4.9? (i.e. those not replaced by v1 so far)

I have tried using old v4.9 endpoints that haven't been replaced by v1 so far such as:
https://developers.google.com/my-business/reference/rest/v4/accounts.locations/reportInsights
https://developers.google.com/my-business/reference/rest/v4/accounts.locations.reviews
However, none of these endpoints work anymore.
I am using PHP client that had these endpoints missing, but using the official v4.9 library listed here: https://developers.google.com/my-business/samples/previousVersions I have been able to reach some of the old endpoints such as reviews.
However they no longer return any data or data object is empty.
Anyone has experienced similar issues?
The v4.9 (not yet deprecated) endpoints such as reviews, insights etc. are working, but the official library is broken and botched.
I had to code a replacement using Guzzle client reaching to the endpoints directly instead. So you need to code the API library yourself from scratch for these v4.9 endpoints as the official library does not work.
How to fetch reviews:
public static function listReviews($client, $params, $account, $location)
{
$response = $client->authorize()->get('https://mybusiness.googleapis.com/v4/' . $account . '/' . $location . '/reviews', ['query' => $params]);
return json_decode((string) $response->getBody(), false);
}
How to fetch insights:
/** v4.9 working 02/2022 **/
public static function reportInsights($client, $params, $account)
{
try {
$response = $client->authorize()->post('https://mybusiness.googleapis.com/v4/' . $account . '/locations:reportInsights', [
\GuzzleHttp\RequestOptions::JSON => $params,
]);
} catch (\GuzzleHttp\Exception\RequestException $ex) {
return $ex->getResponse()->getBody()->getContents();
}
return json_decode((string) $response->getBody(), false);
}
How to prepare payload for insights:
$params = new \stdClass();
$params->locationNames = $account->name . '/' . $location->name;
$time_range = new \stdClass();
$time_range->startTime = Carbon::parse('3 days ago 00:00:00')->toISOString();
$time_range->endTime = Carbon::parse('2 days ago 00:00:00')->toISOString();
if ($force == 'complete') {
$time_range->startTime = Carbon::parse('17 months ago 00:00:00')->toIso8601ZuluString();
$time_range->endTime = Carbon::parse('3 days ago 00:00:00')->toIso8601ZuluString();
}
$params->basicRequest = new \stdClass();
$params->basicRequest->timeRange = $time_range;
$params->basicRequest->metricRequests = new \stdClass();
$metric_request = new \stdClass();
$metric_request->metric = 'ALL';
$metric_request->options = ['AGGREGATED_DAILY'];
$params->basicRequest->metricRequests = [
$metric_request,
];
Note: if you are getting empty insights response, you have to check verification using new v1 API call such as:
$verifications = \Google_Service_MyBusinessVerifications($client)->locations_verifications->listLocationsVerifications($location->getName());
$verification = '0';
if ($verifications->getVerifications()) {
$verification = $verifications->getVerifications()[0]->getState();
}
Using official API client with an existing token (needs to be fetched via OAuth2):
$provider = new GoogleClientServiceProvider(true);
$client = $provider->initializeClient($known_token, ['https://www.googleapis.com/auth/plus.business.manage', 'https://www.googleapis.com/auth/drive']);

PHP + Web Services

I'm struggling to get a web service to work which we are using to integrate with a software package from Civica. Unfortunately they have sent us code in visual basic which we don't use here and I'm struggling to "translate" the visual basic into PHP.
So here's the code I have so far:
error_reporting(E_ALL);
$client = new SoapClient('https://xxx/cx/WebService/WSTokenService?
singleWsdl');
var_dump($client->__getFunctions());
The above works and I can see the functions. It's the next bit I can't get to work:
$request_param = array('Password' => 'xxx', 'UserName' => 'yyy');
try
{
$request = $client ->GetUserWSToken($request_param);
$result = $request ->GetUserWSTokenResult;
print_r($result);
}
catch (Exception $e)
{
echo "<P><P>Exception Error!";
echo $e->getMessage();
}
When I run the above code I get an error message "Exception Error!GetUserWSToken has service faults". I also get another error "Object reference not set to an instance of an object".
The visual basic code we've been sent by the package company to use is:
Dim tokenClient As New TokenService.WSTokenServiceClient
Dim tokenreq As New TokenService.SecurityTokenRequest
tokenreq.UserName = "usernamehere"
tokenreq.Password = "passwordhere"
Dim token = tokenClient.GetUserWSToken(tokenreq)
Does anyone know how to translate the visual basic above into what I need to do for PHP?

google analytics API implementation for tracking a specific user activities in php

I'm developing an e-commerce student project using php (laravel framework), I have found lots of tutorials about using google analytics, but very rarely about how to retrieve data to my web site using APIs. I have the following questions:
how to retrieve all data from google analytics to my web site using API.
how to retrieve all data of UserID view? because I want to get all data about a specific user to know what is he/she (browser, language, country, Os .... etc) to use it to personalize my web site.
please any idea or help will be appreciated, I'm run out of time, people help
below is my API code that I'm using :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class HomeController extends Controller
{
public function getAnalyticsSummary(Request $request){
$from_date = date("Y-m-d", strtotime($request->get('from_date',"7 days ago")));
$to_date = date("Y-m-d",strtotime($request->get('to_date',$request->get('from_date','today')))) ;
$gAData = $this->gASummary($from_date,$to_date) ;
return $gAData;
}
//to get the summary of google analytics.
private function gASummary($date_from,$date_to) {
$service_account_email = 'get-data-analytics#analytics-api-project-148820.iam.gserviceaccount.com';
// Create and configure a new client object.
$client = new \Google_Client();
$client->setApplicationName("any name");
$analytics = new \Google_Service_Analytics($client);
$cred = new \Google_Auth_AssertionCredentials(
$service_account_email,
array(\Google_Service_Analytics::ANALYTICS_READONLY),
"-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCrzw1R6ca16zYQ\n3ozuTlNVbvNWDPODW6NVrnny08V4ycd/ugvTQeU3EKno6mJ8iXNJ/3GXOz52iaRd\nGRKbfrPomK7gt6+F7EHVdpTfbc/u7TIJi5NbYzXS4jIXhIJhB4bGjzsnTGTY/6pF\nFmW/wgX2Y6n31EWyz2q5MiZDC5lEPrmNk/gOgWOyRHCVNHtBcyFdA3+w2or6ix5l\nrKlCwUkkzKAPb4OSvfDMz8o+h6r433E4+6MMHE/mf53CkX1DbDZIlZbUntYLoh19\n0oxKCufjfFEKqzxgTZxIbG5rK7jdrOFLuQwnaoKkUT0HAQTGnGoYrABo9HGjlgwg\n7rHzh+OzAgMBAAECggEBAKcRq8E41Ft4w1V6JI9jqRON1aCa7X2R8e3SwZFJL2C6\nzn28+9zN2khGswLkUSsLOgn+FYZbPO1mAWfqhragafBH8N5ioJNZX9dk/XWbQjTz\ngNHZYUzf16oe/VjzKRmTiRKym3ImjnaZfwi5s+3ZjZS/67ssNy6fFgfK5XwS3lKG\nFzAZYgCMyJIz8Cz9mHAHKmQELH29xiPNDSSCuAbScptOdNJvBB9Vvpu5b+/LtdWI\naBYLuZgMOSNgJiQFBjj/+RY5yBi9pL5aHYGHJJZnWp1CbxRQIN+xe5jBbpHZ6PWH\nUjoCfMkM+IWBNjlKOWCC/APFpGuDqYMRuHfakPvWIXECgYEA4otETO0hR00SceKt\nGXYtIX6ZfdK6K87EPTFofMXAvcH7CWU3Tr2+3pI/DWUD1pPEEfsOZpaS5Ry37IrQ\nVmhkS2j5QxYJ+NfEvjc17rdJuuwJeCeELDFNxsTvhk7yK6y75F7BFQH/dIcc7MYg\nTL11B340TpPlJtulnxLTW7G3nFkCgYEAwiXfGnpmuPE1yyGdux4mY1Eyp6ZmxC0o\nb+DIBqRRlwY23m7pv3g7a0GAqLIFaW7c/1iVlyoDg24eZ8YtSehtR0B5LEiExBaY\n7UpkqHosvCqgCH94O/Mas+DUv9Sfqy82geEagB65Cf+uLr/ixNbKiK12G29O/V7M\nCar/=========================================================================================================================================================================================================================================x/NCNpGaW7zKvAoGAffG7PqgXYNtqQ3MavgLF\nKtQFMzT65kI5AfXPpyzgBDKr84lhvdUddvK/FZg/mIuoLRLSgnYPnAv3s5yhleZ5\n7LGyo5fXXH7XUm2nNt+XZoV1rt6y+WgZi103M+fuv3GXYBdbOonPHopRzw3uzLIA\n9ovyAV95jOu9ybk4YgQXm5I=\n-----END PRIVATE KEY-----\n"
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$optParams = [
'dimensions' => 'ga:date',
'sort'=>'-ga:date'
] ;
$results = $analytics->data_ga->get(
'ga:133119102',
$date_from,
$date_to,
/*'ga:sessions,ga:users,ga:pageviews,ga:bounceRate,ga:hits,ga:avgSessionDuration',*/
'ga:bounceRate',
$optParams
);
$rows = $results->getRows();
$rows_re_align = [] ;
foreach($rows as $key=>$row) {
foreach($row as $k=>$d) {
$rows_re_align[$k][$key] = $d ;
}
}
$optParams = array(
'dimensions' => 'rt:medium'
);
try {
$results1 = $analytics->data_realtime->get(
'ga:132964552',
'rt:activeUsers',
$optParams);
// Success.
} catch (apiServiceException $e) {
// Handle API service exceptions.
$error = $e->getMessage();
}
$active_users = $results1->totalsForAllResults ;
return view('myGoogle.getGoogle', [
'data'=> $rows_re_align ,
/* 'summary'=>$results->getTotalsForAllResults(),*/
/* 'active_users'=>$active_users['rt:activeUsers']*/
]) ;
}
}
User id is used for internal processing of users across multiple seasons. Example you have a user who uses your website and your moblie application this would technically be two sessions. However if you pass the User id you have for this user when they are logged into there account on your system. You are telling Google analytics this is the same person.
User Id is not something however that you can extract out of the API its used mainly for internal processing. Assuming that your user id is a non user specific value you can also set it as a custom dimension which you can then extract out using the API.

Why do I get 404 Error when using Google Classroom API?

I am writing an app in PHP which will connect to my domains's Google Classroom. However I get the following error when I try to do anything with the Google Classroom API:
Message: Error calling GET https://www.googleapis.com/v1/courses?pageSize=100: (404) Not Found
My code so far:
$scopes = array(
'https://www.googleapis.com/auth/classroom.courses',
'https://www.googleapis.com/auth/classroom.courses.readonly',
'https://www.googleapis.com/auth/classroom.rosters',
'https://www.googleapis.com/auth/classroom.rosters.readonly'
);
$gServiceEmail = "random#developer.gserviceaccount.com";
$gServiceKey = file_get_contents("../path/to/cert.p12");
$client = new Google_Client();
$gAuth = new Google_Auth_AssertionCredentials(
$gServiceEmail,
$scopes,
$gServiceKey
);
$gAuth->sub = "user#mydomain.com";
$client->setAssertionCredentials($gAuth);
$service = new Google_Service_Classroom($client);
$results = $service->courses->listCourses();
I have enabled the scopes in the API Settings in the Google Admin Console for the service account and enabled the api in the developer console. Where am I going wrong?
I think your endpoint is wrong according to the documentation of Classroom API. Try changing it to https://classroom.googleapis.com
sample request:
GET https://classroom.googleapis.com/v1/courses?pageSize=100&key={YOUR_API_KEY}
Course with id is not found.
For a list of courses, use the courses.list(), as shown in the following sample.
$client = getClient();
$service = new Google_Service_Classroom($client);
// Print the first 10 courses the user has access to.
$optParams = array(
'pageSize' => 10
);
$results = $service->courses->listCourses($optParams);
if (count($results->getCourses()) == 0) {
print "No courses found.\n";
} else {
print "Courses:\n";
foreach ($results->getCourses() as $course) {
printf("%s (%s)\n", $course->getName(), $course->getId());
}
}
References:
https://developers.google.com/classroom/quickstart/php?hl=en
https://developers.google.com/classroom/guides/manage-courses?hl=en

Displaying posts from owned facebook with the PHP SDK

So I admittedly am quite new to the facebook Graph api, but what I want to do feels like it should be doable.
All I want to do is display posts from a facebook page that is owned by me on a website.
Now I should say that I have achieved this with the api and the php sdk already, but its all of the access token stuff that is perplexing me, I just want a permanent access token so that I don't have to renew it in anyway.
Any help would be much appreciated
Just in case anyone landed on this question and was looking for direction on this subject too
$client = array(
"id" => {APP_ID},
"secret" => {APP_SECRET},
"token" => {ACCESS_TOKEN}, // Generated from the graph api explorer, with the 'manage_posts' extended permission ticked
"page" => {PAGE_ID}
);
FacebookSession::setDefaultApplication($client['id'], $client['secret']);
$session = new FacebookSession($client['token']);
try
{
$response = (new FacebookRequest($session, 'GET', '/oauth/access_token?grant_type=fb_exchange_token&client_id='.$client['id'].'&client_secret='.$client['secret'].'&fb_exchange_token='.$client['token']))->execute();
$results = $response->getGraphObject();
$data = $results->asArray();
$token = $data['access_token'];
$response = (new FacebookRequest($session, 'GET', '/'.$client['page'].'?fields=access_token'))->execute();
$results = $response->getGraphObject();
$data = $results->asArray();
echo "Access Token: ".$data['access_token']; // this is your never expiring access token
}
catch (FacebookRequestException $e) {
print_r($e);
}
catch (\Exception $e) {
print_r($e);
}
Obviously I do not recommend doing this in any form of production environment, but if you are in a local environment and just need the access token, feel free to use this to find out the access token.

Categories