Need help updating from md5 to sha-512 Authorize.net - php

I am new to authorize.net and i receive an email from them saying that they are phasing out md5 hash and i have to move to sha-512 hash via signature key, but i don't have any idea how to do that.
I have followed the hello world (PHP) steps from their website: https://developer.authorize.net/hello_world/ and it's working fine.
I don't have any md5 on my codes, and I'm thinking that maybe the sdk I'm currently using has that code.
This is my code when charging customer's credit card
function chargeCreditCard($arrayPost, $creditCardNum, $creditCardExp, $creditCardCode)
{
$totalAmountDue = str_replace(',', '', $arrayPost['total-due']);
// Common setup for API credentials
$merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
$merchantAuthentication->setName(X_API_LOGIN);
$merchantAuthentication->setTransactionKey(X_TRAN_KEY);
$refId = 'ref' . time();
// Create the payment data for a credit card
$creditCard = new AnetAPI\CreditCardType();
$creditCard->setCardNumber($creditCardNum);
$creditCard->setExpirationDate($creditCardExp);
$creditCard->setCardCode($creditCardCode);
$paymentOne = new AnetAPI\PaymentType();
$paymentOne->setCreditCard($creditCard);
$order = new AnetAPI\OrderType();
$order->setInvoiceNumber($arrayPost['invoice']);
$order->setDescription(PRODUCT_DESCRIPTION);
// Set the customer's Bill To address
$customerAddress = new AnetAPI\CustomerAddressType();
$customerAddress->setFirstName($arrayPost['fname']);
$customerAddress->setLastName($arrayPost['lname']);
$customerAddress->setCompany($arrayPost['company']);
$customerAddress->setAddress($arrayPost['address']);
$customerAddress->setCity($arrayPost['city']);
$customerAddress->setState($arrayPost['state']);
$customerAddress->setZip($arrayPost['zip']);
$customerAddress->setCountry($arrayPost['country']);
// Create a TransactionRequestType object
$transactionRequestType = new AnetAPI\TransactionRequestType();
$transactionRequestType->setTransactionType("authCaptureTransaction");
$transactionRequestType->setAmount($totalAmountDue);
$transactionRequestType->setOrder($order);
$transactionRequestType->setPayment($paymentOne);
$transactionRequestType->setBillTo($customerAddress);
$request = new AnetAPI\CreateTransactionRequest();
$request->setMerchantAuthentication($merchantAuthentication);
$request->setRefId($refId);
$request->setTransactionRequest($transactionRequestType);
$controller = new AnetController\CreateTransactionController($request);
$response = $controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::PRODUCTION);
if ($response != null) {
$tresponse = $response->getTransactionResponse();
if ($response->getMessages()->getResultCode() == "Ok") {
if ($tresponse != null && $tresponse->getMessages() != null) {
$messages = "";
$errors = "";
$responseCode = $tresponse->getResponseCode();
$rawResponseCode = $tresponse->getRawResponseCode();
$authCode = $tresponse->getAuthCode();
$avsResultCode = $tresponse->getAvsResultCode();
$cvvResultCode = $tresponse->getCvvResultCode();
$cavvResultCode = $tresponse->getCavvResultCode();
$transId = $tresponse->getTransId();
$refTransID = $tresponse->getRefTransID();
$transHash = $tresponse->getTransHash();
$testRequest = $tresponse->getTestRequest();
$accountNumber = $tresponse->getAccountNumber();
$entryMode = $tresponse->getEntryMode();
$accountType = $tresponse->getAccountType();
$splitTenderId = $tresponse->getSplitTenderId();
$prePaidCard = $tresponse->getPrePaidCard();
if($tresponse->getMessages() != null){
$messages .= " Code : " . $tresponse->getMessages()[0]->getCode() . "\n";
$messages .= " Description : " . $tresponse->getMessages()[0]->getDescription() . "\n";
}
if($tresponse->getErrors() != null){
$errors .= " Error code : " . $tresponse->getErrors()[0]->getErrorCode() . "\n";
$errors .= " Error message : " . $tresponse->getErrors()[0]->getErrorText() . "\n";
}
$splitTenderPayments = serialize($tresponse->getSplitTenderPayments());
$userFields = serialize($tresponse->getUserFields());
$shipTo = $tresponse->getShipTo();
$secureAcceptance = $tresponse->getSecureAcceptance();
$emvResponse = $tresponse->getEmvResponse();
$transHashSha2 = $tresponse->getTransHashSha2();
//$profile = $tresponse->getProfile();
$profile = "";
//SAVE PERSONAL DETAILS
$personal_detail_id = $this->objEcommerceModel->savePersonalDetails($arrayPost['fname'], $arrayPost['lname'], $arrayPost['company'], $arrayPost['address'], $arrayPost['city'], $arrayPost['state'], $arrayPost['zip'], $arrayPost['country']);
//SAVE MERCHANT LOGS
$this->objEcommerceModel->saveMerchantTransactionLogs($personal_detail_id, $responseCode, $rawResponseCode, $authCode, $avsResultCode, $cvvResultCode, $cavvResultCode, $transId, $refTransID, $transHash, $testRequest, $accountNumber, $entryMode, $accountType, $splitTenderId, $prePaidCard, $messages, $errors, $splitTenderPayments, $userFields, $shipTo, $secureAcceptance, $emvResponse, $transHashSha2, $profile);
return 'Success';
} else {
$msg = "Transaction Failed \n";
if ($tresponse->getErrors() != null) {
$msg .= " Error code : " . $tresponse->getErrors()[0]->getErrorCode() . "\n";
$msg .= " Error message : " . $tresponse->getErrors()[0]->getErrorText() . "\n";
}
}
} else {
$msg = "Transaction Failed \n";
$tresponse = $response->getTransactionResponse();
if ($tresponse != null && $tresponse->getErrors() != null) {
$msg .= " Error code : " . $tresponse->getErrors()[0]->getErrorCode() . "\n";
$msg .= " Error message : " . $tresponse->getErrors()[0]->getErrorText() . "\n";
} else {
$msg .= " Error code : " . $response->getMessages()->getMessage()[0]->getCode() . "\n";
$msg .= " Error message : " . $response->getMessages()->getMessage()[0]->getText() . "\n";
}
}
} else {
$msg .= "No response returned \n";
}
}

