Square API - invalid character 'C' looking for beginning of value - php

I am using Square Charge API, and following is my request object for a test card -
I am using Square provided PHP client to connect to the API. And I am receiving following response for "Charge" endpoint -
[HTTP/1.1 400 Bad Request] {"errors":[{"category":"INVALID_REQUEST_ERROR","code":"BAD_REQUEST","detail":"invalid character 'C' looking for beginning of value (line 1, character 1)"}]}
Following is my code in PHP -
public function chargeCustomerCard($userId, $custId, $cardId, $note, $billingAddres, $amount, $idempotencyKey){
$billingAddrRequest = array("address_line_1" => $billingAddres->addr1, "address_line_2" => $billingAddres->addr2, "locality" => $billingAddres->city, "administrative_district_level_1" => $billingAddres->state, "postal_code" => $billingAddres->zip, "country" => $billingAddres->country);
$billingAddressReq = new \SquareConnect\Model\Address($billingAddrRequest);
$moneyRequest = array("amount" => $amount, "currency" => "USD");
$money = new \SquareConnect\Model\Money($moneyRequest);
$request = array("idempotency_key" => $idempotencyKey, "customer_id" => $custId, "customer_card_id" => $cardId, "delay_capture" => false, "amount_money" => $money, "billing_address" => $billingAddressReq, "note" => $note, "reference_id" => $userId);
$charge = new \SquareConnect\Model\ChargeRequest($request);
$response = null;
try{
$charge_api = new \SquareConnect\Api\TransactionsApi();
$response = $charge_api->charge($this->authtoken, $this->locationId, $charge);
if($response != null && count($response->getErrors()) == 0){
$transaction = $response->getTransaction();
$data = array();
$data['transactionId'] = $transaction->getId();
$data['created'] = $transaction->getCreatedAt();
$data['referenceId'] = $transaction->getReferenceId(); //this should be equal to userid
$tender = $transaction->getTenders()[0];
$data['tenderId'] = $tender->getId();
$data['note'] = $tender->getNote();
$data['amount'] = ($tender->getAmountMoney()->getAmount())/100;
$data['currency'] = $tender->getAmountMoney()->getCurrency();
$processingFee = $tender->getProcessingFeeMoney();
if(isset($processingFee) && !empty($processingFee)){
$data['processingFee'] = $tender->getProcessingFeeMoney()->getAmount();
}else{
$data['processingFee'] = 0;
}
$data['tendertype'] = $tender->getType();
$data['cardStatus'] = $tender->getCardDetails()->getStatus();
$data['cardBrand'] = $tender->getCardDetails()->getCard()->getCardBrand();
$data['cardLast4'] = $tender->getCardDetails()->getCard()->getLast4();
$data['idempotencyKey'] = $idempotencyKey;
$data['customerPayId'] = $custId;
$data['customerCardId'] = $cardId;
return $this->generateReturnData(PAY_API_SUCCESS, '', $data);
}else{
return $this->generateReturnData(PAY_API_FAIL, '', $response->getErrors());
}
}catch(Exception $e) {
return $e->getMessage();
}
}
Can someone please point out to me what am I doing wrong here. I am really stuck here. Other API endpoints are working fine, such as, Create Customer, Create Customer Card API endpoints, using the same approach and same PHP client provided by square.
PS - this is on sandbox

Related

Google Task API PHP: Setting the TaskList ID & "Invalid task list ID" error

