gosdk/erp/staff_user.go

113 lines
2.4 KiB
Go

package erp
import (
"errors"
"fmt"
"git.u8t.cn/open/goutil"
"github.com/tidwall/gjson"
)
const (
LoginTypePassword = "password"
LoginTypeVerify = "verify"
)
type StaffCode struct {
Timestamp string `json:"timestamp"`
}
type LoginReq struct {
Type string `json:"type"`
Username string `json:"username"`
Password string `json:"password"`
Timestamp string `json:"timestamp"`
}
type LoginRsp struct {
Username string `json:"username"`
Realname string `json:"realname"`
Phone string `json:"phone"`
}
type ChangePasswordReq struct {
Username string `json:"username"`
OldPassword string `json:"old_password"`
NewPassword string `json:"new_password"`
}
type StaffUser struct {
Erp
}
func NewStaffUser(baseUrl, token string) *StaffUser {
return &StaffUser{
Erp: Erp{
baseUrl: baseUrl,
token: token,
},
}
}
func (e *StaffUser) SendCode(username, scene string) (*StaffCode, error) {
var reqBody string
reqBody = fmt.Sprintf(`{"username":"%s","scene":"%s"}`, username, scene)
reqUrl := e.GetBaseUrl() + "/ext/staff/user/code"
body, err := goutil.HttpPost(reqUrl, e.GetHeader(), []byte(reqBody))
if err != nil {
return nil, err
}
g := gjson.ParseBytes(body)
if g.Get("code").Int() != 0 {
return nil, errors.New(string(body))
}
r := new(StaffCode)
r.Timestamp = g.Get("data.timestamp").String()
return r, nil
}
func (e *StaffUser) Login(req *LoginReq) (*LoginRsp, error) {
var reqBody string
reqBody = fmt.Sprintf(`{"username":"%s","password":"%s", "timestamp":"%s","type":"%s"}`,
req.Username, req.Password, req.Timestamp, req.Type)
reqUrl := e.GetBaseUrl() + "/ext/staff/user/login"
body, err := goutil.HttpPost(reqUrl, e.GetHeader(), []byte(reqBody))
if err != nil {
return nil, err
}
g := gjson.ParseBytes(body)
if g.Get("code").Int() != 0 {
return nil, errors.New(string(body))
}
r := new(LoginRsp)
r.Realname = g.Get("data.realname").String()
r.Username = g.Get("data.username").String()
r.Phone = g.Get("data.phone").String()
return r, nil
}
func (e *StaffUser) ChangePassword(req *ChangePasswordReq) error {
var reqBody string
reqBody = goutil.EncodeJSON(req)
reqUrl := e.GetBaseUrl() + "/ext/staff/user/password"
body, err := goutil.HttpPost(reqUrl, e.GetHeader(), []byte(reqBody))
if err != nil {
return err
}
g := gjson.ParseBytes(body)
if g.Get("code").Int() != 0 {
return errors.New(g.Get("message").String())
}
return nil
}