Skip to content

Instantly share code, notes, and snippets.

@defp
Created March 16, 2017 09:17
Show Gist options
  • Save defp/0ad6aa50a398863f3010f466c1f143bb to your computer and use it in GitHub Desktop.
Save defp/0ad6aa50a398863f3010f466c1f143bb to your computer and use it in GitHub Desktop.
Wechat validateUrl
package main
import (
"crypto/sha1"
"fmt"
"io"
"log"
"net/http"
"sort"
"strings"
)
const (
token = "aa"
)
func makeSignature(timestamp, nonce string) string {
sl := []string{token, timestamp, nonce}
sort.Strings(sl)
s := sha1.New()
io.WriteString(s, strings.Join(sl, ""))
return fmt.Sprintf("%x", s.Sum(nil))
}
func validateUrl(w http.ResponseWriter, r *http.Request) bool {
timestamp := strings.Join(r.Form["timestamp"], "")
nonce := strings.Join(r.Form["nonce"], "")
signatureGen := makeSignature(timestamp, nonce)
signatureIn := strings.Join(r.Form["signature"], "")
if signatureGen != signatureIn {
return false
}
echostr := strings.Join(r.Form["echostr"], "")
fmt.Fprintf(w, echostr)
return true
}
func procRequest(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
if !validateUrl(w, r) {
log.Println("Wechat Service: this http request is not from Wechat platform!")
return
}
log.Println("Wechat Service: validateUrl Ok!")
}
func main() {
log.Println("Wechat Service: Start!")
http.HandleFunc("/webchat", procRequest)
err := http.ListenAndServe(":80", nil)
if err != nil {
log.Fatal("Wechat Service: ListenAndServe failed, ", err)
}
log.Println("Wechat Service: Stop!")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment