GithubHelp home page GithubHelp logo

freshworks / fresh-samples Goto Github PK

View Code? Open in Web Editor NEW
183.0 100.0 182.0 197 KB

Samples of code created by freshdesk

Ruby 9.62% C# 29.54% HTML 3.76% PHP 23.06% Python 6.95% Java 19.59% JavaScript 4.92% TypeScript 2.56%

fresh-samples's Introduction

Sample code for API V2

Samples of code created by freshdesk

fresh-samples's People

Contributors

ahamedalthaf avatar hrishikesh-p avatar huan avatar johnpaulh avatar rashmiram avatar seetharam-rajagopal avatar shoaibmerchant avatar sooryazeal avatar sribalakumar avatar steynvanesveld avatar subwiz avatar sudhircirra avatar thanashyam avatar vicky-fd avatar yovasx2 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fresh-samples's Issues

SSL Exception

I get this exception on Windows 10 (net framework 4.5.2):

System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send. ---> System.IO.IOException: Authentication failed because the remote party has closed the transport stream.

Any ideas ?

having non ASCII characters in filenames

Hello,

(I'm referring to Python/create_ticket_attachment.py)

I have a pretty similar code to this one (except that I only pass my attachments in files=... and I pass the other info in data=..., all encoded to be multipart/form compliant).

My filenames have non ASCII characters, like 'deux-étoiles.jpg' and I get an error

{"description":"Validation failed","errors":[{"field":"attachments","message":"It should contain elements of type valid file format only","code":"datatype_mismatch"}]}

My call

# This code works without problem when only ascii chars in filenames
r = requests.post(url, files=attached_files, data=multipart_data, auth=auth)

Add an attachment to a ticket

Hi,
I use this example for adding an attachment to a ticket: https://github.com/freshdesk/fresh-samples/blob/master/c-sharp_samples/AddNoteWithAttachment.cs, changed only the api_key and attachment's path,

but I always get an error: "The remote server returned an error: (500) Internal Server Error."
I can't figure out what is the problem... Does this code works?
I successfully added a note to existing ticket using the sample, but stuck on adding an attachment.

Best Regards,
Marina

Location for Knowledge Base

Is there any location related to Solutions/Knowledge base?

I've tried something like kbase-sidebar but it doesn't seem to be working.

image

Error while trying to create a ticket with attachment

I am trying to create a ticket using FreshDesk create ticket with attachment using axios library in react native,
code:

	const headers = {
                'Content-Type': 'multipart/form-data',
		"mimeType": "multipart/form-data",
	  }
	  var formdata = new FormData();
	  formdata.append('attachments[]', {
		uri: "file://"+attachments[0],
		type: 'image/jpeg',
		name: 'attachment1'
  		});
	  formdata.append('description',"description");
	  formdata.append('email', "email");
	  formdata.append('subject',  "subject");
	  formdata.append('priority', '1');
	  formdata.append('status', '2');
	  formdata.append('type', 'Client Complaint');
	  formdata.append('custom_fields', {"custom_field1": "test", "custom_field2": "test"});


	  
	return axios.post(FD_BASEURL+'tickets/',formdata,{
		headers:headers,
		auth:{ username: key, password: 'x' },
	})

Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:87)
at XMLHttpRequest.dispatchEvent (event-target.js:172)
at XMLHttpRequest.setReadyState (XMLHttpRequest.js:580)
at XMLHttpRequest.__didCompleteResponse (XMLHttpRequest.js:394)
at XMLHttpRequest.js:507
at RCTDeviceEventEmitter.emit (EventEmitter.js:189)
at MessageQueue.__callFunction (MessageQueue.js:366)
at MessageQueue.js:106
at MessageQueue.__guard (MessageQueue.js:314)

Creating a ticket redirects? PHP

I'm using the sample PHP code to try and create a ticket via cURL. It seems that the response I'm getting back is "You are being redirected."

The ticket isn't being created either. Is there some reason this would be happening that I'm overlooking?

I've copied the PHP sample code verbatim, but swapped out the fd_domain, token and cc_emails (inside the data arraay).

Thanks,
Evan

Python - Create ticket with attachment

I have a problem with creating a FreshDesk ticket with attachments. I've used a code from this repository but it's not working for me.

My setup:

  • Python 3.8
  • Requests library 2.28.1

My python code:

# Removed credentials from the script
api_key = "..."
domain = "..."
password = "x"
url = "https://" + domain + ".freshdesk.com/api/v2/"

