master v1.0.0
kanade 4 years ago
commit 7047ef642d

@ -0,0 +1 @@
# 微信sdk工具

@ -0,0 +1,3 @@
module git.oa00.com/go/wechat
go 1.16

@ -0,0 +1,37 @@
package wechat
import (
"io"
"net/http"
"strings"
)
const (
post = "POST"
get = "GET"
)
var client = &http.Client{}
// @Title 请求
func request(method, url, data string, headers ...map[string]string) ([]byte, error) {
reqest, err := http.NewRequest(method, url, strings.NewReader(data))
if err != nil {
return nil, err
}
if len(headers) > 0 {
for key, value := range headers[0] {
reqest.Header.Add(key, value)
}
}
response, err := client.Do(reqest)
if err != nil {
return nil, err
}
defer response.Body.Close()
result, err := io.ReadAll(response.Body)
if err != nil {
return nil, err
}
return result, nil
}

@ -0,0 +1,75 @@
package wechat
import (
"encoding/json"
"fmt"
)
var Wechat = &wechat{}
type wechat struct {
appid string
secret string
}
type AuthAccessToken struct {
AccessToken string `json:"access_token"`
ExpiresIn int64 `json:"expires_in"`
Openid string `json:"openid"`
RefreshToken string `json:"refresh_token"`
Scope string `json:"scope"`
}
// InitWechat @Title 初始化
func InitWechat(appid, secret string) *wechat {
Wechat.appid = appid
Wechat.secret = secret
return Wechat
}
// GetOpenId @Title 获取openId
func (w *wechat) GetOpenId(code string) string {
accessToken, err := w.GetAccessToken(code)
if err != nil {
return ""
}
return accessToken.Openid
}
// GetAccessToken @Title 获取微信验证结构体
func (w *wechat) GetAccessToken(code string) (*AuthAccessToken, error) {
res, err := request(get, fmt.Sprintf("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%v&secret=%v&code=%v&grant_type=authorization_code", w.appid, w.secret, code), "")
if err != nil {
return nil, err
}
result := AuthAccessToken{}
if err := json.Unmarshal(res, &result); err != nil {
return nil, err
}
return &result, nil
}
type UserInfo struct {
City string `json:"city"`
Country string `json:"country"`
Headimgurl string `json:"headimgurl"`
Nickname string `json:"nickname"`
Openid string `json:"openid"`
Privilege []string `json:"privilege"`
Province string `json:"province"`
Sex uint `json:"sex"`
Unionid string `json:"unionid"`
}
// GetUserInfo @Title 获取微信登录会员信息
func (w *wechat) GetUserInfo(accessToken, openId string) (*UserInfo, error) {
res, err := request(get, fmt.Sprintf("https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN", accessToken, openId), "")
if err != nil {
return nil, err
}
result := UserInfo{}
if err := json.Unmarshal(res, &result); err != nil {
return nil, err
}
return &result, nil
}
Loading…
Cancel
Save