Can new customers be created in QBO API Sandbox - quickbooks

If I create a customer with DisplayName other than "Bob-Smith" it gives an error: Unknown class Customer. Using v3-php-sdk
Fatal error: Uncaught Error: Class 'Customer' not found in /home/novaacoustics/public_html/inc/common.php:2247 Stack trace: #0 /home/novaacoustics/public_html/admin/projects/testQuickbooks.php(52): getCustomerObj(Object(QuickBooksOnline\API\DataService\DataService), 'Peter Sutcliffe') #1 {main} thrown in /home/novaacoustics/public_html/inc/common.php on line 2247
Customer is created fine if I use API Explorer. I already know the new customer doesn't yet exist because the query:
$customerArray = $dataService->Query("select * from Customer where DisplayName='" . $customerName . "'");
returns null.
$realmId = $accessTokenObj->setRealmId('4620816365164449490');
$dataService->updateOAuth2Token($accessTokenObj);
$customerRef = getCustomerObj($dataService, "John Smith");
function getCustomerObj($dataService, $customerName = NULL) {
// $customerName = 'Bob-Smith';
$customerArray = $dataService->Query("select * from Customer where DisplayName='" . $customerName . "'");
$error = $dataService->getLastError();
if ($error) {
logError($error);
} else {
if (is_array($customerArray) && sizeof($customerArray) > 0) {
return current($customerArray);
}
}
// Create Customer
echo "creating customer " .$customerName . getGUID();
$customerRequestObj = Customer::create([
"DisplayName" => $customerName . getGUID()
]);
$customerResponseObj = $dataService->Add($customerRequestObj);
$error = $dataService->getLastError();
if ($error) {
logError($error);
} else {
echo "Created Customer with Id={$customerResponseObj->Id}.\n\n";
return $customerResponseObj;
}
}
The getGUID() I tried removing and same error. Also the refresh_ and access_tokens are fine, OAuth2 working great.

OK solved by adding use QuickBooksOnline\API\Facades\Customer; at top of file where getCustomerObj function is.

Related

Google API login failed always: back to needing to authorize

