function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
kezia dolakezia dola 

Status=Unauthorized, StatusCode=401, "code":401,"message":"An error occurred. Header not set."

Hi,

I am getting 401 unauthorized error while running my API. I have checked the endpoint url and all credentials from server side, all are correct. Still getting this error. 
Error: [Status=Unauthorized, StatusCode=401]
"code":401,"message":"An error occurred. Header not set."
-------
This is my code:

public class QcAPI {
    @future(callout=true)
    public static void callServer(String id){
        Opportunity opp =[Select Id,Account.FirstName,Account.ShippingAddress,Account.BillingAddress, Account.LastName,Email__c,DUP_Mobile__c,account.BillingStreet,account.BillingCity,account.BillingState,account.BillingCountry,account.BillingPostalCode,
                          account.ShippingStreet,account.ShippingCity,account.ShippingState,account.ShippingCountry,account.ShippingPostalCode from Opportunity where id=: id limit 1];
        
        OpportunityDataWrap oppdata = new OpportunityDataWrap();
        String rno = opp.Account.LastName+'-'+opp.Id;
        oppdata.refno = rno;
        oppdata.syncOnly = true;
        oppdata.deliveryMode = 'API';
        
        if(opp.Account.ShippingAddress !=null){
            ShippingAddressWrap cc = new ShippingAddressWrap();
            cc.firstname = opp.Account.LastName;
            cc.lastname = '';
            cc.email = opp.Email__c;
            cc.telephone = '+91'+opp.DUP_Mobile__c;
            cc.country = 'IN';
            cc.line1 = opp.Account.ShippingStreet;
            cc.line2 = '-';
            cc.city = opp.Account.ShippingCity;
            cc.postcode = opp.Account.ShippingPostalCode;
            cc.region = opp.Account.ShippingState;
            cc.billToThis = true;
            oppdata.address = cc;
        }
        
        if(opp.Account.BillingAddress !=null){
            BillingAddressWrap cb = new BillingAddressWrap();
            cb.firstname = opp.Account.lastname;
            cb.lastname = '';
            cb.email = opp.Email__c;
            cb.telephone = '+91'+opp.DUP_Mobile__c;
            cb.country = 'IN';
            cb.line1 = opp.Account.ShippingStreet;
            cb.line2 = '-';
            cb.city = opp.Account.ShippingCity;
            cb.postcode = opp.Account.ShippingPostalCode;
            cb.region = opp.Account.ShippingState; 
            oppdata.billing = cb;
        }
        List<paymentwrap> pw = new List<paymentwrap>();
        paymentwrap pwr = new paymentwrap();
        pwr.code = 'xyz';
        pwr.amount = 0;
        pw.add(pwr);
        oppdata.payments = pw;
        
        List<productsWrap> prodwrap = new List<productsWrap>();
        productsWrap pdwr = new productsWrap();
        pdwr.sku = 'xyzABCDE000';  
        pdwr.price = 0;
        pdwr.qty = 1;
        pdwr.currency_x =356;
        pdwr.giftMessage ='';
        pdwr.theme ='';
        prodwrap.add(pdwr);
        oppdata.products = prodwrap;
        system.debug('OppData:'+oppdata);
        String jsbody = JSON.serialize(oppdata);
        String jsonBody = jsbody.replace('currency_x', 'currency');
        system.debug('JSON BODY : '+jsonBody);
        map<string,Object> result = (map<string,Object>)JSON.deserializeUntyped(jsonBody);
        system.debug('result '+result);
        string endresult = JSON.serialize(result);
        system.debug('endresult '+endresult);

        String customLabelValue = Label.QCAPI+'/orders';
        //signature calling
        
        XYZ__c    Qc = XYZ__c.getvalues('XYZ details');
        string secretKeyValue = Qc.Consumer_secret__c;
        string reqMethod = 'POST';
        string url = EncodingUtil.URLEncode(Label.QCAPI+'/10000028/resend','UTF-8');
        system.JSONParser requestData = JSON.createParser(jsonBody);
        string endpoint = reqMethod + '&' + url;
        system.debug('end point url '+endpoint);
        string signature;
        Blob hmacData = Crypto.generateMac('HmacSHA512', Blob.valueOf(endpoint), Blob.valueOf(secretKeyValue));
        signature = encodingUtil.convertToHex(hmacData);
        system.debug('signature '+signature);
        
        string BearerToken = QCoauth.BearerToken();
        HttpRequest request = new HttpRequest();
        request.setEndpoint(customLabelValue);
        request.setMethod('POST');
        request.setHeader('Content-Type', 'application/json');
        request.setHeader('Authorization',BearerToken);
        request.setHeader('Accept','*/*');
        request.setBody(jsonBody);
        Http http = new Http();
        HttpResponse response = http.send(request);
        system.debug('get response :'+response.getBody());
        system.debug('get response :'+response);
        List<ResponseData> rd = (List<ResponseData>)JSON.deserialize(response.getBody(),List<ResponseData>.class);
        System.debug('Response Data :'+rd);
        
    }
    
