Salesforce To Authorize.Net Integration

A Little Background About This Post:


In last 2 years working as independent consultant/developer , I got salesforce to Authorize.net integration request some 7-8 times . This is one of the popular integration these days .
I worked over this piece of integration and thought of sharing this with community .

General Requirements :

1. We would like our customers to pay via credit card ,bank(ACH) details automatically .
2. We would like to send them a payment link at a frequency, customers can open link and can pay us .
3. We would like to track transactions as well as payment requests .

4. We do not want to store credit card info within salesforce , it should be PCI DSS compliant .







Authorize.net Account :

Create a authorize.net developer account and create a app to get API credentials .


Payment Page Screens :

Here we have payment screens for creit card as well as e-check .






Code Samples :

Here we have visualforce page as well as apex classes for same .

Visualforce Page :

<apex:page controller="AU_Payment_Class" showHeader="false" >
<script>
    function inputLimiter(e,allow) {
            var AllowableCharacters = '';

            if (allow == 'Letters'){AllowableCharacters=' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';}
            if (allow == 'Numbers'){AllowableCharacters='1234567890';}
            if (allow == 'NameCharacters'){AllowableCharacters=' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-.\'';}
            if (allow == 'NameCharactersAndNumbers'){AllowableCharacters='1234567890 ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-\'';}
            if (allow == 'Currency'){AllowableCharacters='1234567890.';}

            var k = document.all?parseInt(e.keyCode): parseInt(e.which);
            if (k!=13 && k!=8 && k!=0){
                if ((e.ctrlKey==false) && (e.altKey==false)) {
                return (AllowableCharacters.indexOf(String.fromCharCode(k))!=-1);
                } else {
                return true;
                }
            } else {
                return true;
            }
        } 
        
    function GetURLParameter(sParam)
    {
        var sPageURL = window.location.search.substring(1);
        var sURLVariables = sPageURL.split('&');
        for (var i = 0; i < sURLVariables.length; i++) 
        {
            var sParameterName = sURLVariables[i].split('=');
            if (sParameterName[0] == sParam) 
            {
                return sParameterName[1];
            }
        }
    }​
    

    function getPrice()
    {
        var price = GetURLParameter('p');
        document.getElementById("price").innerHTML = price ;
    )            
    window.onload = getPrice;        
</script>
<style>
    .form{
        height: 90%;
        width: 55%;
        align-items: center;
        margin-left:50px;
        margin-right:50px;
        margin-bottom:50px;
        margin-top:10px;
        position: absolute;
        border: none;
        font-size:14px
    }
    .topDiv{
         margin-left:10%;
        margin-right:10%;
        margin-bottom:10%;
        margin-top:3%;
        width : 80%
    }
 .logo{
     align-items: center;
    margin-left: 50%;
 }
 .p, .table, .tr, .td{
     font-size:14px
 }
 #tabTwo{
     font-size : 14px !important
 }