def create_ticket_with_attachment():
    multipart_data = [
        ('email', ('', '[email protected]')),
        ('subject', ('', 'Ticket Title')),
        ('status', ('', '2')),
        ('priority', ('', '2')),
        ('cc_emails[]', ('', '[email protected]')),
        ('cc_emails[]', ('', '[email protected]')),
        ('attachments[]', ('logo.png', open("/Users/mgrandys/Desktop/test.png", "rb"), 'image/png')),
        ('description', ('', 'Ticket description.'))
    ]

    response = requests.post(f"{url}tickets", auth=(api_key, password), files=multipart_data)
    response_json = response.json()
    print(response_json)

an the response is:

{
  'description': 'Validation failed',
  'errors': [
    {
      'field': 'subject',
      'message': 'It should be a/an String',
      'code': 'missing_field'
    },
    {
      'field': 'description',
      'message': 'It should be a/an String',
      'code': 'missing_field'
    },
    {
      'field': 'status',
      'message': "It should be one of these values: '2,3,4,5,8,6,7'",
      'code': 'missing_field'
    },
    {
      'field': 'priority',
      'message': "It should be one of these values: '1,2,3,4'",
      'code': 'missing_field'
    },
    {
      'field': 'requester_id',
      'message': 'Please fill at least 1 of requester_id, phone, email, twitter_id, facebook_id, unique_external_id fields',
      'code': 'missing_field'
    }
  ]
}

response headers:

{
  'Date': 'Thu, 13 Oct 2022 08:22:28 GMT',
  'Content-Type': 'application/json; charset=utf-8',
  'Transfer-Encoding': 'chunked',
  'Connection': 'keep-alive',
  'Status': '400 Bad Request',
  'Pragma': 'no-cache',
  'X-Request-Id': '64e9d83d-5d4b-45f3-8736-7aba25201e92',
  'X-Freshdesk-Api-Version': 'latest=v2; requested=v2',
  'X-Rack-Cache': 'invalidate, pass',
  'Cache-Control': 'no-cache, no-store, max-age=0, must-revalidate',
  'X-Xss-Protection': '1; mode=block',
  'X-Ua-Compatible': 'IE=Edge,chrome=1',
  'X-Content-Type-Options': 'nosniff',
  'Expires': 'Wed, 13 Oct 2010 00:00:00 UTC',
  'Set-Cookie': '_x_w=7_1; path=/; HttpOnly; secure, _x_m=x_c; path=/; HttpOnly; secure',
  'X-Fw-Ratelimiting-Managed': 'true',
  'X-Ratelimit-Total': '50',
  'X-Ratelimit-Remaining': '48',
  'X-Ratelimit-Used-Currentrequest': '1',
  'X-Envoy-Upstream-Service-Time': '54',
  'X-Trace-Id': '00-8630f03a5747c4ffa61c69ab8a5302a6-ab8370909c78fbc2-00',
  'Nel': '{ "report_to": "nel-endpoint", "max_age": 300, "include_subdomains": true}',
  'Report-To': '{ "group": "nel-endpoint", "max_age": 300, "include_subdomains": true, "endpoints": [{"url": "https://edge-admin.freshedge.net/nelreports"}]}',
  'Server': 'fwe'
}

Also I tried to use ('subject', ('Ticket Title')), instead of ('subject', ('', 'Ticket Title')), but getting another error:

{
  'field': 'subject',
  'message': 'Value set is of type valid file format.It should be a/an String',
  'code': 'datatype_mismatch'
}

response headers:

{
  'Date': 'Thu, 13 Oct 2022 08:19:29 GMT',
  'Content-Type': 'application/json; charset=utf-8',
  'Transfer-Encoding': 'chunked',
  'Connection': 'keep-alive',
  'Status': '400 Bad Request',
  'Pragma': 'no-cache',
  'X-Request-Id': '82a4e008-6f82-496f-8c57-511729049a91',
  'X-Freshdesk-Api-Version': 'latest=v2; requested=v2',
  'X-Rack-Cache': 'invalidate, pass',
  'Cache-Control': 'no-cache, no-store, max-age=0, must-revalidate',
  'X-Xss-Protection': '1; mode=block',
  'X-Ua-Compatible': 'IE=Edge,chrome=1',
  'X-Content-Type-Options': 'nosniff',
  'Expires': 'Wed, 13 Oct 2010 00:00:00 UTC',
  'Set-Cookie': '_x_w=7_1; path=/; HttpOnly; secure, _x_m=x_c; path=/; HttpOnly; secure',
  'X-Fw-Ratelimiting-Managed': 'true',
  'X-Ratelimit-Total': '50',
  'X-Ratelimit-Remaining': '49',
  'X-Ratelimit-Used-Currentrequest': '1',
  'X-Envoy-Upstream-Service-Time': '57',
  'X-Trace-Id': '00-b74605956453fe5651157120e73059d5-342bb7f3e4b89944-00',
  'Nel': '{ "report_to": "nel-endpoint", "max_age": 300, "include_subdomains": true}',
  'Report-To': '{ "group": "nel-endpoint", "max_age": 300, "include_subdomains": true, "endpoints": [{"url": "https://edge-admin.freshedge.net/nelreports"}]}',
  'Server': 'fwe'
}

