/home/desid573/public_html/verde/xero/XeroOAuth-PHP-master
NameSizeModeActions
certs/-0755rm
lib/-0755rm
pdf/-0755rm
tests/-0755rm
.gitignore1420644editdlrm
.pdf803810644editdlrm
7320c944-101d-4f21-924f-5c49298ec5df.pdf803810644editdlrm
addBillingContact.php63780644editdlrm
addContact.php79900644editdlrm
addNewContact.php00644editdlrm
class.phpmailer.php800460644editdlrm
class.pop3.php103850644editdlrm
class.smtp.php245860644editdlrm
composer.json5560644editdlrm
error_log123872530644editdlrm
getInvoice.php79560644editdlrm
getInvoiceReturn.php79560644editdlrm
index.php5000644editdlrm
invoiceRetrieve.php24510644editdlrm
invoiceSend.php45410644editdlrm
license.txt10550644editdlrm
partner.php41000644editdlrm
private.php16220644editdlrm
public.php42520644editdlrm
README.md72660644editdlrm
webhook.php160240644editdlrm
_config.php22810644editdlrm
Edit: /home/desid573/public_html/verde/xero/XeroOAuth-PHP-master/webhook.php (16024B)
connect_error); $qcon=mysqli_connect($dbhost, $dbuser, $dbpass, $dbname); $yourHash = base64_encode(hash_hmac('sha256', $payload, $webhookKey, true)); error_log($payload); $payload = json_decode($payload, true); $isEqual = false; if ($yourHash === $_SERVER['HTTP_X_XERO_SIGNATURE']) { http_response_code(200); $isEqual = true; } else { http_response_code(401); } //require 'lib/XeroOAuth.php'; require '../../google/google-api-php-client-2.2.1/gmailSendInvoice.php'; // define ( 'BASE_PATH', dirname(__FILE__) ); // define ( "XRO_APP_TYPE", "Private" ); // define ( "OAUTH_CALLBACK", "oob" ); // $useragent = "appConnect"; // $signatures = array ( // 'consumer_key' => '51DABYIYXXBZDHAZTVAXBX6TU7T3AT', // 'shared_secret' => 'RE390CCDJV1VD29SUZI9VBWTVUV7VF', // // API versions // 'core_version' => '2.0', // 'payroll_version' => '1.0', // 'file_version' => '1.0' // ); // if (XRO_APP_TYPE == "Private" || XRO_APP_TYPE == "Partner") { // $signatures ['rsa_private_key'] = BASE_PATH . '/certs/privatekey.pem'; // $signatures ['rsa_public_key'] = BASE_PATH . '/certs/publickey.cer'; // } // $XeroOAuth = new XeroOAuth ( array_merge ( array ( // 'application_type' => XRO_APP_TYPE, // 'oauth_callback' => OAUTH_CALLBACK, // 'user_agent' => $useragent // ), $signatures ) ); // $initialCheck = $XeroOAuth->diagnostics (); // $checkErrors = count ( $initialCheck ); // if ($checkErrors > 0) { // // you could handle any config errors here, or keep on truckin if you like to live dangerously // foreach ( $initialCheck as $check ) { // error_log('Error: ' . $check); // } // } else { // $session = persistSession ( array ( // 'oauth_token' => $XeroOAuth->config ['consumer_key'], // 'oauth_token_secret' => $XeroOAuth->config ['shared_secret'], // 'oauth_session_handle' => '' // ) ); // $oauthSession = retrieveSession (); // } // $XeroOAuth->config ['access_token'] = $oauthSession ['oauth_token']; // $XeroOAuth->config ['access_token_secret'] = $oauthSession ['oauth_token_secret']; $sql = "SELECT `id`, `token`, `expires`, `tenant_id`, `refresh_token`, `id_token` FROM `desid573_eway_codes`.`xero_token` ORDER BY `id` DESC"; $result = $conn->query($sql); $storage = $result->fetch_assoc(); error_log(time()." > ".$storage["expires"]); $xeroTenantId = $storage["tenant_id"]; $token = $storage['token']; if(time() > $storage["expires"]) { $provider = new \League\OAuth2\Client\Provider\GenericProvider([ 'clientId' => '792F5D6E7E10404EA0BD0DA3CFF525BC', 'clientSecret' => '_w1yk8UQTp5QV9CzzDD4G3daZXjANQ40hQfyUZf91jUxemGF', 'redirectUri' => 'https://desidrivers.com.au/payment/xero-2/callback.php', 'urlAuthorize' => 'https://login.xero.com/identity/connect/authorize', 'urlAccessToken' => 'https://identity.xero.com/connect/token', 'urlResourceOwnerDetails' => 'https://api.xero.com/api.xro/2.0/Organisation' ]); $newAccessToken = $provider->getAccessToken('refresh_token', [ 'refresh_token' => $storage["refresh_token"] ]); $token = $newAccessToken->getToken(); $sql = "INSERT INTO `desid573_eway_codes`.`xero_token`(`id`, `token`, `expires`, `tenant_id`, `refresh_token`, `id_token`) VALUES (NULL,'".$newAccessToken->getToken()."',".$newAccessToken->getExpires().",'".$storage["tenant_id"]."','".$newAccessToken->getRefreshToken()."','".$newAccessToken->getValues()["id_token"]."')"; error_log($sql); $query = $conn->query($sql); if(!$query) { error_log($conn->error); } } error_log($xeroTenantId); $config = XeroAPI\XeroPHP\Configuration::getDefaultConfiguration()->setAccessToken($token); $config->setHost("https://api.xero.com/api.xro/2.0"); // $apiInstance = new XeroAPI\XeroPHP\Api\AccountingApi( // new GuzzleHttp\Client(), // $config // ); $endpoint = "Invoices"; $accountingApi = new XeroAPI\XeroPHP\Api\AccountingApi( new GuzzleHttp\Client(), $config ); //error_log($accountingApi); $apiResponse = $accountingApi->getInvoice($xeroTenantId, "5dee2610-2428-4b76-af62-7ce3bef32d25"); error_log("invoice ".json_encode($apiResponse, true)); $payload = $payload["events"]; $eventlog = array(); foreach($payload as $event) { error_log($event["eventCategory"]." ".$event["eventType"]); $invoice_id = $event["resourceId"]; if(array_search($invoice_id, $eventlog, true) === false) { array_push($eventlog, $invoice_id); $invoice = lookUpInvoice($xeroTenantId, $accountingApi, $invoice_id); if($event["eventCategory"] == "INVOICE" && $event["eventType"] == "CREATE" && $invoice->Type == "ACCREC") { //look up invoice if(!$invoice) { error_log("no invoice found"); } else { $name = $invoice->Contact->Name; $amount = "$".$invoice->Total; $type = $invoice->LineItems->LineItem[0]->ItemCode; if($invoice->AmountDue == "0.00") { $payment = "$".$invoice->Payments->Payment->Amount. " Paid"; } $string = "New ".$type." Invoice created for ".$name." ".$amount; if($invoice->AmountDue == "0.00") { $name = $invoice->Contact->Name; $type = $invoice->LineItems->LineItem[0]->ItemCode; $payment = "$".$invoice->Payments->Payment->Amount; $amount = "$".$invoice->Total; $invType = $invoice->Type; $string .= " - Paid ".$payment; sendToSlack($string); $email = $invoice->Contact->EmailAddress; error_log("Type: ".$invType); if($email != "" && $name != "cash" && $invType == "ACCREC") { //check if sent $query = "SELECT * FROM `desid573_eway_codes`.`customer_invoices_sent` WHERE `invoice_id` = '".$invoice_id."'"; $result = $conn->query($query); if($result->num_rows == 0) { $pdf = getPDF($xeroTenantId, $accountingApi,$invoice_id); if($pdf) { $mail = sendFromGmail($type, $invoice, $invoice_id); if($mail) { $query = "INSERT INTO `desid573_eway_codes`.`customer_invoices_sent`(`id`, `customer_name`, `invoice_amount`, `invoice_id`, `date_sent`) VALUES (NULL,'".$name."','".$amount."','".$invoice_id."',NOW())"; $result = $conn->query($query); if(!$result) { error_log("invoice add error ".$conn->error); } $string .= " Invoice Emailed"; } } } } } sendToSlack($string); $email = $invoice->Contact->EmailAddress; } } if($event["eventCategory"] == "INVOICE" && $event["eventType"] == "UPDATE") { if($invoice->AmountDue == "0.00") { $name = $invoice->Contact->Name; $type = $invoice->LineItems->LineItem[0]->ItemCode; $payment = "$".$invoice->Payments->Payment->Amount; $amount = "$".$invoice->Total; $string = $type." Invoice for ".$name." now paid ".$payment; $email = $invoice->Contact->EmailAddress; if($email != "" && $name != "cash" && $invoice["Type"] == "ACCREC") { //check if sent $query = "SELECT * FROM `desid573_eway_codes`.`customer_invoices_sent` WHERE `invoice_id` = '".$invoice_id."'"; $result = $conn->query($query); if($result->num_rows == 0) { $pdf = getPDF($invoice_id); if($pdf) { $mail = sendFromGmail($type, $invoice, $invoice_id); if($mail) { $query = "INSERT INTO `desid573_eway_codes`.`customer_invoices_sent`(`id`, `customer_name`, `invoice_amount`, `invoice_id`, `date_sent`) VALUES (NULL,'".$name."','".$amount."','".$invoice_id."',NOW())"; $result = $conn->query($query); if(!$result) { error_log("invoice add error ".$conn->error); } $string .= " Invoice Emailed"; } } } } sendToSlack($string); } } } } // Store information into file // Request Headers $filedata = sprintf( "%s %s %s\n\n---- Request headers ----\n", $_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI'], $_SERVER['SERVER_PROTOCOL'] ); foreach (getHeaderList() as $name => $value) { $filedata .= $name . ': ' . $value . "\n"; } // Request Body $filedata .= "\n---- Request body ----\n"; $filedata .= $payload . "\n"; // Signature key $filedata .= "\n---- Signature key ----"; $filedata .= "\nComputed signature key:\n"; $filedata .= $yourHash; $filedata .= "\nXero signature key:\n"; $filedata .= $_SERVER['HTTP_X_XERO_SIGNATURE']; // Result $filedata .= "\n\n---- Result ----\n"; if ($isEqual) { $filedata .= "Match"; } else { $filedata .= "Not match"; } // Store to file $currentTime = microtime(); $filename = substr($currentTime, 11) . substr($currentTime, 2, 8); //output to file //file_put_contents('./'.$filename.'.txt', $filedata); // ---------------------------------------------------------------------------- // Helper function(s) function sendToSlack($message) { $url = 'https://hooks.slack.com/services/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'; $curlObj = curl_init(); curl_setopt($curlObj, CURLOPT_URL, $url); curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($curlObj, CURLOPT_HEADER, 0); curl_setopt($curlObj, CURLOPT_HTTPHEADER, array('Content-type:application/json')); curl_setopt($curlObj, CURLOPT_POST, 1); curl_setopt($curlObj, CURLOPT_POSTFIELDS, '{"text": "'.$message.'"}'); $response = curl_exec($curlObj); curl_close($curlObj); } function getHeaderList() { $headerList = []; foreach ($_SERVER as $name => $value) { if (preg_match('/^HTTP_/',$name)) { $headerList[$name] = $value; } } return $headerList; } function lookUpInvoice($xeroTenantId,$accountingApi,$id) { //global $XeroOAuth; error_log("called look up ".$id); try { $apiResponse = $accountingApi->getInvoice($xeroTenantId, $id); $result = $apiResponse->getInvoices()[0]; error_log("invoice ".json_encode($result, true)); return $apiResponse; } catch (Exception $e) { error_log('Exception when calling AccountingApi->getInvoices: '.$e->getMessage()); } // $url = $XeroOAuth->url('Invoices', 'core')."/".$id; // error_log($url); // $response = $XeroOAuth->request('GET', $url, $params); // if ($XeroOAuth->response['code'] == 200) { // $invoices = $XeroOAuth->parseResponse($XeroOAuth->response['response'], $XeroOAuth->response['format']); // error_log(json_encode($invoices, true)); // if(count($invoices->Invoices[0]) > 0) { // return $invoices->Invoices[0]->Invoice; // } else { // return false; // } // } else { // error_log("error with oauth token"); // } } function getPDF($xeroTenantId,$accountingApi,$invoice_id){ // global $XeroOAuth; // $response = $XeroOAuth->request('GET', $XeroOAuth->url('Invoice/'.$invoice_id, 'core'), array(), "", 'pdf'); // if ($XeroOAuth->response['code'] == 200) { // $myFile = "pdf/".$invoice_id.".pdf"; // $fh = fopen($myFile, 'w') or die("can't open file"); // fwrite($fh, $XeroOAuth->response['response']); // fclose($fh); // return true; // } else { // outputError($XeroOAuth); // return false; // } try { $result = $accountingApi->getInvoiceAsPdf($xeroTenantId, $invoice_id); $myFile = "pdf/".$invoice_id.".pdf"; $fh = fopen($myFile, 'w') or die("can't open file"); fwrite($fh, 200); fclose($fh); return true; } catch (Exception $e) { error_log('Exception when calling AccountingApi->getInvoiceAsPdf: '.$e->getMessage()); } } function persistSession($response) { if (isset($response)) { $_SESSION['access_token'] = $response['oauth_token']; $_SESSION['oauth_token_secret'] = $response['oauth_token_secret']; if(isset($response['oauth_session_handle'])) $_SESSION['session_handle'] = $response['oauth_session_handle']; } else { return false; } } /** * Retrieve the OAuth access token and session handle * In my example I am just using the session, but in real world, this is should be a storage engine * */ function retrieveSession() { if (isset($_SESSION['access_token'])) { $response['oauth_token'] = $_SESSION['access_token']; $response['oauth_token_secret'] = $_SESSION['oauth_token_secret']; $response['oauth_session_handle'] = $_SESSION['session_handle']; return $response; } else { return false; } } function outputError($XeroOAuth) { error_log('Error: ' . $XeroOAuth->response['response']); pr($XeroOAuth); } /** * Debug function for printing the content of an object * * @param mixes $obj */ function pr($obj) { if (!is_cli()) echo '
';
    if (is_object($obj))
        print_r($obj);
    elseif (is_array($obj))
        print_r($obj);
    else
        echo $obj;
    if (!is_cli())
        echo '
'; } function is_cli() { return (PHP_SAPI == 'cli' && empty($_SERVER['REMOTE_ADDR'])); } ?>