55 "encoding/json"
66 "io/ioutil"
77 "net/http"
8- "strconv"
98)
109
1110const arcaptchaApi = "https://arcaptcha.ir/2/siteverify"
@@ -15,55 +14,58 @@ type Website struct {
1514 SecretKey string
1615}
1716
17+ type verifyReq struct {
18+ SiteKey string `json:"site_key"`
19+ SecretKey string `json:"secret_key"`
20+ ChallengeID string `json:"challenge_id"`
21+ }
22+
23+ type VerifyResp struct {
24+ Success bool `json:"success"`
25+ ErrorCodes []string `json:"error-codes"`
26+ }
27+
1828func NewWebsite (siteKey , secretKey string ) * Website {
1929 return & Website {
2030 SiteKey : siteKey ,
2131 SecretKey : secretKey ,
2232 }
2333}
2434
25- func (w * Website ) ValidateCaptcha (challengeID string ) (success bool , err error ) {
26-
27- data := & verifyCaptchaRequest {
35+ func (w * Website ) Verify (token string ) (VerifyResp , error ) {
36+ data := & verifyReq {
2837 SiteKey : w .SiteKey ,
2938 SecretKey : w .SecretKey ,
30- ChallengeID : challengeID ,
39+ ChallengeID : token ,
3140 }
41+ var resp VerifyResp
42+ err := sendRequest (http .MethodPost , arcaptchaApi , data , & resp )
43+ return resp , err
44+ }
45+
46+ func sendRequest (method , url string , data interface {}, resp interface {}) error {
3247 bin , err := json .Marshal (data )
3348 if err != nil {
34- return
49+ return err
3550 }
36-
37- req , err := http .NewRequest (
38- http .MethodPost ,
39- arcaptchaApi ,
40- bytes .NewBuffer (bin ),
41- )
51+ req , err := http .NewRequest (method , url , bytes .NewBuffer (bin ))
4252 if err != nil {
43- return
53+ return err
4454 }
45-
4655 req .Header .Add ("Content-Type" , "application/json" )
47- req .Header .Add ("Content-Length" , strconv .Itoa (len (string (bin ))))
48-
4956 res , err := http .DefaultClient .Do (req )
5057 if err != nil {
51- return
58+ return err
5259 }
5360 defer func () {
5461 _ = res .Body .Close ()
5562 }()
56-
5763 bin , err = ioutil .ReadAll (res .Body )
5864 if err != nil {
59- return
65+ return err
6066 }
61-
62- var response VerifyCaptchaResponse
63- if err = json .Unmarshal (bin , & response ); err != nil {
64- return
67+ if err = json .Unmarshal (bin , resp ); err != nil {
68+ return err
6569 }
66-
67- success = response .Success
68- return
70+ return nil
6971}
0 commit comments