    public class ShippingAddressWrap{
        public String firstname{get;set;}
        public String lastname{get;set;} 
        public String email{get;set;} 
        public String telephone{get;set;} 
        public String line1{get;set;} 
        public String line2{get;set;} 
        public String city{get;set;} 
        public String region{get;set;} 
        public String country{get;set;} 
        public String postcode{get;set;} 
        public boolean billToThis{get;set;} 
    }
    
    public class BillingAddressWrap{
        public String firstname{get;set;}
        public String lastname{get;set;} 
        public String email{get;set;} 
        public String telephone{get;set;} 
        public String line1{get;set;} 
        public String line2{get;set;} 
        public String city{get;set;} 
        public String region{get;set;} 
        public String country{get;set;} 
        public String postcode{get;set;} 
    }
    public class paymentwrap{
        public string code{get;set;}
        public double amount{get;set;}
    }
    public class productsWrap{
        public string sku{get;set;}
        public double price{get;set;}
        public integer qty{get;set;}
        public integer currency_x{get;set;}
        public string giftMessage{get;set;}
        public string theme{get;set;}
    }
    public class OpportunityDataWrap{    
        Public ShippingAddressWrap address{get;set;}
        Public BillingAddressWrap billing{get;set;}
        Public List<paymentwrap> payments{get;set;}
        public string refno{get;set;}
        public List<productsWrap> products{get;set;}
        public boolean syncOnly{get;set;}
        public String deliveryMode{get;set;} 
    }
    public class ResponseData {
        public string status;
        public List<cardwrap> cards;
    }
    public class cardwrap{
        public string cardNumber;
        public string cardPin;
    }
}
-----------
This is my Oauth code:

public class qcOauth {
    public static string AuthCode(){
        string Authcode;
        qc__c    Qc = qc__c.getvalues('qc details');
        authWrapreq Aw = new authWrapreq();
        Aw.clientId = Qc.Consumer_Key__c;
        Aw.username = Qc.UserName__c;
        Aw.password = Qc.Password__c;
        
        string endpoint = Qc.url__c+'verify';
        HttpRequest request = new HttpRequest();
        request.setEndpoint(endpoint);
        request.setMethod('POST');
        request.setHeader('Content-Type', 'application/json');
        String jsonBody = JSON.serialize(Aw);
      //  system.debug('JSON BODY : '+jsonBody);
        request.setBody(jsonBody);
        Http http = new Http();
        HttpResponse response = http.send(request);
     //   system.debug('response body: '+response.getBody());
        if(response.getStatusCode() == 200){
            authRes res = (authRes)json.deserialize(response.getBody(), authRes.class);
            authcode = res.authorizationCode;
        }
     //   system.debug(authcode);
        return authcode;
    }
    
    public static string BearerToken(){
        string BearerToken;
        qc__c    Qc = qc__c.getvalues('qc details');
        BearerWrapReq Bw = new BearerWrapReq();
        Bw.clientId = Qc.Consumer_Key__c;
        Bw.clientSecret = Qc.Consumer_secret__c;
        Bw.authorizationCode = Authcode();
        
        string endpoint = Qc.url__c+'token';
        HttpRequest request = new HttpRequest();
        request.setEndpoint(endpoint);
        request.setMethod('POST');
        request.setHeader('Content-Type', 'application/json');
        String jsonBody = JSON.serialize(Bw);
    //    system.debug('JSON BODY : '+jsonBody);
        request.setBody(jsonBody);
        Http http = new Http();
        HttpResponse response = http.send(request);
     //   system.debug('response body: '+response.getBody());
        if(response.getStatusCode() == 200){
            BearRes res = (BearRes)json.deserialize(response.getBody(), BearRes.class);
            BearerToken = res.token;
        }
     //   system.debug(BearerToken);
        return BearerToken;
    }

    public class authWrapreq{
        public string clientId;
        public string username;
        public string password;
    }
    public class authRes{
        public string authorizationCode;
    }
    public class BearerWrapReq{
        public string clientId;
        public string clientSecret;
        public string authorizationCode;
    }
    public class BearRes{
        public string token;
    }
}


Any idea to resolve this issue?

Thanks,
Kezia
ShivankurShivankur (Salesforce Developers) 
Hi Kezia,

It looks like you are not getting OAuth token to process this request.

Error 401 indicates: The session ID or OAuth token used has expired or is invalid. The response body contains the message and errorCode.

As per this, BearerToken is not being set while making this request, so you can try debugging first with BearerToken and then with the whole request.

Reference for error code:
https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/errorcodes.htm

Hope above information helps. Please mark as Best Answer so that it can help others in future.

Thanks.
 
kezia dolakezia dola
Hi Shivankur,

I tried debugging bearer token and it is being generated, still getting error. Now I want regenerate a new bearer token for every 6 days i.e; the token will expire after 6 days. Any idea how to regenerate a new bearer token for every 6 days in my code? 

Thanks,
Kezia