Writing to General Journal, Financial Dimensions not working - axapta

I'm writing to the general journal in x++. I am able to post there currently but the dimensions on the line item are not showing up. The code runs just will have 701100- - - - - and the rest not populated on the line item. i'm not sure why... I've tried several different things... such as below.
ledgerDimensions = ["701100","701100", "MIDWHS", "ACCT", "000001", "AIR", "019-000100"];
journalTrans.parmLedgerDimension(AxdDimensionUtil::getLedgerAccountId(ledgerDimensions));
offsetDimensions = ["701100","701100", "MIDWHS", "ACCT", "000001", "AIR", "019-000100"];
journalTrans.parmOffsetLedgerDimension(AxdDimensionUtil::getLedgerAccountId(offsetDimensions));
journaltrans.save()
and also have tried
// dimensionAttribute = DimensionAttribute::findByName("Location");
// dimensionAttributeValue = //DimensionAttributeValue::findByDimensionAttributeAndValue(dimensionAttribute, "MINOT");
// dimStorage = DimensionAttributeValueSetStorage::find(0);
// dimStorage.addItem(dimensionAttributeValue);
// journalTrans.parmOffsetDefaultDimension(dimStorage.save());
//journalTrans.save()
both are just adding the account number and nothing else.. don't know why!

I used the service for our import interface for general journal.
Below my code, try it this way, it's easy to create the dimensions with this service.
I copied the code from our system and commented it, if you need any further explaination, ask me.
Declarations:
LedgerGeneralJournal ledgerGeneralJournal;
LedgerGeneralJournalService ledgerGeneralJournalService;
AfStronglyTypedDataContainerList journalHeaderCollection;
LedgerGeneralJournal_LedgerJournalTable journalHeader;
AfStronglyTypedDataContainerList journalLineCollection;
AifEntityKeyList journalHeaderCollectionKeyList;
int journalLineCounter; // to create more than one line
int entityKeyCount;
int journalHeaderCounter; // to create more than one journal header if needed
Add parm methods for your counter variables if needed:
public int parmJournalLineCounter(int _journalLineCounter = journalLineCounter)
{
journalLineCounter = _journalLineCounter;
return journalLineCounter;
}
public int parmJournalHeaderCounter(int _journalHeaderCounter = journalHeaderCounter)
{
journalHeaderCounter = _journalHeaderCounter;
return journalHeaderCounter;
}
initializations:
Header
ledgerGeneralJournalService = LedgerGeneralJournalService::construct();
ledgerGeneralJournal = new LedgerGeneralJournal();
journalHeaderCollection = ledgerGeneralJournal.createLedgerJournalTable();
this.parmJournalLineCounter(0); // note to add a parm method for your counter variables
this.parmJournalHeaderCounter(_newInstance ? 1 : this.parmJournalHeaderCounter() + 1); // i added a parameter if more headers are needed
journalHeader = journalHeaderCollection.insertNew(this.parmJournalHeaderCounter());
journalHeader.parmJournalName(contract.parmJournalNameId()); // init your own journal ID
Here my method to create the lines with dimensions.
Note that i only use CostCenter here, if you need more, add them as done with CostCenter (i commented the lines)
protected void writeLine(
str _oldCompany,
TransDate _transDate,
Voucher _voucher,
str _mainAccountNum,
AmountMST _amount,
LedgerJournalTransTxt _transTxt,
CurrencyCode _currencyCode,
str _offsetAccountNum,
str costCenter
)
{
LedgerGeneralJournal_LedgerJournalTrans journalLine;
AifMultiTypeAccount journalLineLedgerDimensionMain;
AifDimensionAttributeValue journalLineDim1Main;
AfStronglyTypedDataContainerList journalLineDimensionCollectionMain;
AifMultiTypeAccount journalLineLedgerDimensionOffset;
str lineMainAccount;
str lineFullAccount;
str lineMainDimensionName = 'CostCenter';
str lineMainDimensionValue;
str lineOffsetAccount;
str lineOffsetFullAccount;
this.parmJournalLineCounter(this.parmJournalLineCounter()+1);
journalLine = this.parmJournalLineCollection().insertNew(this.parmJournalLineCounter());
journalLine.parmLineNum(this.parmJournalLineCounter());
journalLine.parmCompany(CompanyInfo::findByPTROldCompany(_oldCompany).company());
journalLine.parmOffsetCompany(journalLine.parmCompany());
journalLine.parmTransDate(_transDate);
journalLine.parmVoucher(_voucher);
journalLine.parmAccountType(LedgerJournalACType::Ledger);
lineMainAccount = _mainAccountNum;
journalLine.parmAmountCurCredit(_amount > 0 ? 0 : _amount);
journalLine.parmAmountCurDebit(_amount > 0 ? _amount : 0);
journalLine.parmTxt(_transTxt);
journalLine.parmCurrencyCode(_currencyCode);
journalLine.parmOffsetAccountType(LedgerJournalACType::Ledger);
lineOffsetAccount = _offsetAccountNum;
// Create Main Account Dimensions
journalLineLedgerDimensionMain = journalLine.createLedgerDimension();
journalLineLedgerDimensionMain.parmAccount(lineMainAccount);
lineFullAccount = strFmt("%1-%2-", lineMainAccount, costCenter ? lineMainDimensionValue : ''); // if you need more dimensions, add them here first
journalLineLedgerDimensionMain.parmDisplayValue(lineFullAccount);
// and then add the values here like costcenter:
if (costCenter)
{
lineMainDimensionValue = costCenter;
journalLineDimensionCollectionMain = journalLineLedgerDimensionMain.createValues();
journalLineDim1Main = new AifDimensionAttributeValue();
journalLineDim1Main.parmName(lineMainDimensionName);
journalLineDim1Main.parmValue(lineMainDimensionValue);
journalLineDimensionCollectionMain.add(journalLineDim1Main);
journalLineLedgerDimensionMain.parmValues(journalLineDimensionCollectionMain);
}
journalLine.parmLedgerDimension(journalLineLedgerDimensionMain);
// Create Offset Account Dimensions
// same procedure with offset dimensions if needed
if (_offsetAccountNum)
{
journalLineLedgerDimensionOffset = journalLine.createOffsetLedgerDimension();
journalLineLedgerDimensionOffset.parmAccount(lineOffsetAccount);
lineOffsetFullAccount = strFmt("%1--", lineOffsetAccount);
journalLineLedgerDimensionOffset.parmDisplayValue(lineOffsetFullAccount);
journalLine.parmOffsetLedgerDimension(journalLineLedgerDimensionOffset);
}
}
// Create Lines
journalLineCollection = journalHeader.createLedgerJournalTrans();
Finally to write the journal:
public void finalizeLedgerJournal()
{
int keyCount;
List journalIdList;
journalHeader.parmLedgerJournalTrans(journalLineCollection);
ledgerGeneralJournal.parmLedgerJournalTable(journalHeaderCollection);
journalHeaderCollectionKeyList = LedgerGeneralJournalService.create(ledgerGeneralJournal);
// if you need the journalId for further processing:
this.parmEntityKeyCount(journalHeaderCollectionKeyList.getEntityKeyCount());
if (entityKeyCount > 0)
{
for (keyCount = 1;keyCount <= entityKeyCount;keyCount++)
{
if (!contract.parmJournalIdList())
{
contract.parmJournalIdList(new List(Types::String));
}
journalIdList = contract.parmJournalIdList();
journalIdList.addEnd(LedgerJournalTable::findByRecId(journalHeaderCollectionKeyList.getEntityKey(keyCount).parmRecId()).JournalNum);
contract.parmJournalId(LedgerJournalTable::findByRecId(journalHeaderCollectionKeyList.getEntityKey(keyCount).parmRecId()).JournalNum);
}
}
}

