From e2def3228e6c614f9963b3858cd8f735b98cd317 Mon Sep 17 00:00:00 2001 From: listen <494177603@qq.com> Date: Wed, 7 Jul 2021 14:18:38 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8A=A0=E5=85=A5=E5=85=AC=E4=BC=97=E5=8F=B7?= =?UTF-8?q?=E8=8E=B7=E5=8F=96openid=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- common.go | 36 ++++++++++++++++++++ mp_open_id.client.go | 80 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 116 insertions(+) create mode 100644 mp_open_id.client.go diff --git a/common.go b/common.go index 3cc9cf5..72df163 100644 --- a/common.go +++ b/common.go @@ -67,6 +67,42 @@ type MiniAppOpenidRes struct { WxApiRes } +/** + * 获取公众号openid返回参数 + */ +type MpOpenidRes struct { + AccessToken string + ExpiresIn string + RefreshToken string + Openid string + Scope string +} + +/** + * 获取公众号用户信息请求参数 + */ +type MpUserInfoReq struct { + AccessToken string + Openid string + Lang string +} + +/** + * 根据用户access_token换取用户信息返回参数 + */ +type MpUserInfoRes struct { + Openid string + Nickname string + Sex string + Province string + City string + Country string + Headimgurl string + Privilege string + Unionid string +} + + func rpc_server_conn(url ...string) (*WeixinRpcServiceClient, error) { var wx_rpc_url string = "127.0.0.1:7969" diff --git a/mp_open_id.client.go b/mp_open_id.client.go new file mode 100644 index 0000000..ee5bc3e --- /dev/null +++ b/mp_open_id.client.go @@ -0,0 +1,80 @@ +package weixinrpc + +import ( + "encoding/json" + "log" + "strconv" + "time" + + "git.tetele.net/tgo/crypter" + + "github.com/golang/protobuf/proto" +) + +func GetMpOpenId(appid, secret, js_code string, url ...string) (*MpOpenidRes, error) { + + conn, err := rpc_server_conn(url...) + if err != nil { + return nil, err + } + defer conn.Close() + + data := MiniAppOpenidReq{} + data.Appid = appid + data.Secret = secret + data.JsCode = js_code + + data_json, err := json.Marshal(data) + if err != nil { + return nil, err + } + + encryData := crypter.DesEn(string(data_json), DES_KEY) + + now_int64 := time.Now().Unix() + + now := strconv.FormatInt(now_int64, 10) + + sign := Sign(encryData, now) + + req := &Request{ + proto.String(encryData), + proto.String(now), + proto.String(sign), + nil} + + res := &Response{} + + err = conn.GetMiniAppOpenid(req, res) + + if err != nil { + return nil, err + } + + return HandleMpOpenid(res) + +} + +/** + * 处理返回结果 + */ +func HandleMpOpenid(res *Response) (*MpOpenidRes, error) { + + //解密 + res_data_de, err := GetOrgData(res) + + if err != nil { + return nil, err + } + + var res_arr MpOpenidRes + + err = json.Unmarshal([]byte(res_data_de), &res_arr) + + if err != nil { + log.Println(err, res_data_de) + return nil, err + } + + return &res_arr, nil +}