93 lines
2.4 KiB
Go
93 lines
2.4 KiB
Go
package handlers
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
|
|
"github.com/spf13/viper"
|
|
)
|
|
|
|
var code2Session = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code"
|
|
|
|
type LoginRequest struct {
|
|
Code string `json:"code"`
|
|
}
|
|
|
|
// 封装code2session接口返回数据
|
|
type LoginResponse struct {
|
|
OpenId string `json:"openid"`
|
|
SessionKey string `json:"session_key"`
|
|
UnionId string `json:"unionid"`
|
|
ErrCode int `json:"errcode"`
|
|
ErrMsg string `json:"errmsg"`
|
|
}
|
|
|
|
func getLoginResponse(code string) (*LoginResponse, error) {
|
|
appid := viper.GetString("wechat.appid")
|
|
secret := viper.GetString("wechat.secret")
|
|
url := fmt.Sprintf(code2Session, appid, secret, code)
|
|
resp, err := http.Get(url)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
var loginResponse LoginResponse
|
|
if err := json.NewDecoder(resp.Body).Decode(&loginResponse); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if loginResponse.ErrCode != 0 {
|
|
return nil, fmt.Errorf("code2session error: %s", loginResponse.ErrMsg)
|
|
}
|
|
return &loginResponse, nil
|
|
}
|
|
|
|
func (h *Handler) Login(w http.ResponseWriter, r *http.Request) {
|
|
|
|
var req LoginRequest
|
|
body, err := io.ReadAll(r.Body)
|
|
if err != nil {
|
|
http.Error(w, "Failed to read request body", http.StatusBadRequest)
|
|
return
|
|
}
|
|
if err := json.Unmarshal(body, &req); err != nil {
|
|
http.Error(w, "Failed to parse request body", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
loginResponse, err := getLoginResponse(req.Code)
|
|
if err != nil {
|
|
http.Error(w, "Failed to get session key", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
// // 插入或更新用户的openid和sessionid
|
|
// query := `
|
|
// INSERT INTO users (openid, sessionid)
|
|
// VALUES ($1, $2)
|
|
// ON CONFLICT (openid) DO UPDATE SET sessionid = $2
|
|
// RETURNING id;
|
|
// `
|
|
|
|
// var ID int
|
|
// if err := h.DB.QueryRow(query, loginResponse.OpenId, loginResponse.SessionKey).Scan(&ID); err != nil {
|
|
// http.Error(w, "Failed to log in user", http.StatusInternalServerError)
|
|
// return
|
|
// }
|
|
|
|
data := map[string]interface{}{
|
|
"openid": loginResponse.OpenId,
|
|
"session_key": loginResponse.SessionKey,
|
|
}
|
|
respData, err := json.Marshal(data)
|
|
if err != nil {
|
|
http.Error(w, "Failed to marshal response data", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(http.StatusOK)
|
|
w.Write([]byte(respData))
|
|
}
|