The MD5 hash is only used to verify a transaction response is actually from Authorize.Net. This code processes a transaction using the AIM API which typically does not need to verify the response since you get it as a result of your direct call to Authorize.Net. The MD5 hash is typically used by SIM and DPM API users who do not have a direct connection to Authorize.Net and thus need a way to verify the response is authentic.

Related

When I try to connect to google spreadsheet I got error -> 404 "you need permission"

I am trying to get in a Google spreadsheet via the PHP API Client, but I am getting a 404->You need permission. The file has been given edit permissions to my user, which is the user I used to set up the JSON credentials via the Google Developers Console. What am I missing?
Here is my code :
$this->client = new Google_Client();
$this->client->setApplicationName('BreezingForms Google Drive Spreadsheets');
$this->client->addScope(array('https://spreadsheets.google.com/feeds'));
// testing:
// 197794184197-bt2q9knrdu1i54vgladd97ob196k4c6s.apps.googleusercontent.com
// dImciIWj3WNOrIcYRbu9MFeA
if (isset($_POST['gdata_custom_client_id']) && trim($_POST['gdata_custom_client_id']) != '' && trim($_POST['gdata_custom_client_secret']) != '') {
$this->client->setClientId(trim($_POST['gdata_custom_client_id']));
$this->client->setClientSecret(trim($_POST['gdata_custom_client_secret']));
$db->setQuery("Update #__breezingforms_addons_gdata Set custom_client_id = " . $db->quote(trim($_POST['gdata_custom_client_id'])) . ", custom_client_secret = " . $db->quote(trim($_POST['gdata_custom_client_secret'])) . " Where form_id = " . intval($_REQUEST['form']));
$db->execute();
} else {
$form_id = -1;
if(JRequest::getInt('ff_form',-1) > 0){
$form_id = JRequest::getInt('ff_form',-1);
}else if(isset($_REQUEST['form'])){
$form_id = intval($_REQUEST['form']);
}
$db->setQuery("Select * From #__breezingforms_addons_gdata Where form_id = " . $db->quote($form_id));
$client = $db->loadObject();
if ($client) {
$this->client->setClientId($client->custom_client_id);
$this->client->setClientSecret($client->custom_client_secret);
}
}
$this->client->setApprovalPrompt('auto');
$this->client->setPrompt('consent');
$this->client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$this->client->setAccessType('offline');
}
function onPropertiesDisplay($form_id, $tabs){
if(!$form_id) return '';
$error = '';
$db = JFactory::getDBO();
$db->setQuery("Select `title`,`name`,`id` From #__facileforms_elements Where form = " . intval($form_id) . " And `title` Not In ('bfFakeTitle','bfFakeTitle2','bfFakeTitle3','bfFakeTitle4','bfFakeTitle5') And `type` Not In ('','UNKNOWN') Order By ordering");
$breezingforms_fields = $db->loadObjectList();
$db->setQuery("Select `enabled`, `username`, `password`, `worksheet_id`, `spreadsheet_id`, `fields`, `meta`, `debug` From #__breezingforms_addons_gdata Where form_id = " . intval($form_id));
$gdata = $db->loadObject();
if( $gdata === null ){
$gdata = new stdClass();
$gdata->username = '';
$gdata->password = '';
$gdata->enabled = 0;
$gdata->worksheet_id = '';
$gdata->spreadsheet_id = '';
$gdata->fields = '';
$gdata->meta = '';
$gdata->debug = 0;
}
$gdata->fields = explode('/,/', $gdata->fields);
$gdata->meta = explode('/,/', $gdata->meta);
$gdata_spreadsheets = array();
$gdata_worksheets = array();
$gdata_columns = array();
//if( $gdata->enabled == 1 ){
try{
$spreadsheetFeed = null;
$auth_url = '';
$db->setQuery("Select password From #__breezingforms_addons_gdata Where form_id = " . intval($form_id));
$accessToken = $db->loadResult();
// $accessToken='{"access_token":"ya29.a0ARrdaM--_ZKuuOfK3CyRsAubHXYgGlwMhLfg9x10fLbYhOq0Polqela1GjGYjhBO9Fi0v7LKuDauV4qA-uFLCilun0_NuQDuEFHjYb9iX0rcOjS6YWMDTHfe2UsyxJkyvlULrMIV7sh4_-_-vORj0kh6sw7o","expires_in":3599,"refresh_token":"1\/\/09aQ4SG_STBzBCgYIARAAGAkSNwF-L9Ir9FDHRmbwiLoCXglVSksa1tfyes6AdQedbTx2dqZKGh-ZTMT-M2i665x18NzT1luWu1Q","scope":"https:\/\/www.googleapis.com\/auth\/spreadsheets","token_type":"Bearer","created":1635842294}';
if(!$accessToken){
$auth_url = $this->client->createAuthUrl();
} else {
try{
$this->client->setAccessToken($accessToken);
$token = json_decode($accessToken);
if ($this->client->isAccessTokenExpired()) {
$this->client->refreshToken($token->refresh_token);
$tok = json_encode($this->client->getAccessToken());
$token = json_decode($tok);
$db->setQuery("Update #__breezingforms_addons_gdata set password = " . $db->quote($tok) . " Where form_id = " . intval($form_id));
$db->execute();
}
$serviceRequest = new DefaultServiceRequest($token->access_token, $token->token_type);
ServiceRequestFactory::setInstance($serviceRequest);
$spreadsheetService = new Google\Spreadsheet\SpreadsheetService();
$spreadsheetFeed = $spreadsheetService->getSpreadsheets();
}catch(Exception $ee){
//$accessToken = null;
//$auth_url = $this->client->createAuthUrl();
$error=$ee->getMessage();
}
}
if($spreadsheetFeed !== null){
foreach($spreadsheetFeed As $sheet){
$gdata_spreadsheets[$sheet->getId()] = $sheet->getTitle();
}
}
if($gdata->spreadsheet_id != '' && isset( $gdata_spreadsheets[$gdata->spreadsheet_id] ) && $spreadsheetFeed !== null){
$spreadsheet = $spreadsheetFeed->getByTitle($gdata_spreadsheets[$gdata->spreadsheet_id]);
$worksheetFeed = $spreadsheet->getWorksheets();
foreach ( $worksheetFeed as $sheet ){
$gdata_worksheets[$sheet->getId()] = $sheet->getTitle();
}
if($gdata->worksheet_id != '' && isset( $gdata_worksheets[$gdata->worksheet_id] )){
$worksheet = $worksheetFeed->getByTitle($gdata_worksheets[$gdata->worksheet_id]);
$cellFeed = $worksheet->getCellFeed();
foreach($cellFeed->getEntries() as $cellEntry) {
$row = $cellEntry->getRow();
$col = $cellEntry->getColumn();
if( $row > 1 ){
break;
}
$gdata_columns[] = $cellFeed->getCell($row, $col)->getContent();
}
}
}
} catch(Exception $e){
$error = $e->getMessage();
}
//}
ob_start();
$version = new JVersion();
if(version_compare($version->getShortVersion(), '1.6', '<')){
require_once JPATH_SITE . DS . 'plugins' . DS . 'breezingforms_addons' . DS . 'breezingforms_addons_gdata_tmpl' . DS . 'properties.php';
}else{
require_once JPATH_SITE . DS . 'plugins' . DS . 'breezingforms_addons' . DS . 'gdata' . DS . 'breezingforms_addons_gdata_tmpl' . DS . 'properties.php';
}
$c = ob_get_contents();
ob_end_clean();
return $c;
}
function onPropertiesSave($form_id){
if(!$form_id) return '';
$accessToken = '';
$reset_accessToken = false;
if(isset($_POST['gdata_code']) && $_POST['gdata_code'] != ''){
$accessToken =json_encode($this->client->authenticate($_POST['gdata_code']));
}
if(isset($_POST['gdata_reset'])){
$reset_accessToken = true;
$accessToken = '';
}
if(isset($_POST['gdata_fields']) && is_array($_POST['gdata_fields'])){
$_POST['gdata_fields'] = implode('/,/', $_POST['gdata_fields']);
}else{
$_POST['gdata_fields'] = '';
}
if(isset($_POST['gdata_meta']) && is_array($_POST['gdata_meta'])){
$_POST['gdata_meta'] = implode('/,/', $_POST['gdata_meta']);
}else{
$_POST['gdata_meta'] = '';
}
$db = JFactory::getDBO();
$db->setQuery("Select form_id From #__breezingforms_addons_gdata Where form_id = " . intval($form_id));
$exists = $db->loadResult();
if(!$exists){
$db->setQuery("Insert Into #__breezingforms_addons_gdata (
`form_id`, `enabled`,`password`,`spreadsheet_id`,`worksheet_id`,`fields`,`meta`) Values
( ".intval($form_id).",
".JRequest::getInt('gdata_enabled', 0).",
".($accessToken ? $db->quote($accessToken).',' : '"",')."
".$db->quote(hexToStr(JRequest::getVar('gdata_spreadsheet_id', "''"))).",
".$db->quote(hexToStr(JRequest::getVar('gdata_worksheet_id', "''"))).",
".$db->quote($_POST['gdata_fields']).",
".$db->quote($_POST['gdata_meta'])."
)");
$db->query();
}
else {
//$token1=json_encode(array("username" => "text",
//"password" => "text"));
$gspid = $reset_accessToken ? "''" : hexToStr(JRequest::getVar('gdata_spreadsheet_id', "''"));
$wid = $reset_accessToken ? "''" : hexToStr(JRequest::getVar('gdata_worksheet_id', "''"));
$db->setQuery("Update #__breezingforms_addons_gdata Set
`enabled` = ".JRequest::getInt('gdata_enabled', 0).",
".($accessToken || $reset_accessToken ? "`password` = " . $db->quote($accessToken).',' : '')."
`spreadsheet_id` = ".$db->quote(trim($gspid) == '' ? "''" : $gspid).",
`worksheet_id` = ".$db->quote(trim($wid) == '' ? "''" : $wid).",
`fields` = ".$db->quote($_POST['gdata_fields']).",
`meta` = ".$db->quote($_POST['gdata_meta'])."
".($reset_accessToken ? ",`custom_client_id` = " . $db->quote("34263101371-4rcre0p6r9ehuhoat1d6ls8u84etuanp.apps.googleusercontent.com").', `custom_client_secret` = ' . $db->quote("IDq59sdLo6wC81KCUweDKVf2") : '')."
Where form_id = " . intval($form_id) . "
");
$db->query();
}
I give permission app to access on my Goole account, then I get auth token back from the Google account, but then I got "you to need permission"!?
Any idea?
The error you are encountering comes from the fact that the https://spreadsheets.google.com/feeds scope you are using is an invalid one.
The list of authorized scopes for Sheets API is the following one:
https://www.googleapis.com/auth/drive which allows you to see, edit, create, and delete all of your Google Drive files;
https://www.googleapis.com/auth/drive.file which allows you to view and manage Google Drive files and folders that you have opened or created with this app;
https://www.googleapis.com/auth/drive.readonly which allows you to see and download all your Google Drive files;
https://www.googleapis.com/auth/spreadsheets which allows you to see, edit, create, and delete your spreadsheets in Google Drive;
https://www.googleapis.com/auth/spreadsheets.readonly which allows you to view your Google Spreadsheets.
Therefore, depending on the exact actions you want to allow your users to make, you will have to choose one of the scopes from the list above. Moreover, make sure to delete the token.json file if you end up modifying the scopes.
Reference
Sheets API Authorize Requests.

RESTful API with Volley Kotlin doens't work

I've seen many others questions and answers on the Web, but I haven't found the solution to my issue.
Basically, I've create an API page. If I use a API tester (such as apitester.com) it works correctly.
Instead, when I do POST request from Volley (Android-Kotlin) it doens't work.
It looks like params are empty.
I can't understand the problem.
PHP Code:
include_once($_SERVER['DOCUMENT_ROOT'] . "/include/variables.php");
global $localhost_db, $username_db, $password_db, $database_api;
header("Content-Type:application/json");
if ($c = new mysqli($localhost_db, $username_db, $password_db, $database_api)) {
$c->set_charset("utf8");
//POST request -> insert a new data to database
$data = json_decode(file_get_contents('php://input'), true);
$condition = isset($data["logged"]) && ($data["logged"] == 0 || $data["logged"] == 1) && isset($data["username"]) && isset($data["language"]);
if ($condition) {
$year = date('Y');
$month = date("m");
$day = date("d");
$sql = "SELECT `date` FROM statistics WHERE `username`='" . $data["username"] . "' AND YEAR(`date`)=" . $year . " AND MONTH(`date`)=" . $month . " AND DAY(`date`)=" . $day;
if ($r = $c->query($sql)) {
if ($r->num_rows == 0) {
$sql = "INSERT INTO statistics(`id`, `date`, `logged`, `username`, `language`) VALUES(NULL,'" . date("Y-m-d H:i:s") . "', '" . $data["logged"] . "', '" . $data["username"] . "', '" . $data["language"] . "')";
if ($r = $c->query($sql)) {
response(200, "OK", "Record inserted correctly");
} else {
response(500, "Error", "Can't insert record on database");
}
} else {
response(400, "Error", "Record has already inserted today");
}
} else {
response(400, "Error", "Something was wrong in POST request (1)");
}
} else {
response(400, "Error", "Something was wrong in POST request (2). Received data> logged: " . $data["logged"] . ", language: " . $data["language"] . ", username: " . $data["username"]);
}
} else {
echo "Failed to connect to the database.";
response(500, "Error", "Can't connect to the database");
}
function response($response_code, $response_status, $response_description)
{
$response['code'] = $response_code;
$response['status'] = $response_status;
$response['description'] = $response_description;
$json_response = json_encode($response);
echo $json_response;
}
?>
instead the Android Kotlin code:
var params = JSONObject()
params.put("username", username)
params.put("logged", logged)
params.put("language", language)
val que = Volley.newRequestQueue(this)
val req = object : JsonObjectRequest(Request.Method.POST, url_statistics, params,
Response.Listener {
val jsonResult = it.toString()
var jsonResultArray = arrayOf(jsonResult, "")
println(jsonResult)
val jsonObj = JSONObject(
jsonResultArray[0].substring(
jsonResultArray[0].indexOf("{"),
jsonResultArray[0].lastIndexOf("}") + 1
)
)
if (jsonObj.getString("code")
.toInt() == 200
) {//Successful}
else {//Error}
}, Response.ErrorListener {
//Error
}
){}
que.add(req)
do this:
$username = $_POST['username']
instead of:
$data = json_decode(file_get_contents('php://input'), true);

Using data retrieved from a form submission in another form [PHP]

I have a small form that allows a user to look up user data, they just enter the user ID and it retrieves data from a series of tables and displays this data.
The logic I was going for was press one button to get data, press another to use it.
Here is the form:
One button on the form is called Get data and the other is called Onboard this user.
So each button has a really basic
if(isset($_POST['nameofbutton']))
{
// Get data
}
if(isset($_POST['nameofbutton']))
{
// Send data
}
One button gets the data using this script
if(isset($_POST['submit']))
{
// Set some variables if necessary
$id = $_POST['id'];
// Write sql statement with ? as placeholders for any values
$sql = "SELECT *
FROM tblInvestor
LEFT JOIN tblReyker ON tblInvestor.invUserId = tblReyker.ReyNPI_Id
LEFT JOIN tblDeclarations ON tblInvestor.invUserId = tblDeclarations.invUserId
WHERE tblInvestor.invUserId = ?";
// Prepare the SQL statement using the database connection parameter
if($stmt = $dbconINV->prepare($sql))
{
// Bind any necessary variables
if($stmt->bind_param('s', $id))
{
$result = $stmt->execute();
// If the statement ran successfully
if($result)
{
$result = $stmt->get_result();
if($result->num_rows >= 1)
{
while($row = $result->fetch_assoc())
{
// If there are result get them here
//
$userId = $row['invUserId'];
//
$email = $row['invUserEmail'];
// [Not Encrypted]
$title = $row['invUserTitle'];
// [Encrypted]
$forename = $row['invUserForename'];
// [Encrypted]
$surname = $row['invUserSurname'];
// [Not encrypted]
$countryOfBirth = $row['ReyCountryOfBirth'];
//
$emailType = $row['ReyEmailType'];
//
$dateOfBirth = $row['ReyDateofbirth'];
//
$nationalInsurance = $row['ReyNI'];
//
$primaryAddress = $row['ReyPrimaryAddress'];
//
$primaryTelephone = $row['ReyPrimaryTelephone'];
//
$bankAccountDetails = $row['ReyBA'];
//
$citizenshipDetails = $row['ReyCitizenship'];
//
$planType = $row['ReyPlanType'];
//
$externalPlanId = $row['ReyExtPlanID'];
if($forename != "")
{
$forename = $security->decrypt($forename);
}
if($surname != "")
{
$surname = $security->decrypt($surname);
}
if($dateOfBirth != "")
{
$dateOfBirth = $security->decrypt($dateOfBirth);
}
if($nationalInsurance != "")
{
$nationalInsurance = $security->decrypt($nationalInsurance);
}
if($primaryAddress != "")
{
$primaryAddress = $security->decrypt($primaryAddress);
$primaryAddressDecoded = json_decode($primaryAddress, true);
}
if($primaryTelephone != "")
{
$primaryTelephone = $security->decrypt($primaryTelephone);
$primaryTelephoneDecoded = json_decode($primaryTelephone, true);
}
if($bankAccountDetails != "")
{
$bankAccountDetails = $security->decrypt($bankAccountDetails);
$bankAccountDetailsDecoded = json_decode($bankAccountDetails, true);
}
if($citizenshipDetails != "")
{
$citizenshipDetails = $security->decrypt($citizenshipDetails);
$citizenshipDetailsDecoded = json_decode($citizenshipDetails, true);
}
echo "User ID " . $userId . "<br />";
echo "Plan ID " . $planType . "<br />";
echo "External Plan ID " . $externalPlanId . "<br />";
echo "Email: " . $email . "<br />";
echo "Title: " . $title . "<br />";
echo "Forename: " . $forename . "<br />";
echo "Surname: " . $surname . "<br />";
echo "Country of birth: " . $countryOfBirth . "<br />";
echo "Email type: " . $emailType . "<br />";
echo "Date of birth: " . $dateOfBirth . "<br />";
echo "National Insurance Number: " . $nationalInsurance . "<br />";
$_SESSION['userId'] = $userId;
$_SESSION['planType'] = $planType;
$_SESSION['externalPlanId'] = $externalPlanId;
$_SESSION['title'] = $title;
$_SESSION['forename'] = $forename;
$_SESSION['surname'] = $surname;
$_SESSION['countryOfBirth'] = $countryOfBirth;
$_SESSION['emailType'] = $emailType;
$_SESSION['dateOfBirth'] = $dateOfBirth;
$_SESSION['nationalInsurance'] = $nationalInsurance;
$_SESSION['address'] = $primaryAddressDecoded;
$_SESSION['citizenship'] = $citizenshipDetailsDecoded;
$_SESSION['telephone'] = $primaryTelephoneDecoded;
$_SESSION['bankAccount'] = $bankAccountDetailsDecoded;
// Address
foreach($primaryAddressDecoded as $addressKey => $addressValue)
{
echo $addressKey . " " . $addressValue . "<br />";
}
// Address
foreach($citizenshipDetailsDecoded as $addressKey => $addressValue)
{
echo $addressKey . " " . $addressValue . "<br />";
}
// Address
foreach($primaryTelephoneDecoded as $addressKey => $addressValue)
{
echo $addressKey . " " . $addressValue . "<br />";
}
// Address
foreach($bankAccountDetailsDecoded as $addressKey => $addressValue)
{
echo $addressKey . " " . $addressValue . "<br />";
}
}
}
else // the statement returned 0 results
{
// Deal with the nothingness
echo "No data found";
}
}
else // the sql didnt execute
{
// Somethings gone wrong here
echo "No execution";
}
}
else // the binding was wrong
{
// Check your bindings
echo "Binding error";
}
}
else // There was an error preparing the sql statement (its wrong)
{
// the sql is wrong
echo "SQL error " . $dbconINV->error;
}
}
Some of the data is encrypted so I decrypt it, also some of the data is a JSON array so I use json_decode(). Once I get the data I store it all in the current session.
The other button does an API call using the data in the session
if(isset($_POST['onboard']))
{
$userId = $_SESSION['userId'];
$planType = $_SESSION['planType'];
$externalPlanId = $_SESSION['externalPlanId'];
$title = $_SESSION['title'];
$forename = $_SESSION['forename'];
$surname = $_SESSION['surname'];
$countryOfBirth = $_SESSION['countryOfBirth'];
$emailType = $_SESSION['emailType'];
$dateOfBirth = $_SESSION['dateOfBirth'];
$nationalInsurance = $_SESSION['nationalInsurance'];
$primaryAddressDecoded = $_SESSION['address'];
$citizenshipDetailsDecoded = $_SESSION['citizenship'];
$primaryTelephoneDecoded = $_SESSION['telephone'];
$bankAccountDetailsDecoded = $_SESSION['bankAccount'];
// Create an array to work with
$onboardingData = array(
// Generic details
"Title" => $title,
"Forenames" => $forename,
"Surname" => $surname,
"CountryOfBirth" => $countryOfBirth,
"EmailAddress" => $email,
"EmailType" => $emailType,
"BirthDate" => $dateOfBirth,
"Suffix" => null,
"NationalInsuranceNumber" => $nationalInsurance,
// Primary address
"PrimaryAddress" => $primaryAddress,
// Additional addresses (as an array)
"AdditionalAddresses" => null,
// Primary telephone
"PrimaryTelephone" => $primaryTelephone,
// Additional telephone
"AdditionalTelephone" => null,
// Bank accounts
"BankAccount" => $bankAccountDetails,
// Primary citizenship
"PrimaryCitizenship" => $citizenshipDetails,
"AdditionalCitizenship" => null,
"ExternalCustomerId" => $userId,
"ExternalPlanId" => $externalPlanId,
"PlanType" => $planType
);
// Ensure the array has data in it
if(!empty($onboardingData))
{
// Usually where I do API call
die(var_dump($onboardingData));
}
}
My issue is that when I try to add the decoded JSON arrays to the session they are dumped out as Array, so when I try to build $onboardingData the arrays are NULL.
Am I overcomplicating this?
PHP Sessions can hold arrays, but bear in mind that PHP does not support objects and handles them through it's own class called "stdClass".
It is not uncommon practice to store JSON Strings as one value and decode them on demand.
$_SESSION['mySession'] = '{"name":"Matt", "bestAnswer":true}';
$mySession = json_decode($_SESSION['mySession'], true); // true because I prefer arrays in PHP
$name = $mySession['name'];
Without my fussy array requirements:
$mySession = json_decode($_SESSION['mySession']);
$name = $mySession->name;

How do I process PHP in batches?

I using PHP to connect a MySQL DB and a 3rd party API. When using the following script I keep getting a timeout error. The owners of the API I'm using suggest limiting each call to 50 records. I'm new to PHP and despite all my Googling can't work out how to batch process. The script is as follows:
<?php
include('config.inc.php');
$conn = new mysqli($hostname, $username, $passwd, $db);
if ($conn->connect_error) {
echo 'Database connection failed...' . 'Error: ' . $conn->connect_errno . ' ' . $conn->connect_error;
exit;
} else {
$conn->set_charset('utf8');
}
$sql = "SELECT Duedate, Invoicenumber, customername, txndate, itemref_fullname, xeroaccountnumber, Description, Quantity, rate, XEROTAXTYPE FROM invoicelinedetail";
$rs = $conn->query($sql);
if ($rs == false) {
} else {
require('xeroconfig.php');
$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) {
echo 'Error: ' . $check . PHP_EOL;
}
} else {
$session = persistSession(array(
'oauth_token' => $XeroOAuth->config ['consumer_key'],
'oauth_token_secret' => $XeroOAuth->config ['shared_secret'],
'oauth_session_handle' => ''
));
$oauthSession = retrieveSession();
if (isset($oauthSession ['oauth_token'])) {
$XeroOAuth->config ['access_token'] = $oauthSession ['oauth_token'];
$XeroOAuth->config ['access_token_secret'] = $oauthSession ['oauth_token_secret'];
$xml = "<Invoices>\n";
foreach ($rs as $row) {
$xml .= "<Invoice>\n";
$xml .= "<Type>ACCREC</Type>\n";
$xml .= "<Contact>\n";
$xml .= "<Name>" . xmlEscape($row['customername']) . "</Name>\n";
$xml .= "</Contact>\n";
$xml .= "<Date>" . xmlEscape($row['txndate']) . "</Date>\n";
$xml .= "<DueDate>" . xmlEscape($row['Duedate']) . "</DueDate>\n";
$xml .= "</Invoice>\n";
}
$xml .= "</Invoices>";
#echo $xml;
$response = $XeroOAuth->request('POST', $XeroOAuth->url('Invoices', 'core'), array(), $xml);
if ($XeroOAuth->response['code'] == 200) {
$invoice = $XeroOAuth->parseResponse($XeroOAuth->response['response'], $XeroOAuth->response['format']);
echo "" . count($invoice->invoices[0]) . " invoice created/updated in this Xero organisation.";
if (count($invoice->Invoices[0]) > 0) {
echo "The first one is: </br>";
pr($Invoice->Invoices[0]->Invoice);
}
} else {
outputError($XeroOAuth);
}
}
}
}
You case use the % operator to make a request every 50 invoices. Something like this (you may have to change count($rs) to something else depending on what type of object it is).
<?php
include('config.inc.php');
$conn = new mysqli($hostname, $username, $passwd, $db);
if ($conn->connect_error) {
echo 'Database connection failed...' . 'Error: ' . $conn->connect_errno . ' ' . $conn->connect_error;
exit;
} else {
$conn->set_charset('utf8');
}
$sql = "SELECT Duedate, Invoicenumber, customername, txndate, itemref_fullname, xeroaccountnumber, Description, Quantity, rate, XEROTAXTYPE FROM invoicelinedetail";
$rs = $conn->query($sql);
if ($rs == false) {
} else {
require('xeroconfig.php');
$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) {
echo 'Error: ' . $check . PHP_EOL;
}
} else {
$session = persistSession(array(
'oauth_token' => $XeroOAuth->config ['consumer_key'],
'oauth_token_secret' => $XeroOAuth->config ['shared_secret'],
'oauth_session_handle' => ''
));
$oauthSession = retrieveSession();
if (isset($oauthSession ['oauth_token'])) {
$XeroOAuth->config ['access_token'] = $oauthSession ['oauth_token'];
$XeroOAuth->config ['access_token_secret'] = $oauthSession ['oauth_token_secret'];
$invoice_counter = 0;
foreach ($rs as $row) {
if(++$invoice_counter % 50 === 1) {
$xml = "<Invoices>\n";
}
$xml .= "<Invoice>\n";
$xml .= "<Type>ACCREC</Type>\n";
$xml .= "<Contact>\n";
$xml .= "<Name>" . xmlEscape($row['customername']) . "</Name>\n";
$xml .= "</Contact>\n";
$xml .= "<Date>" . xmlEscape($row['txndate']) . "</Date>\n";
$xml .= "<DueDate>" . xmlEscape($row['Duedate']) . "</DueDate>\n";
$xml .= "</Invoice>\n";
if($invoice_counter % 50 === 0 || $invoice_counter == count($rs)) {
$xml .= "</Invoices>\n";
#echo $xml;
$response = $XeroOAuth->request('POST', $XeroOAuth->url('Invoices', 'core'), array(), $xml);
if ($XeroOAuth->response['code'] == 200) {
$invoice = $XeroOAuth->parseResponse($XeroOAuth->response['response'], $XeroOAuth->response['format']);
echo "" . count($invoice->invoices[0]) . " invoice created/updated in this Xero organisation.";
if (count($invoice->Invoices[0]) > 0) {
echo "The first one is: </br>";
pr($Invoice->Invoices[0]->Invoice);
}
} else {
outputError($XeroOAuth);
}
}
}
}
}
}