Related

Player character won't go in front of buildings

Ok, so I managed to get all the buildings to stay in place, but now for some reason, the player character won't go in front of the buildings.
I tried switching the places in the code where the if the command for checking if the character's going behind the building and the if-else for checking if it's going in front of the code, but nothing changed.
here's the code:
var _dg = depth_grid;
var _inst_num = instance_number(obj_depth_buildings);
//below is for resizing the grid
ds_grid_resize(depth_grid,2, _inst_num);
//below adds instance info to grid
var _yy = 0;
with (obj_depth_buildings)
{
_dg[# 0,_yy] = id;
_dg[# 1,_yy] = y;
_yy++;
}
//below sorts the grid so that the ones with the biggest y variables end up at the top
ds_grid_sort(_dg,1,false);
//below goes through the grid and identifies everything
var _inst;
_yy = 0;
repeat (_inst_num)
{
//below pulls out an id
_inst = _dg[# 0, _yy];
//below gets the instance execute depth
with(_inst)
{
_inst.depth= layer_get_depth("collision") + _yy;
with (obj_nonbuilding_depths)
{
if object_index.y > _inst.y
{
object_index.depth = (_inst.depth + 1);
}
else if object_index.y <= _inst.y
{
object_index.depth = (_inst.depth - 1);
}
}
}
_yy++;
}
you should change the object depth by change the leyar depth in GMS2

Copy table data from one object to another object AX 2012

I'm trying to do a Job which used to Copy and insert Journal Names from one entity to another entity. Below code able to handle only fields only I hardcoded. But I'm trying to do a code which will be useful in future i.e if we add new custom field to the table. My code should able to copy data of that newly custom field added.
static void sa_CopyData(Args _args)
{
LedgerJournalName tblLedgerJournalNameSource, tblLedgerJournalNameDesination;
NumberSequenceTable tblNST, tblNSTCopy;
NumberSequenceScope tblNSS;
Counter countIN, countOUT;
DataAreaId sourceEntity, destinationEntity;
sourceEntity = 'CNUS';
destinationEntity = 'CNEN';
//Journal Names creation
changeCompany(sourceEntity)
{
tblLedgerJournalNameSource = null;
while select * from tblLedgerJournalNameSource
where tblLedgerJournalNameSource.dataAreaId == sourceEntity
{
++countIN;
tblNSTcopy = null; tblNST = null; tblNSS = null;
select * from tblNSTcopy
where tblNSTCopy.RecId == tblLedgerJournalNameSource.NumberSequenceTable;
changeCompany(destinationEntity)
{
tblNST = null; tblNSS = null; tblLedgerJournalNameDesination = null;
select * from tblNST
join tblNSS
where tblNST.NumberSequenceScope == tblNSS.RecId
&& tblNST.NumberSequence == tblNSTCopy.NumberSequence
&& tblNSS.DataArea == destinationEntity;
//Insert only if Journal name is not exists
if(!(LedgerJournalName::find(tblLedgerJournalNameSource.JournalName)))
{
ttsBegin;
tblLedgerJournalNameDesination.initValue();
tblLedgerJournalNameDesination.JournalName = tblLedgerJournalNameSource.JournalName;
tblLedgerJournalNameDesination.Name = tblLedgerJournalNameSource.Name;
tblLedgerJournalNameDesination.JournalType = tblLedgerJournalNameSource.JournalType;
tblLedgerJournalNameDesination.ApproveActive = tblLedgerJournalNameSource.ApproveActive;
tblLedgerJournalNameDesination.ApproveGroupId = tblLedgerJournalNameSource.ApproveGroupId;
tblLedgerJournalNameDesination.NoAutoPost = tblLedgerJournalNameSource.NoAutoPost;
tblLedgerJournalNameDesination.WorkflowApproval = tblLedgerJournalNameSource.WorkflowApproval;
tblLedgerJournalNameDesination.Configuration = tblLedgerJournalNameSource.Configuration;
if (!tblNST.RecId)
{
info(strFmt('Number Sequence is not updated for %1 > Entity %2', tblLedgerJournalNameDesination.JournalName, destinationEntity));
}
tblLedgerJournalNameDesination.NumberSequenceTable = tblNST.recid;
tblLedgerJournalNameDesination.NewVoucher = tblLedgerJournalNameSource.NewVoucher;
tblLedgerJournalNameDesination.BlockUserGroupId = tblLedgerJournalNameSource.BlockUserGroupId;
tblLedgerJournalNameDesination.FixedOffsetAccount = tblLedgerJournalNameSource.FixedOffsetAccount;
tblLedgerJournalNameDesination.OffsetAccountType = tblLedgerJournalNameSource.OffsetAccountType;
tblLedgerJournalNameDesination.OffsetLedgerDimension = tblLedgerJournalNameSource.OffsetLedgerDimension;
tblLedgerJournalNameDesination.LedgerJournalInclTax = tblLedgerJournalNameSource.LedgerJournalInclTax;
tblLedgerJournalNameDesination.insert();
ttsCommit;
++countOUT;
}
}
}
}
info(strFmt('Journal Names Creation > Read: %1, Inserted: %2', countIN, countOUT));
}
Please let me know if you have any suggestions.
Use buf2buf(from, to). https://msdn.microsoft.com/en-us/library/global.buf2buf.aspx
It does not perform an insert, so after you do buf2buf() you can modify any fields you want in the target before doing an insert.
You could do tblLedgerJournalNameDesination.data(tblLedgerJournalNameSource); but that also copies system fields, which you most likely do not want.
You can also look at the source code behind Global::buf2Buf(from, to) and modify that logic if you want.

phpexcel PHPExcel_Shared_Date::isDateTime not working

the file is xlsx and the column format is date MM-DD-YYYY
I have tried several different ways to determine if the value is a date.
PHPExcel_Shared_Date::isDateTime just is not working and do not know why. The data is being save in database and is showing the numbers as such:
41137
41618
42206
42076
41137
42206
41137
41988
my code:
$inputFileType = PHPExcel_IOFactory::identify($fullFilePath);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objReader->setReadDataOnly(false);
$objPHPExcel = $objReader->load($fullFilePath);
$objPHPExcel->setActiveSheetIndex(0);
$worksheetIndex = 1;
$worksheetName = '';
$actualRows = 0;
foreach($objPHPExcel->getWorksheetIterator() as $worksheet)
{
$lineNumber = 1;
$worksheetName = $worksheet->getTitle();
$columnSum = array();
foreach($worksheet->getRowIterator() as $row)
{
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(true); // Loop all cells, even if it is not set = true else set to false
$columnNumber = 1;
foreach($cellIterator as $cell)
{
$dataValue = $cell->getCalculatedValue();
//$dataValue = $cell->getFormattedValue();
if(!empty($dataValue))
{
if(PHPExcel_Shared_Date::isDateTime($cell))
{
$dataValue = date('Y-m-d H', PHPExcel_Shared_Date::ExcelToPHP($dataValue));
}
else
{
// do something
}
}
}
}
}
Analysing the file, there's a few problems.... it doesn't validate cleanly under the Microsoft's Open XML SDK 2.0 productivity tool for MS Office.
Initial problem (which should trigger a loader error in PHPExcel) is the SheetView Zoom Scale, which should be a minimum value of 1. This problem can by "bypassed" by editing Classes/PHPExcel/Worksheet/SheetView.php and modifying the setZoomScaleNormal() method to avoid throwing the exception if the supplied argument value is out of range.
public function setZoomScaleNormal($pValue = 100)
{
if (($pValue >= 1) || is_null($pValue)) {
$this->zoomScaleNormal = $pValue;
// } else {
// throw new PHPExcel_Exception("Scale must be greater than or equal to 1.");
}
return $this;
}
The second problem is that custom number formats are defined with ids in the range 100-118, but all format ids below 164 are documented as reserved for Microsoft use. Excel itself is obviously more forgiving about breaking its documented rules.
You can resolved this by hacking the Classes/PHPExcel/Reader/Excel2007.php file and modifying the load() method, around line 512, by commenting out the check that tells PHPExcel to use the built-in number formats:
// if ((int)$xf["numFmtId"] < 164) {
// $numFmt = PHPExcel_Style_NumberFormat::builtInFormatCode((int)$xf["numFmtId"]);
// }
or
if ((int)$xf["numFmtId"] < 164 &&
PHPExcel_Style_NumberFormat::builtInFormatCodeIndex((int)$xf["numFmtId"]) !== false) {
$numFmt = PHPExcel_Style_NumberFormat::builtInFormatCode((int)$xf["numFmtId"]);
}
There are also issues with font size definitions, but these won't prevent the file from loading

Game Maker Studio: DoSet :: Invalid comparison type

___________________________________________
############################################################################################
FATAL ERROR in
action number 4
of Create Event
for object eng_Global:
DoSet :: Invalid comparison type
at gml_Script_Data_Load (line 1) - ///Data_Load()
############################################################################################
--------------------------------------------------------------------------------------------
stack frame is
gml_Script_Data_Load (line 1)
called from - gml_Object_eng_Global_CreateEvent_4 (line 60) - Data_Load();
I get this error on a comment, not an actual if statement, I can't bypass this without commenting out Data_Load(), which is what loads the users' data.
I recently updated to version 1.4.1567, maybe that is a bug in this version.
I should state that "Connected" and "Guest" variables are both integers (boolean) and do not get set to string at any point in the code.
Here is the Data_Load() script:
///Data_Load()
if (Connected && !Guest) {
ini_open(User_Name+"_NSD_Temp.ini");
// Base Statistics
Level = ini_read_real("Statistics","Level",Level);
Exp_Total = ini_read_real("Statistics","Experience_Total",Exp_Total);
Exp = ini_read_real("Statistics","Experience",Exp);
Exp_Left = ini_read_real("Statistics","Experience_Left",Exp_Left);
Exp_Max = ceil(Level*5);
Gold = ini_read_real("Statistics","Gold",Gold);
Gold_Total = ini_read_real("Statistics","Gold_Total",Gold_Total);
Karma = ini_read_real("Statistics","Karma",Karma);
Karma_Total = ini_read_real("Statistics","Karma_Total",Karma_Total);
Highscore = ini_read_real("Statistics","Highscore",Highscore);
Weapons_Inv_Length = ini_read_real("Statistics","Weapons_Inv_Length",Weapons_Inv_Length);
Stones_Inv_Length = ini_read_real("Statistics","Stones_Inv_Length",Stones_Inv_Length);
Stone_Slots_Owned = ini_read_real("Statistics","Stones_Slots_Owned",Stones_Slots_Owned);
// Game
Ninja_Name = ini_read_string("Game","Ninja_Name",Ninja_Name);
Ninja_Level = ini_read_real("Game","Ninja_Level",Ninja_Level);
Ninja_Health = ini_read_real("Game","Ninja_Health",Ninja_Health);
Ninja_Health_Max = ini_read_real("Game","Ninja_Health_Max",Ninja_Health_Max);
Ninja_Health_Regen_Upgrade = ini_read_real("Game","Ninja_Health_Regen_Upgrade",Ninja_Health_Regen_Upgrade);
Ninja_Health_Regen = Ninja_Health_Base*(Ninja_Health_Regen_Upgrade)/room_speed;
Ninja_Weapon = ini_read_real("Game","Ninja_Weapon",Ninja_Weapon);
Ninja_Colour = ini_read_real("Game","Ninja_Colour",Ninja_Colour);
Ninja_Power = ini_read_real("Game","Ninja_Power",Ninja_Power);
Ninja_Max_Speed = ini_read_real("Game","Ninja_Max_Speed",Ninja_Max_Speed);
Ninja_Attack_Speed = ini_read_real("Game","Ninja_Attack_Speed",Ninja_Attack_Speed);
// Weapons Inventory
for (i=0; i<Weapons_Inv_Length; i++) {
Weapons_Inv[i,0] = i;
Weapons_Inv[i,1] = ini_read_real("Weapons Inventory","Inv_Slot_"+string(i),0);
Weapons[Weapons_Inv[i,1],5] = ini_read_real("Weapons Inventory","Inv_Slot_"+string(i)+"_Owned",Weapons[Weapons_Inv[i,1],5]);
}
// Stones Inventory
for (i=0; i<Stones_Inv_Length; i++) {
Stones_Inv[i,0] = i;
Stones_Inv[i,1] = ini_read_real("Stones Inventory","Inv_Slot_"+string(i),0);
Stones[Stones_Inv[i,1],5] = ini_read_real("Stones Inventory","Inv_Slot_"+string(i)+"_Owned",Stones[Stones_Inv[i,1],5]);
}
// Equipped Stones
for (i=0; i<Stone_Slots_Owned; i++) {
Stone_Slots[i,0] = i;
Stone_Slots[i,1] = ini_read_real("Stones Equipped","Slot_"+string(i),Stone_Slots[i,1]);
}
// Costume Colours
for (i=0; i<array_height_2d(Colours); i++) {
Colours[i,5] = ini_read_real("Costume Colours",Colours[i,1],Colours[i,5]);
}
// Stats
Stat_Clouds_Clicked = ini_read_real("Stats","Clouds_Clicked",Stat_Clouds_Clicked);
Stat_Stars_Clicked = ini_read_real("Stats","Stars_Clicked",Stat_Stars_Clicked);
// Options
SoundFX = ini_read_real("Options","SoundFX",SoundFX);
// Version
Save_Version = ini_read_string("Version","Current",Save_Version);
// Resets
ForceResets = ini_read_string("External","Force_Resets",Force_Resets);
ini_close();
if (ForceResets != Force_Resets) {
Data_Erase();
}
Data_Submit();
} // If Connected & Not Guest
GM's compiler is always weird about those line errors. It often doesn't count blank lines as actual lines.
If you adjust for that issue, the real line of code that is throwing the error is this:
if (ForceResets != Force_Resets) {
Maybe it doesn't like that you're basically asking "If something is not equal to itself", which hardly makes sense. That statement will always evaluate to false, so you should probably remove it.
Seeing as you don't declare var on any of these variables, then you're manipulating the variables on the instance that called this script. If there's somehow a ForceResets script variable, and a ForceResets variable on the calling instance, then this whole thing might be a naming issue. I'm also making this assuming because you called:
ForceResets = ini_read_string("External","Force_Resets",Force_Resets);
Where that third parameter isn't declared anywhere in this script.
All in all, I'd say that you need to clean this script up a little.
Pro Tip: Use for(var i = 0; ... instead of for(i = 0 99% of the time. Otherwise you're leaving this instance with an i variable that it will never use.

Parse Credit Card input from Magnetic Stripe

Does anyone know how to parse a credit card string input from a Magnetic Card Swiper?
I tried a JavaScript parser but never got it to work. This is what the input looks like.
%BNNNNNNNNNNNNNNNN^DOE/JOHN
^1210201901000101000100061000000?;NNNNNNNNNNNNNNNN=12102019010106111001?
The N's are the credit card number.
See the Magnetic Stripe Card entry # Wikipedia:
Track one, Format B:
Start sentinel — one character (generally '%')
Format code="B" — one character (alpha only)
Primary account number (PAN) — up to 19 characters. Usually, but not
always, matches the credit card number
printed on the front of the card.
Field Separator — one character (generally '^')
Name — two to 26 characters
Field Separator — one character (generally '^')
Expiration date — four characters in the form YYMM.
Service code — three characters
Discretionary data — may include Pin Verification Key Indicator (PVKI,
1 character), PIN Verification Value
(PVV, 4 characters), Card Verification
Value or Card Verification Code (CVV
or CVK, 3 characters)
End sentinel — one character (generally '?')
Longitudinal redundancy check (LRC) — one character (Most reader devices
do not return this value when the card
is swiped to the presentation layer,
and use it only to verify the input
internally to the reader.)
I hope the data is fake, otherwise Anyone could get the:
Name
Expiration Date
CVV
And I'm not sure but I think the credit card number (or # of possibilities) can be computed using the LRC.
I did you one better: I made a video showing how to do exactly this with ASP.Net/c#:
http://www.markhagan.me/Samples/CreditCardSwipeMagneticStripProcessing
Here is the section of code that you probably care about:
protected void CardReader_OTC(object sender, EventArgs e)
{
bool CaretPresent = false;
bool EqualPresent = false;
CaretPresent = CardReader.Text.Contains("^");
EqualPresent = CardReader.Text.Contains("=");
if (CaretPresent)
{
string[] CardData = CardReader.Text.Split('^');
//B1234123412341234^CardUser/John^030510100000019301000000877000000?
PersonName.Text = FormatName(CardData[1]);
CardNumber.Text = FormatCardNumber(CardData[0]);
CardExpiration.Text = CardData[2].Substring(2, 2) + "/" + CardData[2].Substring(0, 2);
}
else if (EqualPresent)
{
string[] CardData = CardReader.Text.Split('=');
//1234123412341234=0305101193010877?
CardNumber.Text = FormatCardNumber(CardData[0]);
CardExpiration.Text = CardData[1].Substring(2, 2) + "/" + CardData[1].Substring(0, 2);
}
}
The complete code is on that website I linked above.
From what I can remember:
That is a two-track magnetic strip data - first track starts with % and ends with ?, the second track starts with ; and ends with ?. These are Start/End markers.
The first track is alphanumeric, the second track is numeric, and there is a third track which is numeric also (if my memory serves correct).
The data between the start/end markers can be variable depending on the recording density of the magnetic strip. The higher the density, the more it can be recorded on one track.
Using a regex to get at the data may not be a reliable method to pick out the information required.
And not all credit cards have exactly two tracks, some uses three tracks.
Generally for a card-not present transaction (i.e. MOTO transactions) you will need cc#, expiry and possibly the CVV (aka CVC2 etc). You can obtain the first 2 from a card-swipe as this in the track data. CVV is printed on the card.
Name on card doesn't matter so much. Unless your acquirer and the cardholder are using address verification, but you can find that between ^^, it may have white space padding which you can remove.
The part you want is track2 NNNNNNNNNNNNNNNN=1210 where NNNNN=card number PAN, and 1210 = Expiry date.
Even if track1 is empty (which sometimes it is as it's not used in processing), you will still get the ;?, so you could use the index of the second ; as start of the string and = as the end of the cc# string. With the 4 characters after the = as the expiry.
I would advise getting the card holder to sign something in record of the transaction otherwise they could dispute the card and do a charge-back.
And not all credit cards have exactly two tracks, some uses three tracks.
Only track2 is used for processing and has a standardized format.
Debit cards can't generally be processed (unless they have a visa-debit card or something).
P.S. you shouldn't store cc data in plain text, so try and keep everything in mem or strong encryption.
Try this :
https://github.com/pdamer/CardReader/blob/master/CardReader.js
Or this:
http://blog.cnizz.com/2008/10/16/javascript-snippet-for-handling-credit-card-readers/
I think that what u need
here is my code:
1st the listener to get the data.... this data needs validation which i am looking for help on. A good swipe works fine, but a bad swipe will cause an error in the parser.
$('#cc-dialog-form').keypress(function(e)
{
var charCode = e.which;
//ie? evt = e || window.event;
track_start = '%';
finished = false;
timeout = 100;
track_start_code = track_start.charCodeAt(0);
//console.log('Track_start_code: ' + track_start_code);
//console.log('keycode ' + e.keycode);
//console.log('charcode ' + charCode);
//console.log('track_start_code ' + track_start_code);
if (charCode == track_start_code)
{
collect_track_data = true;
$('#offline_cc_entry').hide();
$('#cc_online').hide();
$('#Manual_CC_DATA').hide();
$('#cc_loading_image').show();
}
if (collect_track_data)
{
if (charCode == $.ui.keyCode.ENTER)
{
//all done
//console.log( card_data);
collect_track_data = false;
$('#cc_loading_image').hide();
$('#Manual_CC_DATA').show();
//console.log("Track Data: " + card_data);
process_swipe_cc_payment(card_data);
card_data = '';
}
else
{
card_data = card_data + String.fromCharCode(charCode);
console.log(card_data);
if (e.preventDefault) e.preventDefault();
e.returnValue=false;
return false;
}
}
else
{
//i am guessing this will be regular input?
if (charCode == $.ui.keyCode.ENTER)
{
process_keyed_or_offline_CC_payment();
}
}
//console.log("which: " + e.which);
//console.log("keyCode: " + e.keyCode);
//track and collect data here?
});
And here is the parser.... note I put it all in one function so I can destroy all the variables so they are not lingering in a browser.
parse_data = true;
if (parse_data)
{
var parsed_card_data = {};
parsed_card_data['card_data'] = card_data;
var tracks = card_data.split("?");
//console.log ("tracks");
//console.log (tracks);
parsed_card_data['track1'] = tracks[0];
parsed_card_data['track2'] = tracks[1];
//if there is a third track we might find it under tracks[2]
//splitting the card data OPTION 1
var track1_parsed = tracks[0].split("^");
//console.log (track1_parsed);
//track1 data....
var card_number_track1 = track1_parsed[0].substring(2);
parsed_card_data['card_number_track1'] = card_number_track1;
var details2_1 = tracks[1].split(";");
details2_1 = details2_1[1].split("=");
var exp_date_track_1 = details2_1[1];
exp_date_track_1 = exp_date_track_1.substring(0, exp_date_track_1.length - 1);
exp_date_track_1 = exp_date_track_1.substring(2, 4) + "/" + exp_date_track_1.substring(0,2);
parsed_card_data['exp_track1'] = exp_date_track_1;
//now check if track one matches track 2...
track2_parsed = tracks[1].split("=");
card_number_track_2 = track2_parsed[0].substring(1);
parsed_card_data['card_number_track_2'] = card_number_track_2;
exp_date_track_2 = track2_parsed[1].substring(0,4);
exp_date_track_2 = exp_date_track_2.substring(2, 4) + "/" + exp_date_track_2.substring(0,2);
parsed_card_data['exp_date_track_2'] = exp_date_track_2;
var primary_account_number = card_number_track1.substring(0,1);
if(card_number_track1 == card_number_track_2 && exp_date_track_1 == exp_date_track_2)
{
//now make a security feature showing the last 4 digits only....
parsed_card_data['secure_card_number'] = "xxxx " + card_number_track1.substring(card_number_track1.length-4, card_number_track1.length);
if(card_number_track1.length == 15)
{
parsed_card_data['card_type'] = "American Express";
}
else if(primary_account_number == 4)
{
parsed_card_data['card_type'] = "Visa";
}
else if(primary_account_number == 5)
{
parsed_card_data['card_type'] = "Master Card";
}
else if(primary_account_number == 6)
{
parsed_card_data['card_type'] = "Discover";
}
else
{
parsed_card_data['card_type'] = false;
}
var names_1 = track1_parsed[1].split("/");
parsed_card_data['first_name'] = names_1[1].trim();
parsed_card_data['last_name'] = names_1[0].trim();
//console.log("return Data");
//console.log(return_data);
}
else
{
parsed_card_data = false;
}
//zero out the variables...
tracks = '';
track1_parsed = '';
card_number_track1 = '';
details2_1 = '';
exp_date_track_1 = '';
track2_parsed = '';
card_number_track_2 = '';
exp_date_track_2 = '';
primary_account_number = '';
}
if(parsed_card_data)
{
//console.log(parsed_card_data);
$('#card_type').val(parsed_card_data['card_type']);
$('#credit_card_number').val(parsed_card_data['secure_card_number']);
$('#expiration').val(parsed_card_data['exp']);
$('#card_holder').val(parsed_card_data['first_name']+ " " + parsed_card_data['last_name']);
//parsed_card_data['track1'] is basically what we want???
$('#CC_SWIPE_INSTRUCTIONS').hide();
$('#CC_DATA').hide();
$('#cc_loading_image').show();
var post_string = {};
post_string['ajax_request'] = 'CREDIT_CARD_PAYMENT';
post_string['amount'] = $('#cc_input').val();
post_string['card_data'] = parsed_card_data;
post_string['pos_sales_invoice_id'] = pos_sales_invoice_id;
post_string['pos_payment_gateway_id'] = $('#pos_payment_gateway_id').val();
post_string['line'] = 'online';
post_string['swipe'] = 'swipe';
card_data = '';
parsed_card_data = {};
var url = 'ajax_requests.php';
$.ajax({
type: 'POST',
url: url,
data: post_string,
async: true,
success: function(response)
{
$('#cc_loading_image').hide();
console.log(response);
$('#CC_RESPONSE').show();
$('#CC_RESPONSE').html(response);
//here we would update the payment table - currently we will just refresh
post_string = '';
}
});
post_string = '';
}
else
{
//error
alert("Read Error");
$( "#cc-dialog-form" ).dialog( "close" );
}

Resources