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

2022-10-13,,

这篇文章主要介绍了使用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语言中的Array、Slice、Map和Set使用详解
  • Go语言实现简单的一个静态WEB服务器
  • GO语言并发编程之互斥锁、读写锁详解
  • ubuntu下搭建Go语言(golang)环境
  • GO语言(golang)基础知识
  • 浅谈Go语言中字符串和数组
  • GO 语言学习指南

《使用Go语言实现微信公众平台.doc》

下载本文的Word格式文档,以方便收藏与打印。