.activeTab {background-color: #236FBD; color:white; background-image:none;font-size:14px}
.inactiveTab { background-color: lightgrey; color:black; background-image:none;font-size:14px}
</style>
<apex:form styleclass="form" >
<apex:pageblock >
    <div class="topDiv">
    <div class="logo" width="100%" >Logo</div>
    <div><p id="price"></p></div>
    <p style="align-items: center;margin-left: 50%;">TestCompany.Com</p>
    <br/>
        Thank you for signing the Proposal letter.  To proceed with the next steps in the process please provide 
payment for the $250 due diligence fee either using Credit Card or Check via the form below:
    <br/><br/> 
    <apex:tabPanel switchType="client" selectedTab="creditCard" id="theTabPanel" tabClass="activeTab" inactiveTabClass="inactiveTab">
        <apex:tab label="CreditCard" style="font-size:14px;" name="creditCard" id="tabOne">
           <p>The charge will appear on your credit card as Test Company Business Capital,LLC</p>
           <br/>
               
                    <table>
                    <tr><td width="25%">*Credit Card: </td>
                    <td>
                        <apex:selectList value="{!creditCard}" multiselect="false" size="1">
                            <apex:selectOptions value="{!CreditCards}"/>
                        </apex:selectList>
                    </td>
                    </tr>
                    
                    <tr><td>*Card Number: </td>
                    <td colspan="2">
                      <apex:inputText value="{!cardNumber}" style="width:100px;" onkeypress="return inputLimiter(event,'Numbers');"/>
                    </td>
                    </tr>
                    
                    <tr><td>*Name on Card: </td>
                    <td colspan="4" >
                      <apex:inputText value="{!cardName}" style="width:180px;" onkeypress="return inputLimiter(event,'NameCharacters');"/>
                    </td>
                    </tr>
                    
                     <tr><td>*Expires: </td>
                    <td >
                   <apex:selectList value="{!cardExpYear}" multiselect="false" size="1" >
                            <apex:selectOptions value="{!Year}"/>
                        </apex:selectList>
                      <apex:selectList value="{!cardExpMonth}" multiselect="false" size="1">
                            <apex:selectOptions value="{!Months}"/>
                        </apex:selectList>
                    </td>
                    </tr>
                    
                    <tr><td>*Security Code: </td>
                    <td >
                        <apex:inputText value="{!securityCode}" style="width:70px;" onkeypress="return inputLimiter(event,'Numbers');"/>
                    </td>
                    </tr>
                    
                    <tr><td>*Address (line 1): </td>
                    <td >
                        <apex:inputText value="{!Add1}" style="width:200px;"/>
                    </td>
                    </tr>
                    
                    <tr><td>Address (line 2): </td>
                    <td >
                        <apex:inputText value="{!Add2}" style="width:200px;"/>
                    </td>
                    </tr>
                    
                    <tr><td>*City: </td>
                    <td >
                        <apex:inputText value="{!city}" style="width:80px;"/>
                    </td>
                    </tr>
                    
                    <tr><td>*state: </td>
                    <td >
                        <apex:inputText value="{!state}" style="width:80px;"/>
                    </td>
                    </tr>
                    
                    <tr><td>*Zip Code: </td>
                    <td >
                        <apex:inputText value="{!zip}" style="width:60px;" onkeypress="return inputLimiter(event,'Numbers');"/>
                    </td>
                    </tr>
                        <tr></tr>
                    <tr></tr>
                    <tr><td></td>
                    <td> 
                    <span><apex:inputCheckbox value="{!cardTermCheck}"/></span> *I understand that Test Company Business Capital,LLC does not process refunds 
                    </td></tr>
                    </table>
                   <apex:commandbutton action="{!submitPayProfile}" value="Submit Payment" immediate="true" style="margin-left: 34%;margin-top: 3%"/>
               
        </apex:tab>
        <apex:tab label="Check" style="font-size:14px !important;" name="check" id="tabTwo">
          
           <p>Enter the Following: </p>
            <table>
            <tr><td>*Bank Routing: </td>
                    <td >
                        <apex:inputText value="{!bankRouting}" />
                    </td>
                    </tr>
                    
                    <tr><td>*Bank Account: </td>
                    <td >
                        <apex:inputText value="{!accountNum}" />
                    </td>
                    </tr>
                    
                    <tr><td>*Confirm Bank Account: </td>
                    <td >
                        <apex:inputText value="{!confirmAccNum}" />
                    </td>
                    </tr>
                        
                    </table>
                    
                    <apex:commandbutton action="{!SaveCheck}" value="Submit Payment" immediate="true" style="margin-left: 31%;margin-top: 5%;" />
                   <p>
                       By clicking "Submit Payment" button above, I confirm that I am the owner of the account identified by the numbers entered above and authorize Test Company Business Capital,LLC to initiate an ACH(eletronic debit) to my account in the amount of $250.
                   </p>
            
        </apex:tab>
    </apex:tabPanel></div></apex:pageblock></apex:form>
</apex:page>

Apex Class :

public class AU_Payment_Class{
    
    public Id payId {get;set;}
    public String firstName {get;set;}
    public String lastName {get;set;}
    public String Add1 {get;set;}
    public String Add2 {get;set;}
    public String city {get;set;}
    public String state {get;set;}
    public String zip {get;set;}
    public String email {get;set;}
    public String country {get;set;}
    public String cardName {get;set;}
    public String cardNumber {get;set;}
    public String cardExpMonth {get;set;}
    public String cardExpYear {get;set;}
    public String cardCVV {get;set;}
    public boolean cardTermCheck {get;set;}  
    public boolean tankFlag {get;set;}
    public boolean payFlag {get;set;}
    public String ResString {get;set;}
    public Decimal Amount {get;set;}
    private String transactionID;
    public Payment_Request__c payReqRec;
    public Contact conRec {get;set;}
    public Opportunity oppRec;
    
    public string securityCode{get;set;}
    public  string bankRouting {get;set;}
    public  string accountNum {get;set;}
    public string confirmAccNum {get;set;}
    public string creditCard {get;set;}
    
    public static string bankRouting1 {get;set;}
    public  static string accountNum1 {get;set;}
     
    public AU_Payment_Class(){
        payId = apexpages.currentpage().getparameters().get('id');
        payReqRec = new Payment_Request__c();
        Contact conRec = new Contact();
        tankFlag = true;
        payFlag = true;
        cardNumber = '';
        cardExpMonth = '';
        cardExpYear = '';
        cardCVV = '';
        
        System.debug('payId=>'+payId );
        if(payId != null){
            payReqRec = [SELECT Id, Billing_Contact__c, Opportunity__c, Status__c FROM Payment_Request__c WHERE Id =: payId];
            conRec = [SELECT Id, Customer_Payment_Token__c, Customer_Profile_Token__c, FirstName, LastName, Email, MailingCity, MailingState, MailingPostalCode, MailingCountry, MailingStreet FROM Contact WHERE Id =: payReqRec.Billing_Contact__c];
            oppRec = [SELECT Id, Name, Amount FROM Opportunity WHERE Id =: payReqRec.Opportunity__c];
            System.debug('Contact=>'+conRec);
            firstName = conRec.FirstName;
            lastName = conRec.LastName;
            Add1 = conRec.MailingStreet;
            city = conRec.MailingCity;
            state = conRec.MailingState;
            zip = conRec.MailingPostalCode;
            email = conRec.Email;
            country = conRec.MailingCountry;
            //Amount = oppRec.Amount;
            Amount = 10;
            
            
        }
    }
    
    public PageReference submitPayProfile() {
        System.debug('submitPayProfile==>'+cardNumber+cardExpYear+cardExpMonth);
        String custPayProfileId;
        String custProfileId;
        AuthorizeNet__c ANetCS = AuthorizeNet__c.getInstance('Cred');
                
        //Create Customer Profile
        JSONGenerator gen = JSON.createGenerator(true);
        
        // Write data to the JSON string.
        gen.writeStartObject();
            gen.writeFieldName('createCustomerProfileRequest');
            gen.writeStartObject();
                gen.writeFieldName('merchantAuthentication');
                gen.writeStartObject();
                    gen.writeStringField('name', ANetCS.Api_Login_ID__c);
                    gen.writeStringField('transactionKey', ANetCS.Transaction_Key__c);
                gen.writeEndObject();
                    gen.writeFieldName('profile');
                    gen.writeStartObject();
                        gen.writeStringField('email', email);
                            gen.writeFieldName('paymentProfiles');
                            gen.writeStartObject();
                                gen.writeStringField('customerType', 'individual');
                                    gen.writeFieldName('payment');
                                    gen.writeStartObject();
                                        gen.writeFieldName('creditCard');
                                        gen.writeStartObject();
                                            gen.writeStringField('cardNumber', cardNumber);
                                            gen.writeStringField('expirationDate', cardExpYear+'-'+cardExpMonth);
                                        gen.writeEndObject();
                                    gen.writeEndObject();
                            gen.writeEndObject();
                    gen.writeEndObject();
            gen.writeEndObject();
        gen.writeEndObject();
        // Get the JSON string.
        String CreateCustProString = gen.getAsString();      
        System.debug('CreateCustProString==>'+CreateCustProString);
        Http http1=new Http();
        HttpRequest req1=new HttpRequest();
        req1.setendpoint(ANetCS.Endpoint_URL__c);
        req1.Setheader('Content-Type','application/json');
        req1.setmethod('POST'); //you can also SET method `GET` with Get there is no need of req1.setbody()
        req1.setbody(CreateCustProString);
        
        HttpResponse res1;
        res1 = http1.send(req1);
        if(res1.getStatusCode()==200){
            
            String str=res1.getbody().escapeUnicode();
            string FinalJSON=str.replaceall('uFEFF','');
            FinalJSON=FinalJSON.replaceall('\\\\','');
            System.debug(FinalJSON);
            
            AU_PaymentCustProfileJSON custProfileObj=new AU_PaymentCustProfileJSON();
            custProfileObj=(AU_PaymentCustProfileJSON) System.JSON.deserialize(FinalJSON, AU_PaymentCustProfileJSON.class);
            
            AU_PaymentCustProfileJSON.cls_messages custProfileMsg=custProfileObj.messages;
            List custProfileSubMsg = custProfileMsg.message;
            
            if(custProfileSubMsg[0].text == 'Successful.'){
                custProfileId = custProfileObj.customerProfileId;
            }else if(custProfileSubMsg[0].text.containsIgnoreCase('duplicate')){
                custProfileId = custProfileSubMsg[0].text.replaceAll('[^-?0-9]+', ''); 
            }else{
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error,custProfileSubMsg[0].text));
                return null;
            }
            System.debug('custProfileId=>'+custProfileId );
            
            //Create Customer Profile
            JSONGenerator genPayPro = JSON.createGenerator(true);
            
            // Write data to the JSON string Customer Payment Profile .
            genPayPro.writeStartObject();
                genPayPro.writeFieldName('createCustomerPaymentProfileRequest');
                genPayPro.writeStartObject();
                    genPayPro.writeFieldName('merchantAuthentication');
                    genPayPro.writeStartObject();
                        genPayPro.writeStringField('name', ANetCS.Api_Login_ID__c);
                        genPayPro.writeStringField('transactionKey', ANetCS.Transaction_Key__c);
                    genPayPro.writeEndObject();
                    genPayPro.writeStringField('customerProfileId', custProfileId );
                    genPayPro.writeFieldName('paymentProfile');
                    genPayPro.writeStartObject();
                        genPayPro.writeFieldName('billTo');
                        genPayPro.writeStartObject();
                            genPayPro.writeStringField('firstName', firstName );
                            genPayPro.writeStringField('lastName', lastName );
                            genPayPro.writeStringField('address', Add1 + Add2 );
                            genPayPro.writeStringField('city', city );
                            genPayPro.writeStringField('state', state );
                            genPayPro.writeStringField('zip', zip );
                            genPayPro.writeStringField('country', country );
                            genPayPro.writeStringField('phoneNumber', '');
                        genPayPro.writeEndObject();
                        genPayPro.writeFieldName('payment');
                        genPayPro.writeStartObject();
                            genPayPro.writeFieldName('creditCard');
                            genPayPro.writeStartObject();
                                genPayPro.writeStringField('cardNumber', cardNumber);
                                genPayPro.writeStringField('expirationDate', cardExpYear+'-'+cardExpMonth);
                            genPayPro.writeEndObject();
                        genPayPro.writeEndObject();
                        genPayPro.writeStringField('defaultPaymentProfile', 'true');
                    genPayPro.writeEndObject();
                genPayPro.writeEndObject();
            genPayPro.writeEndObject();
            
            // Get the JSON string.
            String CreateCustPayProString = genPayPro.getAsString();      
            System.debug('CreateCustProString==>'+CreateCustPayProString );
            Http http2=new Http();
            HttpRequest req2=new HttpRequest();
            req2.setendpoint(ANetCS.Endpoint_URL__c);
            req2.Setheader('Content-Type','application/json');
            req2.setmethod('POST'); //you can also SET method `GET` with Get there is no need of req1.setbody()
            req2.setbody(CreateCustPayProString);
            
            HttpResponse res2;
            res2 = http2.send(req2);
            if(res1.getStatusCode()==200){
            
                String str2=res2.getbody().escapeUnicode();
                string FinalJSON2=str2.replaceall('uFEFF','');
                FinalJSON2=FinalJSON2.replaceall('\\\\','');
                System.debug('FinalJSON2=>'+FinalJSON2);
                
                AU_CustPayProfilefromJSON custProfileObj2=new AU_CustPayProfilefromJSON();
                custProfileObj2=(AU_CustPayProfilefromJSON) System.JSON.deserialize(FinalJSON2, AU_CustPayProfilefromJSON.class);
                
                AU_CustPayProfilefromJSON.cls_messages custProfileMsg2=custProfileObj2.messages;
                List custProfileSubMsg2 = custProfileMsg2.message;
                
                custPayProfileId = custProfileObj2.customerPaymentProfileId;
                System.debug('custPayProfileId=>'+custPayProfileId);
                
                //Create Customer Profile
                JSONGenerator genPayPro2 = JSON.createGenerator(true);

                genPayPro2.writeStartObject();
                    genPayPro2.writeFieldName('createTransactionRequest');
                    genPayPro2.writeStartObject();
                        genPayPro2.writeFieldName('merchantAuthentication');
                        genPayPro2.writeStartObject();
                            genPayPro2.writeStringField('name', ANetCS.Api_Login_ID__c);
                            genPayPro2.writeStringField('transactionKey', ANetCS.Transaction_Key__c);
                        genPayPro2.writeEndObject();
                        genPayPro2.writeFieldName('transactionRequest');
                        genPayPro2.writeStartObject();
                            genPayPro2.writeStringField('transactionType', 'authCaptureTransaction');
                            genPayPro2.writeStringField('amount', String.ValueOf(Amount));
                            genPayPro2.writeFieldName('profile');
                            genPayPro2.writeStartObject();
                                genPayPro2.writeStringField('customerProfileId', custProfileId);
                                genPayPro2.writeFieldName('paymentProfile');
                                genPayPro2.writeStartObject();
                                    genPayPro2.writeStringField('paymentProfileId', (custPayProfileId !=null ? custPayProfileId:''));
                                genPayPro2.writeEndObject();
                            genPayPro2.writeEndObject();
                        genPayPro2.writeEndObject();
                    genPayPro2.writeEndObject();
                genPayPro2.writeEndObject();
                
                // Get the JSON string.
                String JSONRequestBODY = genPayPro2.getAsString();      
                System.debug('JSONRequestBODY==>'+JSONRequestBODY );
                
                Http http3=new Http();
                HttpRequest req3=new HttpRequest();
                req3.setendpoint(ANetCS.Endpoint_URL__c);
                req3.Setheader('Content-Type','application/json');
                req3.setmethod('POST'); //you can also SET method `GET` with Get there is no need of req1.setbody()
                req3.setbody(JSONRequestBODY);
                
                HttpResponse res3;
                res3 = http3.send(req3);
                if(res1.getStatusCode()==200){
            
                    String str3=res3.getbody().escapeUnicode();
                    string FinalJSONTran=str3.replaceall('uFEFF','');
                    FinalJSONTran=FinalJSONTran.replaceall('\\\\','');
                    System.debug(FinalJSONTran);
                    
                    Transaction__c tanRec = new Transaction__c();
                                        
                    AU_Transaction_fromJSON transactionObj=new AU_Transaction_fromJSON();
                    transactionObj=(AU_Transaction_fromJSON) System.JSON.deserialize(FinalJSONTran, AU_Transaction_fromJSON.class);
                    
                    AU_Transaction_fromJSON.cls_messages tranMsg=transactionObj.messages;
                    List tranSubMsg = tranMsg.message;
                    
                    if(tranSubMsg[0].text == 'Successful.'){
                         AU_Transaction_fromJSON.cls_transactionResponse tranData=transactionObj.transactionResponse;
                         
                         tanRec.Amount__c = Amount;
                         tanRec.Authorization__c = tranData.authCode;
                         tanRec.Card_Last_4__c = cardNumber.right(4);
                         tanRec.Credit_Card_Name__c = cardName;
                         tanRec.Credit_Card_Type__c = tranData.accountType;
                         tanRec.Opportunity__c = payReqRec.Opportunity__c;
                         //tanRec.Payment_Method__c = 
                         tanRec.Payment_Request__c = payReqRec.Id;
                         //tanRec.Reason_Code__c = 
                         //tanRec.Reason_Text__c =
                         //tanRec.Recurring__c =
                         //tanRec.Response__c = 
                         tanRec.Response_Code__c = tranData.responseCode;
                         tanRec.Type__c = 'Charge';
                         
                         List tranSubData = tranData.messages;
                         tanRec.Response_Message__c = String.ValueOf(tranSubData[0].message);
                         tanRec.Response_Status__c = String.ValueOf(tranSubData[0].resultCode);
                         //tanRec.Security_Response__c = 
                         tanRec.Tokenization__c = tranData.transId;
                         //tanRec.Type__c = 
                        
                        Insert tanRec;
                        
                        system.debug('custPayProfileId=>'+custPayProfileId);
                        system.debug('custProfileId=>'+custProfileId);
                        system.debug('payReqRec=>'+payReqRec);
                        system.debug('conRec=>'+conRec);
                        Contact conRec2 = new Contact();
                        conRec2 = [SELECT Id, Customer_Payment_Token__c, Customer_Profile_Token__c FROM Contact WHERE Id =: payReqRec.Billing_Contact__c LIMIT 1];
                        conRec2.Customer_Payment_Token__c = custPayProfileId;
                        conRec2.Customer_Profile_Token__c = custProfileId;
                        Update conRec2;
                        
                        tankFlag = false;
                        payFlag = true;
                        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Warning,'This transaction has been approved'));
                        return null;
                    }else{
                        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error,tranSubMsg[0].text));
                        return null;
                    }
                    System.debug('Tansaction=>'+custProfileId );
                }   
                
            }
        }
        tankFlag = false;
        payFlag = true;
        return null;
    }
    
    public static pageReference SaveCheck(){
        String custPayProfileId;
        String custProfileId;
        AuthorizeNet__c ANetCS = AuthorizeNet__c.getInstance('Cred');
                
        //Create Customer Profile
        JSONGenerator gen = JSON.createGenerator(true);
        
        // Write data to the JSON string.
        gen.writeStartObject();
            gen.writeFieldName('createCustomerProfileRequest');
            gen.writeStartObject();
                gen.writeFieldName('merchantAuthentication');
                gen.writeStartObject();
                    gen.writeStringField('name', ANetCS.Api_Login_ID__c);
                    gen.writeStringField('transactionKey', ANetCS.Transaction_Key__c);
                gen.writeEndObject();
                    gen.writeFieldName('profile');
                    gen.writeStartObject();
                        //gen.writeStringField('email', email);
                        gen.writeStringField('email', 'test@test.com');
                            gen.writeFieldName('paymentProfiles');
                            gen.writeStartObject();
                                gen.writeStringField('customerType', 'individual');
                                    gen.writeFieldName('payment');
                                    gen.writeStartObject();
                                        gen.writeFieldName('bankAccount');
                                        gen.writeStartObject();
                                           
                                            gen.writeStringField('routingNumber', bankRouting1);
                                             gen.writeStringField('accountNumber', accountNum1);
                                             gen.writeStringField('nameOnAccount', 'test Name');
                                            /*gen.writeStringField('bankName', 'test bank');*/
                                            //gen.writeStringField('accountType', 'checking');
                                           gen.writeStringField('echeckType', 'WEB');
                                            //gen.writeStringField('checkNumber', '123456874');
                                        gen.writeEndObject();
                                    gen.writeEndObject();
                            gen.writeEndObject();
                    gen.writeEndObject();
            gen.writeEndObject();
        gen.writeEndObject();
        // Get the JSON string.
        String CreateCustProString = gen.getAsString();      
        System.debug('CreateCustProString==>'+CreateCustProString);
        Http http1=new Http();
        HttpRequest req1=new HttpRequest();
        req1.setendpoint(ANetCS.Endpoint_URL__c);
        req1.Setheader('Content-Type','application/json');
        req1.setmethod('POST'); //you can also SET method `GET` with Get there is no need of req1.setbody()
        req1.setbody(CreateCustProString);
        
        HttpResponse res1;
        
        system.debug('req1==>'+req1);
        res1 = http1.send(req1);
        
        system.debug('res1==>'+req1);
        if(res1.getStatusCode()==200){
            
            String str=res1.getbody().escapeUnicode();
            string FinalJSON=str.replaceall('uFEFF','');
            FinalJSON=FinalJSON.replaceall('\\\\','');
            System.debug('FinalJSON==>'+FinalJSON);
            
            AU_PaymentCustProfileJSON custProfileObj=new AU_PaymentCustProfileJSON();
            custProfileObj=(AU_PaymentCustProfileJSON) System.JSON.deserialize(FinalJSON, AU_PaymentCustProfileJSON.class);
            
            AU_PaymentCustProfileJSON.cls_messages custProfileMsg=custProfileObj.messages;
            List custProfileSubMsg = custProfileMsg.message;
            
            if(custProfileSubMsg[0].text == 'Successful.'){
                custProfileId = custProfileObj.customerProfileId;
            }else if(custProfileSubMsg[0].text.containsIgnoreCase('duplicate')){
                custProfileId = custProfileSubMsg[0].text.replaceAll('[^-?0-9]+', ''); 
            }else{
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error,custProfileSubMsg[0].text));
                return null;
            }
            System.debug('custProfileId=>'+custProfileId );
            
            //Create Customer Profile
            JSONGenerator genPayPro = JSON.createGenerator(true);
            
            // Write data to the JSON string Customer Payment Profile .
            genPayPro.writeStartObject();
                genPayPro.writeFieldName('createCustomerPaymentProfileRequest');
                genPayPro.writeStartObject();
                    genPayPro.writeFieldName('merchantAuthentication');
                    genPayPro.writeStartObject();
                        genPayPro.writeStringField('name', ANetCS.Api_Login_ID__c);
                        genPayPro.writeStringField('transactionKey', ANetCS.Transaction_Key__c);
                        
                    genPayPro.writeEndObject();
                    genPayPro.writeStringField('customerProfileId', custProfileId);
                    genPayPro.writeFieldName('paymentProfile');
                    genPayPro.writeStartObject();
                        genPayPro.writeFieldName('payment');
                        genPayPro.writeStartObject();
                            genPayPro.writeFieldName('bankAccount');
                            genPayPro.writeStartObject();
                                genPayPro.writeStringField('routingNumber', bankRouting1);
                                genPayPro.writeStringField('accountNumber', accountNum1);
                                genPayPro.writeStringField('nameOnAccount', 'test Name');
                                /*gen.writeStringField('bankName', 'test bank');*/
                                //gen.writeStringField('accountType', 'checking');
                                 genPayPro.writeStringField('echeckType', 'WEB');
                                genPayPro.writeStringField('checkNumber', '123456874');
                            genPayPro.writeEndObject();
                        genPayPro.writeEndObject();
                        genPayPro.writeStringField('defaultPaymentProfile', 'true');
                    genPayPro.writeEndObject();
                genPayPro.writeEndObject();
            genPayPro.writeEndObject();
            
            
            system.debug('genPayPro==>'+genPayPro);
            // Get the JSON string.
            String CreateCustPayProString = genPayPro.getAsString();      
            System.debug('CreateCustProString==>'+CreateCustPayProString );
            Http http2=new Http();
            HttpRequest req2=new HttpRequest();
            req2.setendpoint(ANetCS.Endpoint_URL__c);
            req2.Setheader('Content-Type','application/json');
            req2.setmethod('POST'); //you can also SET method `GET` with Get there is no need of req1.setbody()
            req2.setbody(CreateCustPayProString);
            
            HttpResponse res2;
            res2 = http2.send(req2);
            if(res1.getStatusCode()==200){
            
                String str2=res2.getbody().escapeUnicode();
                string FinalJSON2=str2.replaceall('uFEFF','');
                FinalJSON2=FinalJSON2.replaceall('\\\\','');
                System.debug('FinalJSON2=>'+FinalJSON2);
                
                AU_CustPayProfilefromJSON custProfileObj2=new AU_CustPayProfilefromJSON();
                custProfileObj2=(AU_CustPayProfilefromJSON) System.JSON.deserialize(FinalJSON2, AU_CustPayProfilefromJSON.class);
                
                AU_CustPayProfilefromJSON.cls_messages custProfileMsg2=custProfileObj2.messages;
                List custProfileSubMsg2 = custProfileMsg2.message;
                
                custPayProfileId = custProfileObj2.customerPaymentProfileId;
                System.debug('custPayProfileId=>'+custPayProfileId);
                
                //Create Customer Profile
                JSONGenerator genPayPro2 = JSON.createGenerator(true);

                genPayPro2.writeStartObject();
                    genPayPro2.writeFieldName('createTransactionRequest');
                    genPayPro2.writeStartObject();
                        genPayPro2.writeFieldName('merchantAuthentication');
                        genPayPro2.writeStartObject();
                            genPayPro2.writeStringField('name', ANetCS.Api_Login_ID__c);
                            genPayPro2.writeStringField('transactionKey', ANetCS.Transaction_Key__c);
                        genPayPro2.writeEndObject();
                        genPayPro2.writeFieldName('transactionRequest');
                        genPayPro2.writeStartObject();
                            genPayPro2.writeStringField('transactionType', 'authCaptureTransaction');
                            //genPayPro2.writeStringField('amount', String.ValueOf(Amount));
                            genPayPro2.writeStringField('amount', String.ValueOf(450));
                            genPayPro2.writeFieldName('profile');
                            genPayPro2.writeStartObject();
                                genPayPro2.writeStringField('customerProfileId', custProfileId);
                                
                                 
                                genPayPro2.writeFieldName('paymentProfile');
                                genPayPro2.writeStartObject();
                                    genPayPro2.writeStringField('paymentProfileId', custPayProfileId);
                                    //genPayPro2.writeStringField('paymentProfileId', '12354');
                                    //genPayPro2.writeStringField('defaultShippingAddress', 'false');
                                genPayPro2.writeEndObject();
                            genPayPro2.writeEndObject();
                        genPayPro2.writeEndObject();
                    genPayPro2.writeEndObject();
                genPayPro2.writeEndObject();
                
                system.debug('genPayPro2 ==>'+genPayPro2);
                // Get the JSON string.
                String JSONRequestBODY = genPayPro2.getAsString();      
                System.debug('JSONRequestBODY==>'+JSONRequestBODY );
                
                Http http3=new Http();
                HttpRequest req3=new HttpRequest();
                req3.setendpoint(ANetCS.Endpoint_URL__c);
                req3.Setheader('Content-Type','application/json');
                req3.setmethod('POST'); //you can also SET method `GET` with Get there is no need of req1.setbody()
                req3.setbody(JSONRequestBODY);
                
                HttpResponse res3;
                res3 = http3.send(req3);
                
                system.debug('res3 ==>'+res3 );
                
                if(res1.getStatusCode()==200){
            
                    String str3=res3.getbody().escapeUnicode();
                    string FinalJSONTran=str3.replaceall('uFEFF','');
                    FinalJSONTran=FinalJSONTran.replaceall('\\\\','');
                    System.debug(FinalJSONTran);
                    
                    Transaction__c tanRec = new Transaction__c();
                                        
                    AU_Transaction_fromJSON transactionObj=new AU_Transaction_fromJSON();
                    transactionObj=(AU_Transaction_fromJSON) System.JSON.deserialize(FinalJSONTran, AU_Transaction_fromJSON.class);
                    
                    AU_Transaction_fromJSON.cls_messages tranMsg=transactionObj.messages;
                    List tranSubMsg = tranMsg.message;
                    
                    if(tranSubMsg[0].text == 'Successful.'){
                     /*    AU_Transaction_fromJSON.cls_transactionResponse tranData=transactionObj.transactionResponse;
                         
                         tanRec.Amount__c = Amount;
                         tanRec.Authorization__c = tranData.authCode;
                         tanRec.Card_Last_4__c = cardNumber.right(4);
                         tanRec.Credit_Card_Name__c = cardName;
                         tanRec.Credit_Card_Type__c = tranData.accountType;
                         tanRec.Opportunity__c = payReqRec.Opportunity__c;
                         //tanRec.Payment_Method__c = 
                         tanRec.Payment_Request__c = payReqRec.Id;
                         //tanRec.Reason_Code__c = 
                         //tanRec.Reason_Text__c =
                         //tanRec.Recurring__c =
                         //tanRec.Response__c = 
                         tanRec.Response_Code__c = tranData.responseCode;
                         tanRec.Type__c = 'Charge';
                         
                         List tranSubData = tranData.messages;
                         tanRec.Response_Message__c = String.ValueOf(tranSubData[0].message);
                         tanRec.Response_Status__c = String.ValueOf(tranSubData[0].resultCode);
                         //tanRec.Security_Response__c = 
                         tanRec.Tokenization__c = tranData.transId;
                         //tanRec.Type__c = 
                        
                        Insert tanRec;
                        
                        system.debug('custPayProfileId=>'+custPayProfileId);
                        system.debug('custProfileId=>'+custProfileId);
                        system.debug('payReqRec=>'+payReqRec);
                        system.debug('conRec=>'+conRec);
                        Contact conRec2 = new Contact();
                        conRec2 = [SELECT Id, Customer_Payment_Token__c, Customer_Profile_Token__c FROM Contact WHERE Id =: payReqRec.Billing_Contact__c LIMIT 1];
                        conRec2.Customer_Payment_Token__c = custPayProfileId;
                        conRec2.Customer_Profile_Token__c = custProfileId;
                        Update conRec2;
                        
                        tankFlag = false;
                        payFlag = true;
                        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Warning,'This transaction has been approved'));*/
                        return null;
                    }else{
                        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error,tranSubMsg[0].text));
                        return null;
                    }
                    System.debug('Tansaction=>'+custProfileId );
                }   
                
            }
        }
       /* tankFlag = false;
        payFlag = true;*/
        return null;
        return null;
    }
    
    public List getCreditCards() {
        List options = new List();
        options.add(new SelectOption('None','None'));
        options.add(new SelectOption('Type1','Type1'));
        options.add(new SelectOption('Type2','Type3'));
        options.add(new SelectOption('Type3','Type3'));
        return options;
    }
    
    public List getYear() {
        integer year = Datetime.now().year();
        List options = new List();
        options.add(new SelectOption('Year','Year'));
        for(integer i =0;i<25 electoption="" i="" list="" new="" options.add="" options="" public="" return="" selectoption="" string.valueof="" year=""> getMonths() {
        integer year = Datetime.now().year();
        List options = new List();
        options.add(new SelectOption('MTH','MTH'));
        options.add(new SelectOption('1','Jan'));
        options.add(new SelectOption('2','Feb'));
        options.add(new SelectOption('3','Mar'));
        options.add(new SelectOption('4','Apr'));
        options.add(new SelectOption('5','May'));
        options.add(new SelectOption('6','Jun'));
        options.add(new SelectOption('7','Jul'));
        options.add(new SelectOption('8','Aug'));
        options.add(new SelectOption('9','Sep'));
        options.add(new SelectOption('10','Oct'));
        options.add(new SelectOption('11','Nov'));
        options.add(new SelectOption('12','Dec'));
        
        return options;
    }
    
}


Comments

  1. I think that I'm into your pieces of writing. They really help me out. I wait for your posts every week. I learn many new interesting things from the articles. The information is essential for me. I want to thank you for sharing. https://bit.ly/2y8RMwK, https://bit.ly/2QslLr4, Autoketing

    ReplyDelete
  2. It's so nice article thank you for sharing a valuable content. google cloud online course

    ReplyDelete
  3. The website is looking bit flashy and it catches the visitors eyes. Design is pretty simple and a good user friendly interface. friv jogos online
    jogos online 2019
    friv jogos 4 school online

    ReplyDelete
  4. awesome blog it's very nice and useful i got many more information it's really nice i like your blog styleweb design company in velacheryweb design company in chennai

    ReplyDelete

Post a Comment

Popular posts from this blog

A Quick Salesforce OAuth 2.0 Usage Demonstration

Charts in Lightning component