如何使用Go语言如何实现微信公众平台

一片金黄的阳光,照着苍绿的崖壁,崖壁上长着漂亮的小花,像蝴蝶一样动人。走入自然,踏青游玩,在大自然中尽情放松,享受清新空气。

这个不是全部的代码哦,只是一个演示可以验证跟接受post传过来的消息并且能返回消息,中间的回复逻辑就待需要各位同志们自己写了哈


/*
*@go语言实现公众平台
*/
package main
import (
"crypto/sha1"
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"sort"
"strings"
"time"
)
type Request struct {
ToUserName string
FromUserName string
CreateTime time.Duration
MsgType string
Content string
MsgId int
}
type Response struct {
ToUserName string `xml:"xml>ToUserName"`
FromUserName string `xml:"xml>FromUserName"`
CreateTime string `xml:"xml>CreateTime"`
MsgType string `xml:"xml>MsgType"`
Content string `xml:"xml>Content"`
MsgId int `xml:"xml>MsgId"`
}
func str2sha1(data string) string {
t := sha1.New()
io.WriteString(t, data)
return fmt.Sprintf("%x", t.Sum(nil))
}
func action(w http.ResponseWriter, r *http.Request) {
postedMsg, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Fatal(err)
}
r.Body.Close()
v := Request{}
xml.Unmarshal(postedMsg, &v)
if v.MsgType == "text" {
v := Request{v.ToUserName, v.FromUserName, v.CreateTime, v.MsgType, v.Content, v.MsgId}
output, err := xml.MarshalIndent(v, " ", " ")
if err != nil {
fmt.Printf("error:%v\n", err)
}
fmt.Fprintf(w, string(output))
} else if v.MsgType == "event" {
Content := `"欢迎关注
我的微信"`
v := Request{v.ToUserName, v.FromUserName, v.CreateTime, v.MsgType, Content, v.MsgId}
output, err := xml.MarshalIndent(v, " ", " ")
if err != nil {
fmt.Printf("error:%v\n", err)
}
fmt.Fprintf(w, string(output))
}
}
func checkSignature(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
var token string = "你的token"
var signature string = strings.Join(r.Form["signature"], "")
var timestamp string = strings.Join(r.Form["timestamp"], "")
var nonce string = strings.Join(r.Form["nonce"], "")
var echostr string = strings.Join(r.Form["echostr"], "")
tmps := []string{token, timestamp, nonce}
sort.Strings(tmps)
tmpStr := tmps[0] + tmps[1] + tmps[2]
tmp := str2sha1(tmpStr)
if tmp == signature {
fmt.Fprintf(w, echostr)
}
}
func main() {
http.HandleFunc("/check", checkSignature)
http.HandleFunc("/", action)
http.ListenAndServe(":8080", nil)
}

到此这篇关于如何使用Go语言如何实现微信公众平台就介绍到这了。信仰是生命中的一盏灯,灯若熄灭了,人生便失去方向,随之而来的将是无边的恐惧和失望感。更多相关如何使用Go语言如何实现微信公众平台内容请查看相关栏目,小编编辑不易,再次感谢大家的支持!