simple html dom php curl error cannot grab text i need

i am using the following code in my cript to grab a part of source code i need
but it get this error
Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting ')' in /home/cyberhos/public_html/CH/tes.php on line 151
simple_html_dom.php is already issued in my script elswhere
if (isset($_POST['mp'], $_POST['delim'], $_POST['submit'])) {
$mps = preg_split('/\r\n|\r|\n/', $_POST['mp']);
// Create an array to store results
$result_data = array();
// Iterate over requests
foreach ($mps as $mp) {
$mp = explode($_POST['delim'], $mp);
// Store the account details in variables
list($email, $password) = $mp;
// Get HTML data
$html_string = checkmail($email, $password);
$html = str_get_html($html_string);
$body = $html->find('div[id="welcome_text"]);
// Prepare a reusable string
$result_string = "Checked " . $email . " : " . $password . " is ";
// Append necessary word to it
if ($html>welcome_text === "Welcome to Tesco.com. We hope that you enjoy your visit.") {
$result_string .= "LIVE";
} else {
$result_string .= "DEAD";
}
how can i fix this error is there any way that i can fix this error so my script works properly
heres the part of source code i am trying to get
<div id="welcome_text" class="">
<div class="box">
Welcome to Tesco.com. We hope that you enjoy your visit.
<a id="ctl00_ctl00_lnkLogin" href="javascript:__doPostBack('ctl00$ctl00$lnkLogin','')">Log out</a>
</div>
you miss ' in this line edited is
$body = $html->find('div[id="welcome_text"]');
your edited code
if (isset($_POST['mp'], $_POST['delim'], $_POST['submit'])) {
$mps = preg_split('/\r\n|\r|\n/', $_POST['mp']);
// Create an array to store results
$result_data = array();
// Iterate over requests
foreach ($mps as $mp) {
$mp = explode($_POST['delim'], $mp);
// Store the account details in variables
list($email, $password) = $mp;
// Get HTML data
$html_string = checkmail($email, $password);
$html = str_get_html($html_string);
$body = $html->find('div[id="welcome_text"]');
// Prepare a reusable string
$result_string = "Checked " . $email . " : " . $password . " is ";
// Append necessary word to it
if ($html>welcome_text === "Welcome to Tesco.com. We hope that you enjoy your visit.") {
$result_string .= "LIVE";
} else {
$result_string .= "DEAD";
}
}
}

Categories