I'd like to change my tags of a YouTube video using the YouTube Data API. But I'm already stuck on login:
My page shows the message: You need to authorize access before proceeding. I click on authorize access and select my Google account and then my YouTube channel, I select allow and get redirected to the login message.
The code is directly from the sample files on Github:
<?php
/**
* This sample adds new tags to a YouTube video by:
*
* 1. Retrieving the video resource by calling the "youtube.videos.list" method
* and setting the "id" parameter
* 2. Appending new tags to the video resource's snippet.tags[] list
* 3. Updating the video resource by calling the youtube.videos.update method.
*
* #author Ibrahim Ulukaya
*/
/**
* Library Requirements
*
* 1. Install composer (https://getcomposer.org)
* 2. On the command line, change to this directory (api-samples/php)
* 3. Require the google/apiclient library
* $ composer require google/apiclient:~2.0
*/
if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
throw new \Exception('please run "composer require google/apiclient:~2.0" in "' . __DIR__ .'"');
}
require_once __DIR__ . '/vendor/autoload.php';
session_start();
/*
* You can acquire an OAuth 2.0 client ID and client secret from the
* {{ Google Cloud Console }} <{{ https://cloud.google.com/console }}>
* For more information about using OAuth 2.0 to access Google APIs, please see:
* <https://developers.google.com/youtube/v3/guides/authentication>
* Please ensure that you have enabled the YouTube Data API for your project.
*/
$OAUTH2_CLIENT_ID = 'myID';
$OAUTH2_CLIENT_SECRET = 'mySec';
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);
// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);
// Check if an auth token exists for the required scopes
$tokenSessionKey = 'token-' . $client->prepareScopes();
if (isset($_GET['code'])) {
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
die('The session state did not match.');
}
$client->authenticate($_GET['code']);
$_SESSION[$tokenSessionKey] = $client->getAccessToken();
header('Location: ' . $redirect);
}
if (isset($_SESSION[$tokenSessionKey])) {
$client->setAccessToken($_SESSION[$tokenSessionKey]);
}
// Check to ensure that the access token was successfully acquired.
if ($client->getAccessToken()) {
$htmlBody = '';
try{
// REPLACE this value with the video ID of the video being updated.
$videoId = "Zqt-NvuMKYU";
// Call the API's videos.list method to retrieve the video resource.
$listResponse = $youtube->videos->listVideos("snippet",
array('id' => $videoId));
// If $listResponse is empty, the specified video was not found.
if (empty($listResponse)) {
$htmlBody .= sprintf('<h3>Can\'t find a video with video id: %s</h3>', $videoId);
} else {
// Since the request specified a video ID, the response only
// contains one video resource.
$video = $listResponse[0];
$videoSnippet = $video['snippet'];
$tags = $videoSnippet['tags'];
// Preserve any tags already associated with the video. If the video does
// not have any tags, create a new list. Replace the values "tag1" and
// "tag2" with the new tags you want to associate with the video.
if (is_null($tags)) {
$tags = array("tag1", "tag2");
} else {
array_push($tags, "tag1", "tag2");
}
// Set the tags array for the video snippet
$videoSnippet['tags'] = $tags;
// Update the video resource by calling the videos.update() method.
$updateResponse = $youtube->videos->update("snippet", $video);
$responseTags = $updateResponse['snippet']['tags'];
$htmlBody .= "<h3>Video Updated</h3><ul>";
$htmlBody .= sprintf('<li>Tags "%s" and "%s" added for video %s (%s) </li>',
array_pop($responseTags), array_pop($responseTags),
$videoId, $video['snippet']['title']);
$htmlBody .= '</ul>';
}
} catch (Google_Service_Exception $e) {
$htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
} catch (Google_Exception $e) {
$htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
}
$_SESSION[$tokenSessionKey] = $client->getAccessToken();
} elseif ($OAUTH2_CLIENT_ID == 'REPLACE_ME') {
$htmlBody = <<<END
<h3>Client Credentials Required</h3>
<p>
You need to set <code>\$OAUTH2_CLIENT_ID</code> and
<code>\$OAUTH2_CLIENT_ID</code> before proceeding.
<p>
END;
} else {
// If the user hasn't authorized the app, initiate the OAuth flow
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$authUrl = $client->createAuthUrl();
$htmlBody = <<<END
<h3>Authorization Required</h3>
<p>You need to authorize access before proceeding.<p>
END;
}
?>
<!doctype html>
<html>
<head>
<title>Video Updated</title>
</head>
<body>
<?=$htmlBody?>
</body>
</html>
Would be great if someone has a tip for me.
Fixed... was a space key inside secret

500 backend error while inserting YouTube Channel Art

