go WeChat development sdk-simple to use_image bed has been set up

go WeChat development sdk-simple to use

GitHub - silenceper/wechat: WeChat SDK for Go (WeChat SDK: simple and easy to use)

The sdk used is the above, here is a quick project example

git clone https://github.com/gowechat/example.git

Simple project structure

Image1

Here we simply use docker to run a redis

version: '3'
services:
  redis:
    image: redis:latest
    ports:
      - "6379:6379"
    command: ["redis-server", "--requirepass", ""]

Necessary information can be obtained on the WeChat public platform, please pay attention to apply for interface permission (WeChat authentication)

Image2

Example

My project requires the operation of public accounts. Here are some basic operation examples.

After cloning the basic project address

Image3

After completing the configuration and opening redis, you can obtain the specified functions.

Use redis (recommended)

// 在这里已经设置了全局cache,则在具体获取公众号/小程序等操作实例之后无需再设置,设置即覆盖
// 在这里已经设置了全局cache,则在具体获取公众号/小程序等操作实例之后无需再设置,设置即覆盖
func InitWechat() *wechat.Wechat {
	wc := wechat.NewWechat()
	redisOpts := &cache.RedisOpts{
		Host:        config.GVA_CONFIG.Redis.Host,
		Password:    config.GVA_CONFIG.Redis.Password,
		Database:    config.GVA_CONFIG.Redis.Database,
		MaxActive:   config.GVA_CONFIG.Redis.MaxActive,
		MaxIdle:     config.GVA_CONFIG.Redis.MaxIdle,
		IdleTimeout: config.GVA_CONFIG.Redis.IdleTimeout,
	}
	ctx := context.Background()
	redisCache := cache.NewRedis(ctx, redisOpts)

	//redisCache := cache.NewRedis(redisOpts)
	wc.SetCache(redisCache)
	return wc
}
func Wx() {
	wc := InitWechat()

	cfg := &offConfig.Config{
		AppID:     "",
		AppSecret: "",
		Token:     "xxx",
	}
	//officialAccount := wc.GetOfficialAccount(cfg)
	oa := wc.GetOfficialAccount(cfg)
	fmt.Println(oa.GetAccessToken())
	u := oa.GetUser()
	us, _ := u.ListUserOpenIDs()
	if us == nil {
		fmt.Print("heellwdjwd")
	}
	fmt.Println(us.Data.OpenIDs)
}

When using memory (not recommended)

package main

import (
    "fmt"
    wechat "github.com/silenceper/wechat/v2"
    "github.com/silenceper/wechat/v2/cache"
    offConfig "github.com/silenceper/wechat/v2/officialaccount/config"
)
func main() {
    wc := wechat.NewWechat()
    //这里本地内存保存access_token,也可选择redis,memcache或者自定cache
    memory := cache.NewMemory()
    cfg := &offConfig.Config{
        AppID:     "",
        AppSecret: "",
        Token:     "xxx",
        Cache: memory,
    }
    oa := wc.GetOfficialAccount(cfg)
    fmt.Println(oa.GetAccessToken())
    u := oa.GetUser()
    us, _ := u.ListUserOpenIDs()
    if us == nil {
        fmt.Print("获取用户列表失败")
    }
    //fmt.Println("获取到的openid列表为",us.Data)
    fmt.Println("获取到的openid列表为", us.Data.OpenIDs)
    fmt.Println("获取到的openid总数为", us.Total)

}

Guess you like

Origin blog.csdn.net/qq_42901723/article/details/134344989