I'm trying to loop through task lists in order to generate a list of tasks using the Google Task PHP library.
I have:
Done all the credential stuff & can call the API
I can get task lists
A list of tasks for the respective task list output correctly using the ids generated from the point above & the tasklist parameter in Task API explorer
Where I'm stuck:
I'm not sure if I'm calling the 1) wrong method or 2) passing the wrong parameter to get a list of tasks for a respective tasklist id.
My code:
function getGcalTasks(){
$client = $this->getGcalTaskClient();
try {
$service = new Google_Service_Tasks($client);
$optParamLists = array(
'maxResults' => 10,
);
$result_lists = $service->tasklists->listTasklists($optParamLists);
if (
is_array($result_lists->getItems())
&& count($result_lists->getItems())
) {
foreach ($result_lists->getItems() as $tasklist) {
$taskListId = trim($tasklist->getId());
$taskListTitle = trim($tasklist->getTitle());
if(
$taskListId
){
$optParamsTasks = array(
// I've tried all of the below and still get: "Invalid task list ID",
'id' => $taskListId,
'kind' => 'tasks#taskList',
'title' => $taskListTitle,
//'tasklist' => $taskListId,
//'taskList' => $taskListId,
//'tasklistId' => $taskListId,
//'listName' => $taskListTitle,
);
$result_tasks = $service->tasks->listTasks($optParamsTasks);
}
}
}
} catch (Exception $e) {
log_message('error',$e->getMessage());
}
}
Welp, I took a look a few minutes later and realized that listTasks() only accepts one parameter, the id. The code below is working for me:
function getGcalTasks(){
$client = $this->getGcalTaskClient();
$tasks = array();
try {
$service = new Google_Service_Tasks($client);
$optParamLists = array(
'maxResults' => 10,
);
$result_lists = $service->tasklists->listTasklists($optParamLists);
if (
is_array($result_lists->getItems())
&& count($result_lists->getItems())
) {
foreach ($result_lists->getItems() as $tasklist) {
$taskListId = trim($tasklist->getId());
$taskListTitle = trim($tasklist->getTitle());
if(
$taskListId
){
$optParamsTasks = array(
'tasklist' => $taskListId,
);
$result_tasks = $service->tasks->listTasks($taskListId);
$tasks[] = $result_tasks->getItems();
}
}
return $tasks;
}
} catch (Exception $e) {
log_message('error',$e->getMessage());
}
}

Laravel + Shopify inventoryBulkAdjustQuantityAtLocation

