There are 2 ways to do this and I'll explain each one.
METHOD ONE: The Theory Approach
This method can be good if you understand theory. I know this will seem like a shameless plug, but I literally just put together a series on this on my YouTube account: "Playing By Ear Playlist". I'm assuming that you may not have a theory background. If you don't, and you're willing to take time to acquire one, the videos will help. It is the slower way to identify chords and keys, but it is a fool-proof method that I use with all of my students.
This method is the faster of the two, but it requires you to have a decent ear. I call it the "completing the scale" method.
Step 1: You have to know what a major scale sounds like. Practice by singing it over and over and over again so that you're intimately familiar with its sound.
Step 2: Hum the melody that you've created and then choose a note within that melody and try to sing a note above it within the scale you're singing in. Remember, at this point, we have no idea what that scale might be, but most people can intuitively extrapolate the note above a note.
Step 3: Perform step 2 again, except this time you'll want to sing two notes above any of the notes that are in your melody.
Step 4: Perform step 2 again, except this time continue singing notes above until it sounds somewhat like a major scale.
Step 5: Find the "place of rest" within the major scale. This would be the note known as "do" (pronounced "doh") (the first note of the scale). If you can find this note and identify it on your guitar, then this will be the key that you're in.
Step 6: Identify the chords that belong to that scale. For instance, if the "do" you found was G, then you're in G major. The chords associated with this key are G major, A minor, B minor, C major, D major, E minor and F# diminished (don't use this one). The chords that you need for your song will be among the chords that belong to the scale.
Note: For each melody note you sing, there are usually multiple chords you can use. Select the one that most suits your song.