Help using oauth & jquery to submit new ticket

Comments

8 comments

  • Avatar
    Olaf Kwant

    Dude, you posted an access token to your zendesk. I can see your tickets and am pretty sure I can cause a lot more havoc. You should really not post credentials to the open internet.

    I would recommend revoking/renewing the OAuth tokens.

  • Avatar
    Eric Shen

    I've gone ahead and had this removed for you.  Be mindful of this!

  • Avatar
    Anara D.

    Hey Ben,

    Were you able to resolve your problem? I have the same issue, been trying to submit a ticket to zendesk from javascript, basically a POST request with access token to   https://mydomain.zendesk.com/api/v2/tickets.json. And I get the same error as you. Was able to get the list of tickets as you did. Stuck :s 

  • Avatar
    Ben Askren

    Yes, I was.  However, now that I have tried it for four months, there are other reasons for which I wouldn't recommend using Google Drive.

    (1) here is the code that worked:

    var ticket_id = -1;

    function post_to_url(path, params, method) {

    method = method || "post"; // Set method to post by default if not specified.

    // The rest of this code assumes you are not using a library.
    // It can be made less wordy if you use one.
    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    for(var key in params) {
    if(params.hasOwnProperty(key)) {
    var hiddenField = document.createElement("input");
    hiddenField.setAttribute("type", "hidden");
    hiddenField.setAttribute("name", key);
    hiddenField.setAttribute("value", params[key]);

    form.appendChild(hiddenField);
    }
    }

    document.body.appendChild(form);
    form.submit();
    }

    function getHashParameter(name) {
    return decodeURIComponent((new RegExp('[#|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.hash)||[,""])[1].replace(/+/g, '%20'))
    || null;
    }

    function getTreeURIParameters() {
    return "access_token="+getHashParameter("access_token")+"&scope=read%20write&token_type=bearer"
    }

    function create_ticket(type,subject,description, priority, status, tags) {
    var payload = {"ticket":{"type":type, "subject":subject, "description":description, "priority":priority, "status":status, "tags":tags } };

    $('#loading').show();

    $.ajax({
    url: "https://mydomain.zendesk.com/api/v2/tickets.json?"+getTreeURIParameters(),
    method: "POST",
    type: "POST",
    contentType: "application/json",
    processData: false,
    data: JSON.stringify(payload),
    dataType:"json",
    crossDomain:true
    }).done(function(data, textStatus, xhr) {
    $('#loading').hide();
    //var json = JSON.parse(data);
    ticket_id = data.ticket.id;
    $('#mySmallModalText').html('Ticket '+ticket_id+' has been created.');
    $('#mySmallModal').modal('show');
    //alert('ticket '+ticket_id+' has been created');
    //window.location.replace("https://mydomain.zendesk.com/agent/#/tickets/"+ticket_id);
    }).fail(function(xhr, textStatus, errorThrown) {
    $('#loading').hide();
    console.log(xhr);
    console.log(textStatus);
    console.log(errorThrown);
    alert("An error occured submitting a ticket, check the console.");
    }).always(function() {
    });
    }

     

    $(document).ready(function() {

    var error = getHashParameter("error");
    var token = getHashParameter("access_token");

    $("#error").append(error);
    $("#token").append(token);

    if (error) {
    //var error_msg = document.createElement("p");
    //error_msg.html(getHashParameter("error_description"));
    //document.body.appendChild(error_msg);
    alert(getHashParameter("error_description"));
    } else if (token) {
    $('.mind_map_link').each(function() {
    var _href = $(this).attr("href");
    $(this).attr("href", _href + '#' + getTreeURIParameters());
    });
    $.ajax({
    url: "https://mydomain.zendesk.com/api/v2/users/me.json?"+getTreeURIParameters(),
    method: 'GET'
    }).done(function(data, textStatus, xhr) {
    $("#requestorName").val(data.user.name);
    $("#requestorEmail").val(data.user.email);
    $("#DT_LoggedInAs").html("<b>You are logged in as:</b> <font color=\"blue\">"+data.user.email+"</font>");
    }).fail(function(xhr, textStatus, errorThrown) {
    console.log("xhr=["+xhr+"]");
    console.log("textStatus=["+textStatus+"]");
    console.log("errorThown=["+errorThrown+"]");
    alert("An error occured getting the user name and email, check the console.");
    }).always(function() {
    });
    } else {
    // setup the ZenDesk OATH redirect URL (localhost dev environment is the default)
    var redirect_uri = "http://localhost/VolarDecisionTree.html";
    if (window.location.host.indexOf("googledrive.com")>-1) {
    var pathArray = window.location.pathname.split('/');
    redirect_uri = window.location.protocol+"//googledrive.com";
    for(i=0;i<pathArray.length-1;i++) { redirect\_uri += pathArray[i] + "/"; } redirect\_uri += "VolarDecisionTree.html"; } else if (window.location.host.indexOf("my-zendesk-site.mydomain.com")>-1) {
    redirect_uri = "https://my-zendesk-site.mydomain.com";
    }

    // we need to authenticate with ZenDesk
    var params = {"client_id":"volar_decision_tree_development", "response_type":"token", "redirect_uri":redirect_uri, "scope":"read\%20write" };
    post_to_url("https://mydomain.zendesk.com/oauth/authorizations/new", params, "GET");
    }

    $('#myModalSubmit').click(function() {
    $('#myModal').modal('hide');
    create_ticket($('#requestType').val(),$('#requestSubject').val(),$('#requestDescription').val(),$('#requestPriority').val(),$('#requestStatus').val(),$('#requestTags').val());
    });

    $('#mySmallModalViewTicket').click(function() {
    var newPage ="https://mydomain.zendesk.com/agent/#/tickets/"+ticket_id;
    window.location = newPage;
    });

    $('#mySmallModalOK').click(function() {
    $('#mySmallModal').modal('hide');
    });

    $('#loading').hide();
    });

     

     

    (2) add the following file in the same directory as the html file(my-zendesk-script-file.html) with the above code:

    <?xml version="1.0" encoding="UTF-8"?>

    <configuration>

        <system.webServer>

            <defaultDocument>

                <files>

                    <add value="my-zendesk-script-file.html" />

                </files>

            </defaultDocument>

        </system.webServer>

    </configuration>

     

     

    (3) add (in the same directory) the following .htaccess file:

    DirectoryIndex my-zendesk-script-file.html

     

    This is all that I can remember that I did to get this to work.  

     

    Next, I should say that, about once every 6 weeks, Google Drive would fail to host the file.  When someone would try to access it, it would 404.  The only way to fix it was to delete and (via git) rebuild it.  After the third time, as I should have done in the first place, I spun up an Amazon Micro instance and hosted it there.  It has been trouble free ever since.

     

  • Avatar
    Anara D.

    Oh wow, thank you so much Ben!!!!! I will try this :-) 

  • Avatar
    Ben Askren

    Anara -

    I need to make a small correction.  The part of the .ajax that calls users/me should be changed to the following:

    $.ajax({
        url: "https://ihighlex.zendesk.com/api/v2/users/me.json?"+getTreeURIParameters(),
        method: "GET",
        type: "GET",
        cache: false,
        headers: {"Accept": "application/json"},
        contentType: "application/json",
        crossDomain: true
    }).done(function(data, textStatus, xhr) {
        $("#requestorName").val(data.user.name);
        $("#requestorEmail").val(data.user.email);
        $("#DT_LoggedInAs").html("<b>You are logged in as:</b> <font color=\"blue\">"+data.user.email+"</font>");
    }).fail(function(xhr, textStatus, errorThrown) {
        console.log("xhr=["+xhr+"]");
        console.log("textStatus=["+textStatus+"]");
        console.log("errorThown=["+errorThrown+"]");
        alert("An error occured getting the user name and email, check the console.");
    }).always(function() {
    });

    Notice the addition of the cache, headers and crossDomain parameters to the .ajax call.

     

    • Ben

     

     

  • Avatar
    Joel A Taylor

    Ben, where you able to get Postman working? I'm having trouble building a PUT request for a simple User update and I'm getting the 403 Forbidden header response on my request.

  • Avatar
    Pradeep Balasundaram

    Hi - I am getting a 403 forbidden header response from Postman as well for a POST update for ticket creation. is there a workaround for this?

Please sign in to leave a comment.

Powered by Zendesk