init: 1.0.0
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
package twilio
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/perfect-panel/ppanel-server/pkg/logger"
|
||||
"github.com/perfect-panel/ppanel-server/pkg/templatex"
|
||||
"github.com/twilio/twilio-go"
|
||||
twilioApi "github.com/twilio/twilio-go/rest/api/v2010"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Access string `json:"access"`
|
||||
Secret string `json:"secret"`
|
||||
PhoneNumber string `json:"phone_number"`
|
||||
Template string `json:"template"`
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
config Config
|
||||
client *twilio.RestClient
|
||||
}
|
||||
|
||||
func NewClient(config Config) *Client {
|
||||
client := twilio.NewRestClientWithParams(twilio.ClientParams{
|
||||
Username: config.Access,
|
||||
Password: config.Secret,
|
||||
})
|
||||
return &Client{
|
||||
config: config,
|
||||
client: client,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) SendCode(area, mobile, code string) error {
|
||||
params := &twilioApi.CreateMessageParams{}
|
||||
params.SetTo(fmt.Sprintf("+%s%s", area, mobile))
|
||||
params.SetFrom(c.config.PhoneNumber)
|
||||
text, err := templatex.RenderToString(c.config.Template, map[string]interface{}{
|
||||
"code": code,
|
||||
})
|
||||
if err != nil {
|
||||
logger.Error("twilio send code render template error", logger.Field("error", err.Error()), logger.Field("template", c.config.Template), logger.Field("code", code))
|
||||
}
|
||||
params.SetBody(text)
|
||||
resp, err := c.client.Api.CreateMessage(params)
|
||||
if err != nil {
|
||||
logger.Error("twilio send code error", logger.Field("error", err.Error()), logger.Field("params", params))
|
||||
return fmt.Errorf("twilio send code error: %s", err.Error())
|
||||
}
|
||||
if resp.ErrorCode != nil {
|
||||
logger.Error("twilio send code error", logger.Field("error_code", *resp.ErrorCode), logger.Field("error_message", *resp.ErrorMessage))
|
||||
return fmt.Errorf("twilio send code error: %s", *resp.ErrorMessage)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) GetSendCodeContent(code string) string {
|
||||
text, _ := templatex.RenderToString(c.config.Template, map[string]interface{}{
|
||||
"code": code,
|
||||
})
|
||||
return text
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package twilio
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestClient_SendCode(t *testing.T) {
|
||||
t.Skipf("Skip TestClient_SendCode test")
|
||||
client := NewClient(Config{
|
||||
Access: "", Secret: "", PhoneNumber: "", Template: "",
|
||||
})
|
||||
err := client.SendCode("", "", "123456")
|
||||
if err != nil {
|
||||
t.Errorf("SendCode() error = %v", err.Error())
|
||||
return
|
||||
}
|
||||
t.Logf("SendCode() success")
|
||||
}
|
||||
Reference in New Issue
Block a user