使用Go语言实现微信公众平台
程序员文章站
2022-03-21 10:29:32
这个不是全部的代码哦,只是一个演示可以验证跟接受post传过来的消息并且能返回消息,中间的回复逻辑就待需要各位同志们自己写了哈
复制代码 代码如下:
/*
 ...
这个不是全部的代码哦,只是一个演示可以验证跟接受post传过来的消息并且能返回消息,中间的回复逻辑就待需要各位同志们自己写了哈
复制代码 代码如下:
/*
语言实现公众平台
*/
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语言工程结构