httplib_usercenter_service.go 3.0 KB
package service_gateway

import (
	"bytes"
	"crypto/sha1"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"time"

	"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/constant"
)

type UCenterCommonMsg struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
}

func (msg UCenterCommonMsg) IsOK() error {
	if msg.Code != 0 {
		return fmt.Errorf("统一用户中心响应数据异常,code:%d,msg:%s", msg.Code, msg.Msg)
	}
	return nil
}

type MmmUserCenterServiceGateway struct {
	baseURL string
}

func NewMmmUserCenterServiceGateway() *MmmUserCenterServiceGateway {
	return &MmmUserCenterServiceGateway{
		baseURL: constant.UCENTER_HOST,
	}
}

func (gateway MmmUserCenterServiceGateway) buildHeader() http.Header {
	var h = http.Header{}
	nowTime := fmt.Sprint(time.Now().Unix())
	str := fmt.Sprintf("%s%s%s", nowTime, constant.UCENTER_SECRET, constant.UCENTER_CHECK_ALT)
	bt := sha1.Sum([]byte(str))
	checksum := fmt.Sprintf("%x", bt)
	h.Set("Content-Type", "application/json")
	h.Set("appKey", constant.UCENTER_APP_KEY)
	h.Set("nonce", "")
	h.Set("curTime", nowTime)
	h.Set("checkSum", checksum)
	h.Set("Accept", "application/json")
	return h
}

func (gateway MmmUserCenterServiceGateway) httpDo(reqURL string, mathod string, bodyData interface{}) ([]byte, error) {
	httpclient := http.Client{
		Timeout: 60 * time.Second, //请求超时时间60秒
	}
	bt := &bytes.Buffer{}
	if bodyData != nil {
		enc := json.NewEncoder(bt)
		enc.Encode(bodyData)
	}
	req, err := http.NewRequest(mathod, reqURL, bt)
	if err != nil {
		return nil, err
	}
	req.Header = gateway.buildHeader()
	resp, err := httpclient.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	return body, nil
}

type ResponseLogin struct {
	UCenterCommonMsg
	Data struct {
		Id              int64  `json:"id"` //统一用户中心的id,对应本系统中users表的open_id
		Phone           string `json:"phone"`
		NickName        string `json:"nickname"`        //昵称
		Avatar          string `json:"avatar"`          //头像
		Imtoken         string `json:"imtoken"`         //网易云imtoken
		Accid           int64  `json:"accid"`           //网易云id
		CustomerAccount int64  `json:"customerAccount"` //客服id
		CompanyId       int64  `json:"companyId"`       //总后台的公司id
		Muid            int64  `json:"muid"`            //企业平台的用户id,对应本系统中users表的id
	} `json:"data"`
}

//RequestUCenterLoginBySecret 使用密钥方式登录统一用户中心
func (gateway MmmUserCenterServiceGateway) RequestUCenterLoginBySecret(secret string) (*ResponseLogin, error) {
	param := map[string]interface{}{
		"type":   3,                       //登录方式 固定值
		"secret": url.QueryEscape(secret), //必要的转换
	}
	url := constant.UCENTER_HOST + "/auth/serverLogin"
	byteData, err := gateway.httpDo(url, "post", param)
	if err != nil {
		return nil, err
	}
	respData := &ResponseLogin{}
	err = json.Unmarshal(byteData, respData)
	return respData, err
}