I have tool using the REST API SDK for PHP that captures payments for multiple companies in PayPal. If I Post one or more transactions to capture from different companies. The transactions are marked 'Captured' within PayPal everything is great. The issue is trying to capture multiple transactions from the same company within the same Post. What happens is only the first transaction in the array gets marked as 'Captured' in PayPal but any other transaction in that same array does not. Seemingly they get ignored.
The PayPal logs with the application do not show any errors. Here is the method that grabs the POST transaction Ids:
if(isset($_POST['toCapture']) && ! empty($_POST['toCapture'])){
// Array of transaction ids to capture
$idsToCapture = $_POST['toCapture'];
for($i = 0; $i < $arrayCount; $i++) {
// Transaction id for current iteration in the loop
$theId = $idsToCapture[$i]; //transactionId
// Function call to get information for transaction id being processed in current iteration of loop
$infoToCapture = getInfoToCapture($theId);
$theCompany = $infoToCapture['Company'];
$theAmt = number_format($infoToCapture['DocumentAmount'], 2); // DocAmt formatted to two decimal places
$ohId = $infoToCapture['OrderHeaderId'];
try {
// Setting $theId to $authId
$authId = $theId;
// Maing sure the ids to be processed do not have an acknoledgement from PayPal
$checkAckNull = isAckNull($authId);
// Setting the amount we want to capture
$amt = new Amount();
$amt->setCurrency("USD")
->setTotal($theAmt);
// If there is no acknowledgment from PayPal, process the capture
if($checkAckNull == NULL){
### Capture
$capture = new Capture();
$capture->setId($authId)
->setAmount($amt);
// it is the $apiContexts that are different for each company
switch ($theCompany) {
case "BLL":
allTheImportantStuff( $apiContextBLL, $authId, $ohId, $capture, $theCompany );
break;
case "LOT":
allTheImportantStuff( $apiContextLOT, $authId, $ohId, $capture, $theCompany );
break;
case "SNA":
allTheImportantStuff( $apiContextSNA, $authId, $ohId, $capture, $theCompany );
break;
case "FAB":
allTheImportantStuff( $apiContextFAB, $authId, $ohId, $capture, $theCompany );
break;
case "STS":
allTheImportantStuff( $apiContextSTS, $authId, $ohId, $capture, $theCompany );
break;
case "MIA":
allTheImportantStuff( $apiContextMIA, $authId, $ohId, $capture, $theCompany );
break;
}
} // end if
else {
}
} catch (PayPal\Exception\PayPalConnectionException $ex) {
echo "Exception: " . $ex->getMessage() . PHP_EOL;
echo '<pre>'; var_dump( $ex->getData() ); echo '</pre>';
$fail = "failure";
insertFail($theCompany, $ohId, $theId, $fail);
} // end try/catch
} // end for loop
}
Here is the allTheImportantStuff method:
function allTheImportantStuff( $apiContext, $authId, $ohId, $capture, $theCompany ){
global $mode;
// Lookup the authorization.
$authorization = Authorization::get($authId, $apiContext);
// Perform a capture
$getCapture = $authorization->capture($capture, $apiContext);
// Get acknowledgment from capture
$ack = $getCapture->getId();
// Get state from capture
$state = $getCapture->getState();
return insertAck($theCompany, $ohId, $ack, $authId, $state);
}
Up until (roughly) a few weeks ago this code worked. I am not using the latest version of the REST API SDK for PHP but trying to avoid updating because other tools are using the SDK as well and work fine. I hope I have explained the issue thoroughly enough. Any thoughts or ideas on what may be going on or how to fix would be greatly appreciated.
Related
When I want to update the endpoint, I got the error:
ErrorException: Creating default object from empty value in file /var/www/html/app/Http/Controllers/CasesController.php on line 208
below the code:
public function accept(Request $request)
{
$id_case = $request->id_case;
$case = Cases::find($id_case);
$maxAgent = 0;
switch ($id_case[0]) {
case 'A':
$maxAgent = 1;
break;
case 'B':
$maxAgent = 3;
break;
case 'C':
$maxAgent = 5;
break;
default:
break;
}
// check the agent receive the case
$accepted_agent = AgentInCase::where('id_case', $id_case)->where('id_agent', auth()->user()->id_user)->get();
if ($accepted_agent) {
$message = 'Agent has accepted the request';
return $this->sendResponse($accepted_agent, $message, 200);
}
// check the max agent in case
$agent_in_case = AgentInCase::where('id_case', $id_case)->get();
if (count($agent_in_case) < $maxAgent) {
$agent = Agent::find(auth()->user()->id_user);
$agent->is_in_case = true;
$agent->save();
$agent = AgentInCase::create([
'id_case' => $id_case,
'id_agent' => auth()->user()->id_user
]);
//send FCM to customer that request confirmed
$message = [
'title' => 'accept_agent',
'body' => 'New Agent Come To Help ',
'payment' => 'Rp 15.000'
];
$this->sendNotificationFirebase('customer', $case->id_customer, $message, $agent);
$message = 'Successfully accepted request';
return $this->sendResponse($case, $message, 200);
}
$message = 'Failed to accept request';
$errors = 'Case has been handled by another agent';
return $this->sendError($message, 400, $errors);
}
The error in line:
$agent->is_in_case = true;
I'm trying to solve this error and I just get one reference:
Creating default object from empty value in PHP?.
But, I can't yet to solving this.
Could you help me to solve this? What I must do?
For every request that you want to select by an ID, you should catch and error if requested id is not exists .
In my opinion clean way to do that in laravel is using validation .
For example if you want to find a user by its ID validation should be something like :
'ID' => 'exists:users,ID',
First Id is in your request and second one is your column name in database.
As per the issued solution on Azure/azure-event-hubs-for-kafka/issues/51, I tried to use and consume a message but it came out with no luck. Please have a look at the code and guide on what needs to be done?
I have installed the rdkafka.so on my ubuntu system as per php manual for rdkafka and then used this piece of code :
$conf = new RdKafka\Conf();
$conf->set('group.id', '$Default');
$conf->set('metadata.broker.list', 'NAMESPACE.servicebus.windows.net:9093');
$conf->set('security.protocol', 'SASL_SSL');
$conf->set('sasl.mechanisms', 'PLAIN');
$conf->set('sasl.username', '$ConnectionString');
$conf->set('sasl.password', 'Endpoint=sb://NAMESPACE.servicebus.windows.net/;SharedAccessKeyName=syn-wk;SharedAccessKey=7XXX/XXXE=;EntityPath=someStringHere');
$conf->set('ssl.ca.location', '/absolute_path_to_cert');
$conf->set('enable.partition.eof', 'true');
$conf->set('api.version.request', 'false');
$conf->set('log_level', (string) LOG_DEBUG);
$conf->set('debug', 'all');
$rk = new RdKafka\Consumer($conf);
$topicConf = new RdKafka\TopicConf();
$topicConf->set('auto.commit.interval.ms', 100);
$topicConf->set('offset.store.method', 'broker');
$topicConf->set('auto.offset.reset', 'earliest');
$topic = $rk->newTopic("test", $topicConf);
$topic->consumeStart(0, RD_KAFKA_OFFSET_STORED);
while (true) {
$message = $topic->consume(0, 120*10000);
switch ($message->err) {
case RD_KAFKA_RESP_ERR_NO_ERROR:
var_dump($message);
break;
case RD_KAFKA_RESP_ERR__PARTITION_EOF:
echo "No more messages; will wait for more\n";
break;
case RD_KAFKA_RESP_ERR__TIMED_OUT:
echo "Timed out\n";
break;`
default:
throw new \Exception($message->errstr(), $message->err);
break;
}
}
My connection string already has produced events in it that I can confirm by azure-sdk-for-js, using JS SDK I am able to produce and consume events.
When I try to read the $message from $topic it returns as null
PS:
I am currently using the pricing tier as 'Standard' on the azure event hub and it has Kafka Surface 'enabled'
I have tried setting api.version.request as 'true' as well
I am trying to generate checksum for Paytm payment gateway using php.
<?php
// following files need to be included
require_once("./lib/config_paytm.php");
require_once("./lib/encdec_paytm.php");
if (strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0) {
throw new Exception('Request method must be POST');
}
$content = trim(file_get_contents("php://input"));
$decodeData = json_decode($content, true);
// var_dump($decodeData); // this return null
if (!empty($decodeData)) {
$paramList = array();
$paramList["MID"] = $decodeData["MID"]; //Provided by Paytm
$paramList["ORDER_ID"] = $decodeData["ORDER_ID"]; //unique OrderId for every request
$paramList["CUST_ID"] = $decodeData["CUST_ID"]; // unique customer identifier
$paramList["INDUSTRY_TYPE_ID"] = $decodeData["INDUSTRY_TYPE_ID"]; //Provided by Paytm
$paramList["CHANNEL_ID"] = $decodeData["CHANNEL_ID"]; //Provided by Paytm
$paramList["TXN_AMOUNT"] = $decodeData["TXN_AMOUNT"]; // transaction amount
$paramList["WEBSITE"] = $decodeData["WEBSITE"]; //Provided by Paytm
$paramList["CALLBACK_URL"] = $decodeData["CALLBACK_URL"]; //Provided by Paytm
// $paramList["EMAIL"] = $decodeData["MID"]; // customer email id
$paramList["MOBILE_NO"] = $decodeData["MOBILE_NO"]; // customer 10 digit mobile no.
$checkSum = getChecksumFromArray($paramList, PAYTM_MERCHANT_KEY);
if (!empty($checkSum)) {
echo json_encode(array("CHECKSUMHASH" => $checkSum));
} else {
echo json_encode(array("ORDER_ID" => $decodeData["ORDER_ID"]));
}
} else {
echo "Something went wrong";
}
if (!is_array($decodeData)) {
throw new Exception(('Recieved content containes invalid JSON'));
}
Turns out json_decode returns NULL. i.e. $decodeData is NULL.
Tho $content returns right details.
One thing to point out is $content contains PAYTM_MERCHANT_KEY
which have special characters like # and %. Is that's the reason
json_decode is unable to decode the data?
Or there is something wrong with my code?
I need to search for a specific value that I stored in a sheet and get the entire row or the location of the cell that the value is store.
Note: My sheet contains more than 10000 rows of data and I need to update a single column. I'm not interested to fetch all the data from the sheet and update it, as it will affect the performance of my site.
please help me to find a solution.
Better late than never!?
Well I also had the same problem but I needed to change multiple fields, I even looked at the links above but nothing in php. The code below also works if you need to change just one field or several. (google translate)
<?php
$myvalue = 'NEW VALUE';
$values = [[$c_id,]];
// make conn with credentials
$client = new \Google_Client();
$client->setApplicationName('Google Sheets with PHP');
$client->setScopes([\Google_Service_Sheets::SPREADSHEETS]);
$client->setAccessType('offline');
$client->setAuthConfig(__DIR__ . '/cred.json');
$service = new Google_Service_Sheets($client);
$spreadsheetId = "your-id";
// insert custom range to match with name of spreadsheet and range to search
$range = "COMPLETO!A2:A50000";
$cell_id;
$cell_range;
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$values_r = $response->getValues();
if (empty($values_r)) {
print "None Found.\n";
} else {
print "Data found\n";
$range_index = '1';
foreach ($values_r as $row) {
// Show the results in array
$range_index++;
// Match com id do banco de dados
if($row[0] === $c_id){
echo "ID found\n";
echo "$row[0]\n";
echo "Cell ID A${range_index}\n";
$cell_id = "A${range_index}";
// in $cell_range set the effective range to change
// $cell_range = "A${range_index}:CM${range_index}";
break;
}
}
}
$body = new Google_Service_Sheets_ValueRange([
'values' => $values
]);
// try Update
$append_sheet = $service->spreadsheets_values->update($spreadsheetId, $cell_range, $body,['valueInputOption' => 'RAW']);
echo "Update Google Sheet\n";
$conn = null;
?>
I'm trying to authenticate on Bing Ads Api but I'm getting this message:
Authentication failed. Either supplied credentials are invalid or the account is inactive
This is my code:
$UserName = "xxx#hotmail.com";
$Password = "xxx";
$DeveloperToken = "xxx";
$CustomerId = xxx;
$AccountId = xxx;
$wsdl = "https://campaign.api.bingads.microsoft.com/Api/Advertiser/CampaignManagement/V10/CampaignManagementService.svc?singleWsdl";
try
{
$proxy = ClientProxy::ConstructWithAccountAndCustomerId($wsdl, $UserName, $Password, $DeveloperToken, $AccountId, $CustomerId, null);
// Specify one or more campaigns.
$campaigns = array();
$campaign = new Campaign();
$campaign->Name = "Winter Clothing " . $_SERVER['REQUEST_TIME'];
$campaign->Description = "Winter clothing line.";
$campaign->BudgetType = BudgetLimitType::MonthlyBudgetSpendUntilDepleted;
$campaign->MonthlyBudget = 1000.00;
$campaign->TimeZone = "PacificTimeUSCanadaTijuana";
$campaign->DaylightSaving = true;
// Used with FinalUrls shown in the ads that we will add below.
$campaign->TrackingUrlTemplate =
"http://tracker.example.com/?season={_season}&promocode={_promocode}&u={lpurl}";
$campaigns[] = $campaign;
// Add the campaign, ad group, keywords, and ads
$campaignIds = AddCampaigns($proxy, $AccountId, $campaigns);
PrintCampaignIdentifiers($campaignIds);
}
catch (SoapFault $e)
{
// Output the last request/response.
print "\nLast SOAP request/response:\n";
print $proxy->GetWsdl() . "\n";
print $proxy->GetService()->__getLastRequest()."\n";
print $proxy->GetService()->__getLastResponse()."\n";
// Campaign Management service operations can throw AdApiFaultDetail.
if (isset($e->detail->AdApiFaultDetail))
{
// Log this fault.
print "The operation failed with the following faults:\n";
$errors = is_array($e->detail->AdApiFaultDetail->Errors->AdApiError)
? $e->detail->AdApiFaultDetail->Errors->AdApiError
: array('AdApiError' => $e->detail->AdApiFaultDetail->Errors->AdApiError);
// If the AdApiError array is not null, the following are examples of error codes that may be found.
foreach ($errors as $error)
{
print "AdApiError\n";
printf("Code: %d\nError Code: %s\nMessage: %s\n", $error->Code, $error->ErrorCode, $error->Message);
switch ($error->Code)
{
case 105: // InvalidCredentials
break;
case 117: // CallRateExceeded
break;
default:
print "Please see MSDN documentation for more details about the error code output above.\n";
break;
}
}
Sorry for the delayed reply. I noticed that you are setting the UserName to ***#hotmail.com. If you are using an email address login i.e. Microsoft account, then you must use OAuth i.e. set the AuthenticationToken header element instead of setting the UserName/Password fields.