I'm using following package : 'osiset/Basic-Shopify-API' and need bulk update products by location.
It's only possible with GraphQL. This function should work :
inventoryBulkAdjustQuantityAtLocation Shopify documentation
$shop = 'example.myshopify.com';
$token = 'shppa_admin_api_token';
/ Create options for the API
$options = new Options();
$options->setVersion('2020-04');
// Create the client and session
$api = new BasicShopifyAPI($options);
$api->setSession(new Session($shop, $token));
$products[0]['inventoryItemId'] = '33125243617303';
$products[0]['availableDelta'] = 2000;
$result = $api->graph(
'mutation inventoryBulkAdjustQuantityAtLocation($inventoryItemAdjustments: InventoryAdjustItemInput!,$locationId: ID!)
{inventoryBulkAdjustQuantityAtLocation(inventoryItemAdjustments: $InventoryAdjustItemInput, locationId: $locationId) {userErrors {field message } inventoryLevels { id }}}',
['inventoryItemAdjustments' =>
$products
],
);
But I don't understand how to use it. Could anyone help me ?
Now it works. It's a challenge to understand GraphQL queries if you never used them before.
Here are some more information :
https://www.shopify.com/partners/blog/multi-location_and_graphql
$locationId = "gid://shopify/Location/1";
$inventoryItemAdjustments1['locationId'] = $locationId;
$inventoryItemAdjustments1['inventoryItemAdjustments']['inventoryItemId'] = 'gid://shopify/InventoryItem/1';
$inventoryItemAdjustments1['inventoryItemAdjustments']['availableDelta'] = 500;
$result = $api->graph('mutation inventoryBulkAdjustQuantityAtLocation($inventoryItemAdjustments: [InventoryAdjustItemInput!]!, $locationId: ID!)
{inventoryBulkAdjustQuantityAtLocation(inventoryItemAdjustments: $inventoryItemAdjustments, locationId: $locationId) {userErrors { field message }}}',
$inventoryItemAdjustments1
);
Not so good examples (hardcoded values, aliases - not real life examples) ... graphql variables should be used and they should match mutation requirements ('root' parameters), in this case locationId and inventoryItemAdjustments (array of objects).
You can test this mutation in graphiql/playground using 'query variables' defined like this:
{
locationId: "gid://shopify/Location/1",
inventoryItemAdjustments: [
{
'inventoryItemId': 'gid://shopify/InventoryItem/1',
'availableDelta': 500
},
{
'inventoryItemId': 'gid://shopify/InventoryItem/2',
'availableDelta': 100
}
]
}
... so using php (associative arrays are encoded to json as objects - explicitely declared for readability) it should look more like this:
$locationId = "gid://shopify/Location/1";
$inventoryItemAdjustments = [];
$inventoryItemAdjustments[] = (object)[
'inventoryItemId' => 'gid://shopify/InventoryItem/1',
'availableDelta'] => 500;
];
$inventoryItemAdjustments[] = (object)[
'inventoryItemId' => 'gid://shopify/InventoryItem/2',
'availableDelta'] => 100;
];
$variables = (object)[
'locationId' => $locationId;
'inventoryItemAdjustments' => $inventoryItemAdjustments
];
$result = $api->graph('mutation inventoryBulkAdjustQuantityAtLocation($inventoryItemAdjustments: [InventoryAdjustItemInput!]!, $locationId: ID!)
{inventoryBulkAdjustQuantityAtLocation(inventoryItemAdjustments: $inventoryItemAdjustments, locationId: $locationId) {userErrors { field message }}}',
$variables
);
I would like to show another library that uses this and expand on the last example.
I am using a slightly different library for graphql:
https://github.com/Shopify/shopify-php-api/
Updating the inventory like it was posted here shows a [statusCode:GuzzleHttp\Psr7\Response:private] => 200
So it seems to work but does not reflect in updated inventory. :(
Checking at /admin/products/inventory?location_id=62241177806&query=F11_27781195
would not show the new inventory.
I am using the inventoryid correctly (not product or variantid).
$inventoryItemAdjustments = array();
$inventoryItemAdjustments[] = (object)[
'inventoryItemId' => 'gid://shopify/InventoryItem/43151435235534',
'availableDelta' => 500
];
$inventoryItemAdjustments[] = (object)[
'inventoryItemId' => 'gid://shopify/InventoryItem/43151435268302',
'availableDelta' => 500
];
$variables = array(
'locationId' => ConfigClass::$locationId,
'inventoryItemAdjustments' => $inventoryItemAdjustments
);
$graphqlquery='mutation inventoryBulkAdjustQuantityAtLocation($inventoryItemAdjustments: [InventoryAdjustItemInput!]!, $locationId: ID!)
{inventoryBulkAdjustQuantityAtLocation(inventoryItemAdjustments: $inventoryItemAdjustments, locationId: $locationId) {userErrors { field message }}}';
$response = $client->query(['query' => $graphqlquery, 'variables' => $variables]);
Deleting a product works (and is a good test if the library is initialized well):
$query = <<<QUERY
mutation {
productDelete(input: {id: "gid://shopify/Product/6975310463182"})
{
deletedProductId
}
}
QUERY;
$response = $client->query(["query" => $query]);
print_r($response);
die;

DIsplay all otrs ticket using soap api

How can i display all the otrs tickets using a soap api. Individual ticket can be displayed by passing ticket id in url like this:
$url = "https://url/otrs/rpc.pl"; //// URL for OTRS server
$username = "username"; //// SOAP username set in sysconfig
$password = "password"; //// SOAP password set in sysconfig
$TicketID = $_GET['id'];
//////// Initialize new client session ////////
$client = new SoapClient(
null,
array(
'location' => $url,
'uri' => "Core",
'trace' => 1,
'login' => $username,
'password' => $password,
'style' => SOAP_RPC,
'use' => SOAP_ENCODED
)
);
//////// Create and send the SOAP Function Call ////////
$sql =
$TicketDetails = $client->__soapCall("Dispatch",
array($username, $password,
"TicketObject", "TicketGet",
"TicketID", $TicketID,
));
$ticketInfo = array();
$i = 0;
foreach ($TicketDetails as $name => $value){ //// explode the xml response
if (false !== strpos($name, "s-gensym")){
$temp[$i] = $value;
$v = $temp[$i - 1];
if($i % 2 != 0){
$ticketInfo[$v] = $value;
}
$i++;
}
}
var_dump($ticketInfo);
exit();
How can i display all the tickets using api?????
Use the TicketSearch API call in order to retrieve a list of Ticket IDs. Then feed this list to TicketGet as you already showed in order to retrieve ticket details.

I am not able to add members in a cohort externally in moodle

I am trying to add members in a cohort but whenever i call the function this is the response i get.I am using drupal rest to make the api call.
{
"exception": "dml_write_exception",
"errorcode": "dmlwriteexception",
"message": "Error writing to database",
"debuginfo": "Column 'role_id' cannot be null\nINSERT INTO mdl_cohort_members (cohortid,userid,timeadded,role_id) VALUES(?,?,?,?)\n[array (\n 0 => '3',\n 1 => '52367',\n 2 => 1460546128,\n 3 => NULL,\n)]"
}
Can somebody direct me towards the solution.
{
$fname = 'core_cohort_add_cohort_members';
/// Paramètres
$member = new stdClass();
$member->cohorttype['type']='id';
$member->cohorttype['value']='3';
$member->usertype['type']='id';
$member->usertype['value']='5';
$members = array($member);
$par = array('members' => $members);
$rest_format = 'json';
$Serve_Url = 'http://dev-lms.teletaleem.net' . '/webservice/rest/server.php'. '?wstoken=' . '7882bb500bcefcd8778de64b8e79a19a' .'&wsfunction='. $fname;
require_once('curl.inc');
$Rest_format = ($rest_format == 'json') ? '&moodlewsrestformat=' . $rest_format : '';
$curl = new curl;
//if rest format == 'xml', then we do not add the param for backward compatibility with Moodle < 2.2
$rep = $curl->post($Serve_Url.$Rest_format, $par);
dpm($rep);
}

No 'Access-Control-Allow-Origin' header even thou other requests from the same domain are working

I have a strange error, with No 'Access-Control-Allow-Origin' header. I understand that I have to give some permission the origin domain(client) to be able to access the server and that works fine with some other requests I make. But when it comes to one other function to call, it says No 'Access-Control-Allow-Origin' header only.
I have my client hosted in heroku and server in godaddy...
This is the function when that error shows:
public function store(Request $request)
{
$ffSpending = new FriendsFamilySpending();
$ffSpending->user_id = Auth::user()->id;
$ffSpending->team_id = Auth::user()->student->team_id;
$ffSpending->management_units = $request->input('management_units');
$ffSpending->sales_units = $request->input('sales_units');
$ffSpending->product_units = $request->input('product_units');
$ffSpending->ip_units = $request->input('ip_units');
$ffSpendingRules = array(
'management_units' => 'required',
'sales_units' => 'required',
'product_units' => 'required',
'ip_units' => 'required'
);
$ffSpendingValidator = \Validator::make($ffSpending->getAttributes(), $ffSpendingRules);
if ($ffSpendingValidator->passes()) {
$team = Team::find($ffSpending->team_id);
$currentBalance = $this->teamService->checkBalance($team);
//Baseline costs
$BASELINE = FriendsFamilySpending::BASELINE;
//Get Prices for each unit
$IP_ONE_TIME_COST = OperationalExpensePrice::getPrice(OperationalExpense::IP, $request->input('ip_units'), OperationalExpenseSerie::FF);//one-time IP costs
$MANAGEMENT = OperationalExpensePrice::getPrice(OperationalExpense::MANAGEMENT, $request->input('management_units'), OperationalExpenseSerie::FF);
$SALES = OperationalExpensePrice::getPrice(OperationalExpense::SALES, $request->input('sales_units'), OperationalExpenseSerie::FF);
$PRODUCT = OperationalExpensePrice::getPrice(OperationalExpense::PRODUCT, $request->input('product_units'), OperationalExpenseSerie::FF);
//Monthly Costs
$quartlyCosts = $BASELINE + $MANAGEMENT + $SALES + $PRODUCT;
$newBalance = $currentBalance;
$workingMoney = $newBalance - $IP_ONE_TIME_COST;
$minimumMonth = 12; // the minimum amount of time they must be able to afford (Staging Day = 12 months)
//Calculate how many months they (team) can survive
$survivingMonths = 0;
while ($workingMoney >= $quartlyCosts) {
$workingMoney = $workingMoney - $quartlyCosts; //deduct monthly costs from the current working money
$survivingMonths = $survivingMonths + 3; // quartly spending
if ($survivingMonths > 24) { // team survives the whole staging and deal day
break;
}
}
// month to minute - Conversation ratio
$monthToMinute = 6.25; // (75min / 12month) = 6.25min a month
$totalMinutes = $survivingMonths * $monthToMinute;
$minMinutes = 75; //the minimum amount of time they must be able to afford
//Check if team makes it till the deal day
if ($survivingMonths < $minimumMonth) {
return response()->json(['message' => 'With your current spending plan, you will not make it to deal day. Please try again with less spending plan. Currently you run out of money after ' . $totalMinutes . ' minutes. You have to survive at least 75 minutes."', 'success' => false, 'status' => 500, 'data' => null]);
}
$ffSpendingRes = $this->ffSpendingService->save($ffSpending);
if ($ffSpendingRes) {
$this->ffSpendingService->score(Auth::user()->student->team->class_id); // update ff spending scoring
$this->ffSpendingService->updateTotalScore(Auth::user()->student->team->class_id);
//Update balance
$team = Team::find($ffSpending->team_id);
$this->teamService->updateBalance($team, $workingMoney);
if ($survivingMonths >= $minimumMonth && $survivingMonths < 24) {
$survivingMonthsAfterStagingDay = $survivingMonths - $minimumMonth;
$survivingMonthsAfterStagingDayToMinute = $survivingMonthsAfterStagingDay * $monthToMinute;
$outOfMoney = new OutOfMoney();
$outOfMoney->team_id = Auth::user()->student->team_id;
$outOfMoney->stage = OutOfMoney::$FF_SPENDING;
$outOfMoney->is_running_out_of_money_on_deal_day = 1;
$outOfMoney->month = $survivingMonthsAfterStagingDay;
$outOfMoney->minutes = $survivingMonthsAfterStagingDayToMinute;
$outOfMoney->monthly_cost = $quartlyCosts;
$outOfMoney->save();
} else {
$outOfMoney = new OutOfMoney();
$outOfMoney->team_id = Auth::user()->student->team_id;
$outOfMoney->stage = OutOfMoney::$FF_SPENDING;
$outOfMoney->is_running_out_of_money_on_deal_day = 0;
$outOfMoney->monthly_cost = $quartlyCosts;
$outOfMoney->save();
}
return response()->json(['message' => 'Success', 'success' => true, 'status' => 200, 'data' => $ffSpending]);
} else {
return response()->json(['message' => 'Error', 'success' => false, 'status' => 500, 'data' => null]);
}
} else {
return response()->json(['message' => 'Validation Failed', 'success' => false, 'status' => 400, 'data' => array('class' => $ffSpendingRules)]);
}
Note: if I change the function and make it simple, like return 'test', it does not show anymore that origin access error.
I wonder if there is any problem with function, why does not it show the actuall error, but it show that cors error instead.
Any suggestion?
What's happening is an ORIGINS request is coming in and getting declined because it's not in your allowed methods.
'allowedMethods' => ['GET', 'POST', 'PUT', 'DELETE', 'ORIGINS']
You'll also want to set your allowedOrigins to something.
I always use MDN for reference.

Categories