使用Go语言实现微信公众平台
这个不是全部的代码哦,只是一个演示可以验证跟接受post传过来的消息并且能返回消息,中间的回复逻辑就待需要各位同志们自己写了哈
/*
*@go语言实现公众平台
*/
packagemain
import(
"crypto/sha1"
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"sort"
"strings"
"time"
)
typeRequeststruct{
ToUserName string
FromUserNamestring
CreateTime time.Duration
MsgType string
Content string
MsgId int
}
typeResponsestruct{
ToUserName string`xml:"xml>ToUserName"`
FromUserNamestring`xml:"xml>FromUserName"`
CreateTime string`xml:"xml>CreateTime"`
MsgType string`xml:"xml>MsgType"`
Content string`xml:"xml>Content"`
MsgId int `xml:"xml>MsgId"`
}
funcstr2sha1(datastring)string{
t:=sha1.New()
io.WriteString(t,data)
returnfmt.Sprintf("%x",t.Sum(nil))
}
funcaction(whttp.ResponseWriter,r*http.Request){
postedMsg,err:=ioutil.ReadAll(r.Body)
iferr!=nil{
log.Fatal(err)
}
r.Body.Close()
v:=Request{}
xml.Unmarshal(postedMsg,&v)
ifv.MsgType=="text"{
v:=Request{v.ToUserName,v.FromUserName,v.CreateTime,v.MsgType,v.Content,v.MsgId}
output,err:=xml.MarshalIndent(v,"","")
iferr!=nil{
fmt.Printf("error:%v\n",err)
}
fmt.Fprintf(w,string(output))
}elseifv.MsgType=="event"{
Content:=`"欢迎关注
我的微信"`
v:=Request{v.ToUserName,v.FromUserName,v.CreateTime,v.MsgType,Content,v.MsgId}
output,err:=xml.MarshalIndent(v,"","")
iferr!=nil{
fmt.Printf("error:%v\n",err)
}
fmt.Fprintf(w,string(output))
}
}
funccheckSignature(whttp.ResponseWriter,r*http.Request){
r.ParseForm()
vartokenstring="你的token"
varsignaturestring=strings.Join(r.Form["signature"],"")
vartimestampstring=strings.Join(r.Form["timestamp"],"")
varnoncestring=strings.Join(r.Form["nonce"],"")
varechostrstring=strings.Join(r.Form["echostr"],"")
tmps:=[]string{token,timestamp,nonce}
sort.Strings(tmps)
tmpStr:=tmps[0]+tmps[1]+tmps[2]
tmp:=str2sha1(tmpStr)
iftmp==signature{
fmt.Fprintf(w,echostr)
}
}
funcmain(){
http.HandleFunc("/check",checkSignature)
http.HandleFunc("/",action)
http.ListenAndServe(":8080",nil)
}