Although, we'd prepared YouTube channel art upload mechanism as described on the it's official documentation page, (https://developers.google.com/youtube/v3/docs/channelBanners/insert), from few days, we are facing following error,
A service error occurred: { "error": { "errors": [ { "domain": "global", "reason": "backendError", "message": "Backend Error" } ], "code": 500, "message": "Backend Error" } }
Which was perfectly working before.
/**
* This sample sets a custom banner for a user's channel by:
*
* 1. Uploading a banner image with "youtube.channelBanners.insert" method via resumable upload
* 2. Getting user's channel object with "youtube.channels.list" method and "mine" parameter
* 3. Updating channel's banner external URL with "youtube.channels.update" method
*
* #author Ibrahim Ulukaya
*/
/**
* Library Requirements
*
* 1. Install composer (https://getcomposer.org)
* 2. On the command line, change to this directory (api-samples/php)
* 3. Require the google/apiclient library
* $ composer require google/apiclient:~2.0
*/
if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
throw new \Exception('please run "composer require google/apiclient:~2.0" in "' . __DIR__ .'"');
}
require_once __DIR__ . '/vendor/autoload.php';
session_start();
//session_destroy();
/*
* You can acquire an OAuth 2.0 client ID and client secret from the
* {{ Google Cloud Console }} <{{ https://cloud.google.com/console }}>
* For more information about using OAuth 2.0 to access Google APIs, please see:
* <https://developers.google.com/youtube/v3/guides/authentication>
* Please ensure that you have enabled the YouTube Data API for your project.
*/
$OAUTH2_CLIENT_ID = 'OUR_CLIENT_ID';
$OAUTH2_CLIENT_SECRET = 'OUR_CLIENT_SECRET';
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);
// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);
// Check if an auth token exists for the required scopes
$tokenSessionKey = 'token-' . $client->prepareScopes();
if (isset($_GET['code'])) {
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
die('The session state did not match.');
}
$client->authenticate($_GET['code']);
$_SESSION[$tokenSessionKey] = $client->getAccessToken();
header('Location: ' . $redirect);
}
if (isset($_SESSION[$tokenSessionKey])) {
$client->setAccessToken($_SESSION[$tokenSessionKey]);
}
// Check to ensure that the access token was successfully acquired.
if ($client->getAccessToken()) {
$htmlBody = '';
try{
// REPLACE with the path to your file that you want to upload for thumbnail
$imagePath = "2560x1440-pixels-image.jpg";
$imageSize = get_headers($imagePath, 1);
// Specify the size of each chunk of data, in bytes. Set a higher value for
// reliable connection as fewer chunks lead to faster uploads. Set a lower
// value for better recovery on less reliable connections.
$chunkSizeBytes = 1 * 1024 * 1024;
// Setting the defer flag to true tells the client to return a request which can be called
// with ->execute(); instead of making the API call immediately.
$client->setDefer(true);
$chan = new Google_Service_YouTube_ChannelBannerResource();
// Create a request for the API's channelBanners.insert method to upload the banner.
$insertRequest = $youtube->channelBanners->insert($chan);
// Create a MediaFileUpload object for resumable uploads.
$media = new Google_Http_MediaFileUpload(
$client,
$insertRequest,
'image/jpeg',
null,
true,
$chunkSizeBytes
);
//$media->setFileSize(filesize($imagePath));
$media->setFileSize($imageSize["Content-Length"]);
// Read the media file and upload it chunk by chunk.
$status = false;
$handle = fopen($imagePath, "rb");
while (!$status && !feof($handle)) {
$chunk = fread($handle, $chunkSizeBytes);
$status = $media->nextChunk($chunk);
}
fclose($handle);
// If you want to make other calls after the file upload, set setDefer back to false
$client->setDefer(false);
$thumbnailUrl = $status['url'];
// Call the API's channels.list method with mine parameter to fetch authorized user's channel.
$listResponse = $youtube->channels->listChannels('brandingSettings', array(
'mine' => 'true',
));
/*echo '<pre>';
print_r($listResponse);
echo '</pre>';*/
$responseChannel = $listResponse[0];
$responseChannel['brandingSettings']['image']['bannerExternalUrl']=$thumbnailUrl;
// Call the API's channels.update method to update branding settings of the channel.
$updateResponse = $youtube->channels->update('brandingSettings', $responseChannel);
$bannerMobileUrl = $updateResponse["brandingSettings"]["image"]["bannerMobileImageUrl"];
$htmlBody .= "<h3>Thumbnail Uploaded</h3><ul>";
$htmlBody .= sprintf('<li>%s</li>',
$thumbnailUrl);
$htmlBody .= sprintf('<img src="%s">', $bannerMobileUrl);
$htmlBody .= '</ul>';
} catch (Google_Service_Exception $e) {
$htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
} catch (Google_Exception $e) {
$htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
}
$_SESSION[$tokenSessionKey] = $client->getAccessToken();
} elseif ($OAUTH2_CLIENT_ID == 'OUR_CLIENT_ID') {
$htmlBody = <<<END
<h3>Client Credentials Required</h3>
<p>
You need to set <code>\$OAUTH2_CLIENT_ID</code> and
<code>\$OAUTH2_CLIENT_ID</code> before proceeding.
<p>
END;
} else {
// If the user hasn't authorized the app, initiate the OAuth flow
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$authUrl = $client->createAuthUrl();
$htmlBody = <<<END
<h3>Authorization Required</h3>
<p>You need to authorize access before proceeding.<p>
END;
}
?>
<!doctype html>
<html>
<head>
<title>Banner Uploaded and Set</title>
</head>
<body>
<?=$htmlBody?>
</body>
</html>
Any suggestions?

Message: mysql_real_escape_string() expects parameter 2 to be resource, boolean given Filename: mysql/mysql_driver.php Line Number: 346

I am using the following code to select from a MySQL database with a Code Igniter webapp:
My Model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class m_login extends CI_Model{
function __construct(){
parent::__construct();
}
public function validate(){
// grab user input
$username = $this->security->xss_clean($this->input->post('username'));
$password = $this->security->xss_clean($this->input->post('password'));
$password = md5($password);
// Run the query
//$array = array('nip' => $this->db->escape_str($username), 'password' => $this->db->escape_str($password));
//$this->db->select('pegawai.NIP, akun.PASSWORD, akun.ROLE');
//$this->db->from('pegawai');
//$this->db->join('akun', 'akun.ID_PEGAWAI = pegawai.ID_PEGAWAI');
//$this->db->get_where('nip', $username);
//$this->db->where($array);
//$this->db->where('PASSWORD', 'd93591bdf7860e1e4ee2fca799911215');
//$query = $this->db->get();
$sql = "SELECT NIP, PASSWORD, ROLE FROM pegawai LEFT JOIN akun ON pegawai.ID_PEGAWAI=akun.ID_PEGAWAI WHERE pegawai.NIP=('".$this->db->escape_str($username)."') AND akun.PASSWORD=('".$this->db->escape_str($password)."')";
$this->db->query($sql);
//$query = $this->db->query("SELECT NIP, PASSWORD, ROLE FROM pegawai LEFT JOIN akun ON pegawai.ID_PEGAWAI=akun.ID_PEGAWAI WHERE pegawai.NIP='$username' AND akun.PASSWORD='$password'");
// Let's check if there are any results
//var_dump($this->db);
//var_dump($username);
if($query->num_rows == 1)
{
//If there is a user, then create session data
$row = $query->row();
$data = array(
'role' => $row->role,
'nip' => $row->nip,
'validated' => true
);
$this->session->set_userdata($data);
return true;
}
//If the previous process did not validate
//then return false.
return false;
}
}
?>
I have error like this
A PHP Error was encountered
Severity: Warning
Message: mysql_real_escape_string() expects parameter 2 to be resource, boolean given
Filename: mysql/mysql_driver.php
Line Number: 346
Backtrace:
File: C:\xampp\htdocs\simpeg\application\models\m_login.php
Line: 27
Function: escape_str
File: C:\xampp\htdocs\simpeg\application\controllers\login.php
Line: 26
Function: validate
File: C:\xampp\htdocs\simpeg\index.php
Line: 292
Function: require_once
Most likely, this is a syntax error, but I just can't figure out which part of my code is responsible.
I've also gone through the Queries section of the user guide of CodeIgniter, but it wasn't explained clearly there.
Can anyone please tell me where my mistake is, and what is the correct syntax for what I'm trying to do?

Dart lang, manipulating server returned JSON data in the client

