feat: openid login
This commit is contained in:
@@ -0,0 +1,78 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"lone-services/pkg/utils"
|
||||
)
|
||||
|
||||
const phoneNumberURL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber"
|
||||
|
||||
type PhoneNumberRequest struct {
|
||||
Code string `json:"code"`
|
||||
}
|
||||
|
||||
type PhoneInfo struct {
|
||||
PhoneNumber string `json:"phoneNumber"`
|
||||
PurePhoneNumber string `json:"purePhoneNumber"`
|
||||
CountryCode string `json:"countryCode"`
|
||||
}
|
||||
|
||||
type PhoneNumberResult struct {
|
||||
ErrCode int `json:"errcode"`
|
||||
ErrMsg string `json:"errmsg"`
|
||||
PhoneInfo PhoneInfo `json:"phone_info"`
|
||||
}
|
||||
|
||||
type APIError struct {
|
||||
ErrCode int
|
||||
ErrMsg string
|
||||
}
|
||||
|
||||
func (e *APIError) Error() string {
|
||||
return fmt.Sprintf("errcode=%d errmsg=%s", e.ErrCode, e.ErrMsg)
|
||||
}
|
||||
|
||||
func (c *Client) GetPhoneNumber(accessToken, code string) (*PhoneInfo, error) {
|
||||
if accessToken == utils.StringEmpty {
|
||||
return nil, fmt.Errorf("wechat access_token empty")
|
||||
}
|
||||
if code == utils.StringEmpty {
|
||||
return nil, fmt.Errorf("wechat phone code empty")
|
||||
}
|
||||
|
||||
payload, err := json.Marshal(PhoneNumberRequest{Code: code})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
url := fmt.Sprintf("%s?access_token=%s", phoneNumberURL, accessToken)
|
||||
client := &http.Client{Timeout: 10 * time.Second}
|
||||
resp, err := client.Post(url, "application/json", bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var result PhoneNumberResult
|
||||
if err := json.Unmarshal(body, &result); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if result.ErrCode != utils.NumberZero {
|
||||
return nil, &APIError{ErrCode: result.ErrCode, ErrMsg: result.ErrMsg}
|
||||
}
|
||||
if result.PhoneInfo.PhoneNumber == utils.StringEmpty && result.PhoneInfo.PurePhoneNumber == utils.StringEmpty {
|
||||
return nil, fmt.Errorf("wechat phone number empty")
|
||||
}
|
||||
return &result.PhoneInfo, nil
|
||||
}
|
||||
Reference in New Issue
Block a user