Could you provide a working example of Python3 code for creating tickets with attachments?
Thank you in advance :)

PHP: validation error for all ticket fields when setting header content-type "multipart/form-data"

[using php 5.6 on a windows machine for testing]
Hello,
I've followed this guide to upload an attachment
https://github.com/freshdesk/fresh-samples/blob/master/PHP/create_ticket_with_attachment.php
and it worked when launched directly without using an html form as data source and without setting any header via curl_setopt()
(it's also working without attachments using the default content-type 'application/json', but this is not what I need )
the request header, using the basic example (no html post request but just sample data created on the fly) looks like this (I assume the content-type and boundary are set somewhere under the curtain)

Host: xxxx.freshdesk.com
Authorization: Basic xxxxxxxxxxxxxxxxx==
Accept: */*
Content-Length: 79971
Expect: 100-continue
Content-Type: multipart/form-data; boundary=------------------------d7fb41f0a8e1064b

now, my problem is when I try to use this code on an actual POST from a user, the request's content-type is automatically set to

application/x-www-form-urlencoded

even though I specified in the html form the enctype "multipart/form-data"
so I had to curl_setopt the content-type header

$headers[] = "Content-type: multipart/form-data;";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

My API call now looks like this

    $ticket_payload = array(
       'name' => $requester_name,
       'email' => $requester_email,
       'subject' => 'XXX' - new ticket: '.$ticket_data['subject'],
       'description' => $ticket_data['description'],
       'priority' => intval($ticket_data['priority']),
       'status' => intval($ticket_data['status']),
       'source' => intval($ticket_data['source']),
       'type' => $type,
       'responder_id' => $this->default_agent_id,
       'attachments[]' =>  curl_file_create($local_file_path, mime_content_type($local_file_path), $filename),
       'tags' => $ticket_data['tags'],
   );

curl_setopt($this->ch, CURLOPT_POSTFIELDS, $ticket_payload );

which gets an

Error, HTTP Status Code : 400

and in the response, a list of validation errors that includes basically every ticket field
it seems that if the attachment is there, and the mutipart/form-data header with it, the actual ticket payload (i.e. user-POSTed data) is lost somewhere along the call

How can I post both data and a file ?
I took a look also at this other example
https://github.com/freshdesk/fresh-samples/blob/master/PHP/create_ticket_with_multiple_attachments.php
which manually writes headers and body of the request for every field and file using a custom 'boundary' but honestly it looks a bit weird to me, no curl_create_file and a <file_get_contents()> call for every file to attach

Looking at issues posted here
#37
I noticed another user has the same problem with Node.js, and another user here
#44
suggests to separate the ticket data from the files data

Can you help me with this please ?
User uploaded attachments for incidents and bugs are quite important for us

Thanks in advance
Marco

How to add cc_emails or tags in new ticket

I am using your code samples to create ticket. I tried to add cc_emails in new ticket. Their type is string array and I could not find any coding that writes string array to the stream.

Can you please provide a sample in C# that adds cc_emails or tags to Freshdesk api v2.

Thank you

Ruby create ticket with attachment

This function create ticket with attachment is returning this from the API:

API Error: Your request is not successful. If you are not able to debug this error properly, mail us at [email protected] with the follwing X-Request-Id
X-Request-Id : 47a8b273e978a8715b83cd62321fc32f
Response Code: 400
Response Body: {"description":"Validation failed","errors":[{"field":"description_html","message":"Unexpected/invalid field in request","code":"invalid_field"}]}
=> nil

So I think the field need to be just description

OO Freshdesk API Class for Google Apps Script

I had just wrote a easy to use OO wrapper: gas-freshdesk.

looks like this:

var API_TOKEN = PropertiesService.getScriptProperties().getProperty('FreshDeskApiToken')
var MyFreshdesk = new Freshdesk('https://mikebo.freshdesk.com', API_TOKEN)

var ticket = new MyFreshdesk.Ticket({
  helpdesk_ticket: {
    description:'A description'
    , subject: 'A subject'
    , email: '[email protected]'
  }
})

ticket.assign(9000658396)
ticket.addNote({
  body: 'Hi tom, Still Angry'
  , private: true
})
ticket.setPriority(2)
ticket.setStatus(2)

ticket.del()
ticket.restore()

Logger.log('ticket #' + ticket.getId() + ' was set!')

hope it could useful and help others for easy start to api freshdesk.

Please document freshplug api helper methods

Would be nice to have a little more documentation on say the freshdesk proxy

var proxy = new Freshdesk.Widget(opts);

And what you can and cannot do with the CustomWidget.include_js() like will it handle placeholders inside my widget? Can i include html/style in it as well? So, that i don't need to keep pasting it in to the Freshplug ui.

How to send input value throw freshdesk api? Need help asap

i need help, how send form input value throw this freshdesk api.. what i need to change, to insert input id in ticket_data as value.. please help

<input id="lc-calendar_till" type="hidden" placeholder="Date from">


<script>
$(document).ready(function(){
    $("button").click( // click to send
      function() {
        var yourdomain = 'domainxxxx'; 
        var api_key = 'apikeyherexxx'; 

 

 ticket_data = '{ "description": "here is description", "subject": "Subject text", "email": "[email protected]", "priority": 1, "status": 2 }';
  

        $.ajax(
          {
            url: "https://"+yourdomain+".freshdesk.com/api/v2/tickets",
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            headers: {
              "Authorization": "Basic " + btoa(api_key + ":x")
            },

            data: ticket_data,
            
          }
        );
      }
    );
});



</script>

new feature: real time interface with Freshdesk

I'm trying to build a real time interface with Freshdesk and I'd like an API that would let me fetch tickets information querying for the tickets updated after a certain instant in time.
i.e., I'd like to load all the tickets updated after the 1st of January 2015 with an API call such as
curl https://{subdomain}.freshdesk.com/api/....?start_time=1442000000 -v -u {email_address}:{password}.

What I'd expect is an API that returns a set of tickets updated after that date and a pointer to next page of tickets (if any). This is a pretty common pattern and it exist in most of the other SaaS CRM tools.
Without it I don't see any way to build a real time interface with Freshdesk.
If this feature in your roadmap and if yes when is it planned to be released ?

Nodejs create_ticket_multiple_attachments.js does not work when trying to attach file

Seems like the
.attach('attachments[]', fs.createReadStream('/path/to/file1.ext'))
creates an error in my reqeuest. I got a 400 response with complains about some fields which are set:

{ description: 'Validation failed', errors:  [ { field: 'description', message: 'It should be a/an String', code: 'missing_field' }, { field: 'status', message: 'It should be one of these values: \'2,3,4,5,6,7\'', code: 'missing_field' }, { field: 'subject', message: 'It should be a/an String', code: 'missing_field' }, { field: 'priority', message: 'It should be one of these values: \'1,2,3,4\'', code: 'missing_field' }, { field: 'requester_id', message: 'Please fill at least 1 of requester_id, phone, email, twitter_id, facebook_id fields', code: 'missing_field' }, { field: 'type', message: 'It should be one of these values: \'Question,Problem,Feature Request,Praise,Complain\'', code: 'missing_field' } ] }

When I comment out all the .attach lines the ticket is created correctly. The files are present in the path.

My unirest request looks like this:

{
    "_stream": false,
    "_multipart": [
        {
            "name": "attachments[]",
            "value": {
                "_readableState": {
                    "objectMode": false,
                    "highWaterMark": 65536,
                    "buffer": [],
                    "length": 0,
                    "pipes": null,
                    "pipesCount": 0,
                    "flowing": null,
                    "ended": false,
                    "endEmitted": false,
                    "reading": false,
                    "sync": true,
                    "needReadable": false,
                    "emittedReadable": false,
                    "readableListening": false,
                    "defaultEncoding": "utf8",
                    "ranOut": false,
                    "awaitDrain": 0,
                    "readingMore": false,
                    "decoder": null,
                    "encoding": null
                },
                "readable": true,
                "domain": null,
                "_events": {},
                "_eventsCount": 1,
                "path": "/tmp/test0.png",
                "fd": null,
                "flags": "r",
                "mode": 438,
                "autoClose": true
            },
            "options": {
                "attachment": true
            },
            "attachment": true
        },
        {
            "name": "status",
            "value": "2",
            "options": {
                "attachment": false
            },
            "attachment": false
        },
        {
            "name": "priority",
            "value": "3",
            "options": {
                "attachment": false
            },
            "attachment": false
        },
        {
            "name": "type",
            "value": "Question",
            "options": {
                "attachment": false
            },
            "attachment": false
        },
        {
            "name": "email",
            "value": "[email protected]",
            "options": {
                "attachment": false
            },
            "attachment": false
        },
        {
            "name": "subject",
            "value": "Exemplary ticket subject",
            "options": {
                "attachment": false
            },
            "attachment": false
        },
        {
            "name": "description",
            "value": "test description",
            "options": {
                "attachment": false
            },
            "attachment": false
        },
        {
            "name": "custom_fields[platform]",
            "value": "test",
            "options": {
                "attachment": false
            },
            "attachment": false
        },
        {
            "name": "custom_fields[area]",
            "value": "test",
            "options": {
                "attachment": false
            },
            "attachment": false
        }
    ],
    "_form": [],
    "options": {
        "url": "https://<my_domian>.freshdesk.com/api/v2/tickets",
        "method": "post",
        "headers": {
            "Authorization": "Basic <my_auth>",
            "Content-Type": "multipart/form-data"
        }
    },
    "as": {}
}

Licensing the samples

I haven't found a licensing scheme for the samples.
Maybe it could be licensed as a whole under one license, but all contributors have to agree on that.

Ruby create ticket

The API response:

{"description":"Validation failed","errors":[{"field":"status","message":"Value set is of type String.It should be one of these values: '2,3,4,5,6,7'","code":"datatype_mismatch"}]}

Due to the status: '2' conversion to json, what is "staus": "2" and not an integer

PHP Attatchment with Custom field

Not an issue, more of an approach to a problem I got into.
I have spent some time trying to figure out how to send an attachment along with custom fields without json encoding the whole array due the attachment getting not recognized:

<?php
 'email' => $email,
  'subject' => $subject,
  'description' => $txtMessage,
  'priority' => 2,
  'status' => 2,
  'custom_fields[fieldOne]'=> $One ,
  'custom_fields[fieldTwo]'=> $Two,
  'custom_fields[fieldThree]'=> $Three ,
'attachments[]' =>  curl_file_create("$pathToFile","$mimeType","$fileName") 

Note: I have tried working with:
'attachments'=>array('attachment_url'=>$pathToFile,'content_type'=>$mimeType,'name'=>$fileName'

I kept getting the following error message:
Error Message: {"description":"Validation failed","errors":[{"field":"attachments","message":"Value set is of type key/value pair.It should be a/an Array","code":"datatype_mismatch"}]}

Using JavaLite HTTP library

If you use JavaLite HTTP, than the amount of code is a lot less than using Apache.

  1. Add dependency:
<dependency>
  <groupId>org.javalite</groupId>
  <artifactId>javalite-common</artifactId>
  <version>2.2</version>
</dependency>
  1. Add import statements:
import org.javalite.common.JsonHelper;
import org.javalite.http.Get;
import org.javalite.http.Http;
import org.javalite.http.Post;

import java.util.Map;
import static org.javalite.common.Collections.map;
  1. Listing tickets:
Get get = Http.get("https://expresspigeon.freshdesk.com/api/v2/tickets").basic("Authkeyvalue", "X");
JsonHelper.toList(get.text()).forEach(t -> System.out.println(((Map)t).get("subject")));
  1. Creating a new ticket:
Map requestMap = map(
        "name", "John",
        "email", "[email protected]",
        "subject", "what about pants?",
        "description",  "someone's pants on fire!",
        "status", 2,
        "priority", 1
);

Post post = Http.post("https://expresspigeon.freshdesk.com/api/v2/tickets", JsonHelper.toJsonString(requestMap))
        .header("Content-Type", "application/json")
        .basic("Authkeyvalue", "X");

System.out.println(post.text());
System.out.println(post.responseMessage());
System.out.println(post.responseCode());

prints:

{"cc_emails":[],"fwd_emails":[],"reply_cc_emails":[],"ticket_cc_emails":[],"fr_escalated":false,"spam":false,"email_config_id":null,"group_id":null,"priority":1,"requester_id":22017318637,"responder_id":null,"source":2,"company_id":null,"status":2,"subject":"what about pants?","to_emails":null,"product_id":null,"id":10,"type":null,"due_by":"2019-04-21T20:46:20Z","fr_due_by":"2019-04-19T20:46:20Z","is_escalated":false,"description":"<div>someone's pants on fire!</div>","description_text":"someone's pants on fire!","custom_fields":{},"created_at":"2019-04-18T20:46:20Z","updated_at":"2019-04-18T20:46:20Z","tags":[],"attachments":[]}
Created
201

Nodejs samples don't look satisfying

I went through node.js samples, and don't find them of any help. ideally when adding attachments, i would not call attach for each attachment. this should be dynamic. Also it may be possible that the files are send from one service to another (if i am using microservice architecture, e.g form ui to apiGateway and then to ticket management system that stores the tickets ) as buffer data, however no example provided on how to handle buffer data. Also most of the times, we use axios and/or request module in place or unirest. There seem to be more open issues with no resolution provided from some time now.

Authenticate user to Add forum topic/post with email.

While migrating my existing forum to fresh-desk, I am picking each forum topic/post/comment with user name and email(who has created this) and trying to create on fresh-desk.

Is there already existing support for this?

Suggestion: One way to authenticate is user freshdesk-api-key, with user information(name, email).

Add an example using JavaSE with as few third party dependencies as possible

The current examples depend on Apache Commons HTTPClient API, Jersey, Glassfish and javax.json (part of JavaEE since its 7th version, can be used separately) whereas only the very last dependency is necessary. Why not providing an example using only JavaSE and javax.json?

At first, you simply create a URL:
URL url = new URL("http://YOUR_OWN_DOMAIN.freshdesk.com//helpdesk/tickets/filter/all_tickets?format=json&wf_order=updated_at&wf_order_type=desc&page=0");

Then, you open a connection:
HttpURLConnection con = (HttpURLConnection) url.openConnection();

After that, you prepare the connection parameters for the authentication:

con.setRequestMethod("GET");
con.setRequestProperty("Content-Type", "application/json");
String base64encodedApiKey = DatatypeConverter.printBase64Binary(YOUR_FRESHDESK_API_KEY.getBytes(Charset.forName("UTF-8")));
con.setRequestProperty("Authorization", "Basic " + base64encodedApiKey);

Finally, you get the input stream and you try to read the JSON content from it:

InputStream inputStream = con.getInputStream();
JsonReader jsonReader = Json.createReader(inputStream);
JsonArray jsonTicketPageArray = jsonReader.readArray();

Each JsonObject represents a ticket.

N.B: If the returned array is empty, then the page is empty, there is no need to try reading other pages. You can get the error stream when something goes wrong but the provided information isn't worth it, simply catch the IOException. My source code uses the first version of the FreshDesk API. I have decided to report this issue at least to give some information to other developers with similar requirements. Imagine that someone uses JBoss instead of Glassfish, why should we use org.glassfish.jersey.client.authentication.HttpAuthenticationFeature? Best regards.

Response blank

Error, HTTP Status Code : 0 Headers are Response are

Array
(
[url] => https://groovy.freshdesk.com/api/v2/tickets
[content_type] =>
[http_code] => 0
[header_size] => 0
[request_size] => 0
[filetime] => -1
[ssl_verify_result] => 1
[redirect_count] => 0
[total_time] => 0.437
[namelookup_time] => 0.016
[connect_time] => 0.234
[pretransfer_time] => 0
[size_upload] => 0
[size_download] => 0
[speed_download] => 0
[speed_upload] => 0
[download_content_length] => -1
[upload_content_length] => -1
[starttransfer_time] => 0
[redirect_time] => 0
[redirect_url] =>
[primary_ip] => 54.175.248.244
[certinfo] => Array
(
)

[primary_port] => 443
[local_ip] => 192.168.0.101
[local_port] => 63988

)

Not able to create custom fields using PHP

I am using same example code to create ticket with custom fields like below (even checked in Postman):

$custom_fields = array("mobile" => 5788394511 );

$ticket_data = json_encode(array(
"description" => "Some details on the issue ...",
"subject" => "Support needed..",
"email" => "[email protected]",
"priority" => 1,
"status" => 2,
"cc_emails" => array("[email protected]", "[email protected]"),
"custom_fields" => $custom_fields
));

But I am getting error which says:

{"description":"Validation failed","errors":[{"field":"type","message":"Unexpected/invalid field in request","code":"invalid_field"}]}

Creating ticket with attachments giving strange error

i am using PHP Version 7.2.2 and i am following this document https://github.com/freshdesk/fresh-samples/blob/master/PHP/create_ticket_with_attachment.php to create a ticket with attachment but i am getting this error Error, HTTP Status Code : 0 Headers are Response are .

Here is my code below

$ticket_payload = array(
'email' => $email,
'subject' => 'test',
'description' => 'testing description content',
'priority' => 2,
'status' => 2,
'attachments[]' => curl_file_create("data/butterfly.png", "image/png", "butterfly.png"),
);

$url = "https://$yourdomain.freshdesk.com/api/v2/tickets"; $ch = curl_init($url);`

`$header[] = "Content-type: multipart/form-data";`

`curl_setopt($ch, CURLOPT_POST, false);`
`curl_setopt($ch, CURLOPT_HEADER, true);`
`curl_setopt($ch, CURLOPT_HTTPHEADER, $header);`
`curl_setopt($ch, CURLOPT_USERPWD, "$api_key:$password");`
`curl_setopt($ch, CURLOPT_POSTFIELDS, $ticket_payload);`
`curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);`

$server_output = curl_exec($ch);
$info = curl_getinfo($ch);
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$headers = substr($server_output, 0, $header_size);
$response = substr($server_output, $header_size);

am i doing something wrong ?

Notes with attachment not working

I use below code for uploading a note with attachments. But I received following error in response.

errorcode 400 - {"description":"Validation failed","errors":[{"field":"body","message":"It should be a/an String","code":"missing_field"}]}

If i comment out following line, able to upload body alone.

meb.addBinaryBody("attachments[]", attach2,
ContentType.TEXT_PLAIN.withCharset("utf-8"), attach2.getName());

`
public static String getArrayForUrlPostv2(String urlString) {

    try {

        final HttpClientBuilder hcBuilder = HttpClientBuilder.create();
        final RequestBuilder reqBuilder = RequestBuilder.post();
        final RequestConfig.Builder rcBuilder = RequestConfig.custom();

        // URL object from API endpoint:
        URL url = new URL(urlString);
        final String urlHost = url.getHost();
        final int urlPort = url.getPort();
        final String urlProtocol = url.getProtocol();
        reqBuilder.setUri(url.toURI());

        // Authentication:
        List<String> authPrefs = new ArrayList<>();
        authPrefs.add(AuthSchemes.BASIC);
        rcBuilder.setTargetPreferredAuthSchemes(authPrefs);
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
                new AuthScope(urlHost, urlPort, AuthScope.ANY_REALM),
                new UsernamePasswordCredentials(PreferenceMgr.getString(PreferenceMgr.KEY_AGENT_EMAIL),
                                                PreferenceMgr.getString(PreferenceMgr.KEY_AGENT_PASSWORD)));
        hcBuilder.setDefaultCredentialsProvider(credsProvider);
        AuthCache authCache = new BasicAuthCache();
        AuthSchemeBase authScheme = new BasicScheme();
        authCache.put(new HttpHost(urlHost, urlPort, urlProtocol), authScheme);
        HttpClientContext hccContext = HttpClientContext.create();
        hccContext.setAuthCache(authCache);

        // Body:
        MultipartEntityBuilder meb = MultipartEntityBuilder.create();
        meb.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);


        File attach2 = ApplicationNekt.getContext().getFileStreamPath(Constants.LogFileName + ".txt");
        meb.addBinaryBody("attachments[]", attach2,
                ContentType.TEXT_PLAIN.withCharset("utf-8"), attach2.getName());

        //meb.addTextBody("body", "testing");
        meb.addTextBody("body", "test", ContentType.TEXT_PLAIN);
        meb.addTextBody("private", "true", ContentType.TEXT_PLAIN);


        reqBuilder.setEntity(meb.build());

        // Execute:
        RequestConfig rc = rcBuilder.build();
        reqBuilder.setConfig(rc);

        HttpClient hc = hcBuilder.build();
        HttpUriRequest req = reqBuilder.build();
        HttpResponse response = hc.execute(req, hccContext);


        // Print out:
        HttpEntity body = response.getEntity();
        InputStream is = body.getContent();
        BufferedReader br = new BufferedReader(new InputStreamReader(is, Charset.forName("utf-8")));
        String line;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        int response_status = response.getStatusLine().getStatusCode();
        String response_body = sb.toString();

        Utilities.writeToLogFile(Constants.LOG_ERROR_LEVEL, "Response Status: " + response_status);
        Utilities.writeToLogFile(Constants.LOG_ERROR_LEVEL, "Body:\n");
        Utilities.writeToLogFile(Constants.LOG_ERROR_LEVEL, response_body);
        if (response_status > 400) {
            Utilities.writeToLogFile(Constants.LOG_ERROR_LEVEL, "X-Request-Id: " + response.getFirstHeader("x-request-id").getValue());
        } else if (response_status == 201) {
            //For creation response_status is 201 where are as for other actions it is 200
            try {
                Utilities.writeToLogFile(Constants.LOG_ERROR_LEVEL, "Update Successfull");
                //Creating JSONObject for the response string
                JSONObject response_json = new JSONObject(sb.toString());
                Utilities.writeToLogFile(Constants.LOG_ERROR_LEVEL, "Ticket ID: " + response_json.get("id"));
                return "success";
                //Utilities.writeToLogFile(Constants.LOG_ERROR_LEVEL, "Location : " + response.getFirstHeader("location").getValue());
            } catch (JSONException e) {
                Utilities.writeToLogFile(Constants.LOG_ERROR_LEVEL, "Error in JSON Parsing\n :" + e);
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;

`

filter for fetch tickets

?filter=new_and_my_open";

Any documentation how to expand this filter with a date range and customer/company?
And how to fetch also the timetracking details from the ticket(s) (if any available)?

This looks very interesting to automatically fetch the time tracking from tickets created by company/customer John Doe but only the timetracking from a fix period e.g. 1 June 2016 until 30 June 2016 and pull them into invoicing application.

I need the time tracking with from a certain date range only, because old tickets can be re-opened and could cause double invoicing.
So if I can fetch only records from past month, I'm good to go.

Thanks!

Viewing and Updating a ticket with custom fields

Is there a way to view and update a ticket with custom fields.

I used the C# freshdesk samples to view a specific ticket in my custom app, but I can't use custom fields

Is there a way to do this? Please help me with example code

Thank you

invalid freshplug sample

The custom-widget-sample.html is not a valid example. This is not valid jquery syntax and of course it produces errors in console in both firefox and chrome.
jQuery.ajax{ should probably be jQuery.ajax({ .

Create New ticket with custom fields and attachments using python requests.

I am using freshdesk API to create a new tickets with some custom fields and file attachments. Following the code sample given, the multipart structure which I am trying to send is:

multipart_data=[('subject', ('', 'sub')),
('status', ('', 3)),
('description', ('', 'des')),
('priority', ('', 2)),
('email', ('', '[email protected]')),
('custom_fields[]', ('info', 'reason: New Hire\nemployee: wmp\nuser: User One\npatch: value1\nteam: value1\ndescription: None\nattachment: None\nrequest_effected_date: None')),
('custom_fields[]', ('sub_category_name', 'I need to re-assign all accounts in a patch to another AE on my team')),
('custom_fields[]', ('category_name', 'Territory Assignment Change')),
('custom_fields[]', ('tenant_id', 'wild-butterfly-354')),
('custom_fields[]', ('category_id', 'asy8268aissugsudgutsuaytdu2')),
('custom_fields[]', ('sub_category_id', 'sjkhdksdaakdh89274987')),
('attachments[]', ('requirements.txt', <_io.BufferedReader name='requirements.txt'>, 'text/plain'))]

The request code written is:
headers = {'Content-type': 'multipart/form-data'}
response = requests.post(url, auth=__AUTH, headers = headers, files=meta_data)

The error which I am getting is:
fdata = fp.read()
AttributeError: 'int' object has no attribute 'read'

This error is coming from requests. I think this is because we are passing all the fields in files parameter, which is wrong.

custom-widget-sample.html

Hello,

I am working in a simple code that acess the Freshdesk api, to create a new ticket.
But, I got a CORS error. I am looking for solutions, some people said to me to modify thing in my webserver, but I cant do anything in there.

So, I find your solution to create a ticket by Ruby. I am trying to figure out how your api works.

In the file custom-widget-sample.html you have a script
...
url:"http://mystoreinventory.freshdesk.com/orders.php",
...

And I want to ask, HOW you set the "orders.php" file in you freshdesk domain?

Thank you for your help :)

Ticket with attachments

Hello there,
can you share a working example for ticket with attachment creation using the API?

The docs have not a proper request description nor example for this specific case.

Can you share a proper formatted request and attachment required handling in order to create ticket with attachment via API? I'm specially interested in a nodejs example.

Thanks in advance.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.