I want to check the user log in parameters, and if the parameters accepted, I want the server to send back to the client both the name and roles of the user, to be saved in the SeassonStorage for further usages.
my server side code is:
....
....
var users = <Map>[];
var logged = <Map>[];
....
....
.then((_) {
for (var user in users)
if(_theData['userName']==user['Alias'] && _theData['password']==user['Password'])
{
userFound=true;;
logged.add({
"Alias":user['Alias'],
"Roles": user['Roles']
});
}
})
.then((_) {
if(userFound == true)
res.write(JSON.encode(logged));
else
res.write('sorry, unknown loggin');
res.close();
});
in the client side, I've:
....
....
if(request.responseText != 'sorry, unknown loggen'){
server_msg.innerHtml='Welcome';
print(request.responseText);
print(JSON.decode(request.responseText));
var FonixLogin = JSON.decode(request.responseText);
print(FonixLogin['Alias']);
print(FonixLogin['Roles']);
Storage sessionStorage = window.sessionStorage;
sessionStorage['FonixAlias'] = FonixLogin['Alias'];
sessionStorage['FonixRoles'] = FonixLogin['Roles'];
....
the output I get is:
[{"Alias":"Admin","Roles":"admin"}]
[{Alias: Admin, Roles: admin}]
Exception: Illegal argument(s): Alias login.dart:66login_Element.onData
Why mistake I made here, so that the returned data is not saved properly in the
FonixLogin is a List and you access it like a Map.
Try print(FonixLogin[0]['Alias']);

Unable to print error message in foreach in magento admin

Hi i have added a new mas action in the sales order grid which allow create batch invoices.
For this my controler file is
<?php
class Iclp_Batchupdate_IndexController extends Mage_Adminhtml_Controller_Action
public function batchinvoiceAction ()
{
$already = " already ";
$refererUrl = $this->getRequest()->getServer('HTTP_REFERER');
$this->loadLayout();
$this->renderLayout();
$orderIds = explode(",",$this->getRequest()->getParam('order_ids'));
foreach ($orderIds as $orderIdss) {
$order = Mage::getModel('sales/order')->load($orderIdss);
//echo $orderIdss ."<br/>";
//echo "already ".$order->getStatusLabel();
try
{
if(!$order->canInvoice())
{
echo Mage::getSingleton('core/session')->addError($orderIdss.$already.$order->getStatusLabel());
}
$invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();
if (!$invoice->getTotalQty()) {
Mage::throwException(Mage::helper('core')->__('Cannot create an invoice without products.'));
}
$invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
$invoice->register();
$transactionSave = Mage::getModel('core/resource_transaction')->addObject($invoice)->addObject($invoice->getOrder());
$transactionSave->save();
$order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, true)->save();
//echo "Invoice are created";
}
catch (Mage_Core_Exception $e) {
}
}
//A Success Message
Mage::getSingleton('core/session')->addSuccess("Some success message");
//A Error Message
Mage::getSingleton('core/session')->addError("Some error message");
//A Info Message (See link below)
Mage::getSingleton('core/session')->addNotice("This is just a FYI message...");
//These lines are required to get it to work
session_write_close();
$this->getResponse()->setRedirect($refererUrl);
}
}
every thing is working fine but the problem is it is not printing the error message in foreach in above code
if(!$order->canInvoice())
{
echo Mage::getSingleton('core/session')->addError($orderIdss.$already.$order->getStatusLabel());
}
but the bottom error message are displayed properly. MOreover if i extend the class with front-action than it also prints the foreach messages. Please suggest where i am doing the mistake
You should add your errors and messages to admintml/session and not to core/session when you are in adminhtml. That should display the message correctly. You shouldn't need session_write_close();. There is also no need to echo the message, that should be handled automatically by Magento after the redirect.
There is also no need to call $this->loadLayout(); and $this->renderLayout(); because you are redirecting at the end.
Finally, regarding the redirect, you should not read the referrer yourself, Magento can to that for you more reliably. Just use the $this->_redirectReferer(); method instead of $this->getResponse()->setRedirect($refererUrl);.

Resources