Updated on 2024-07-03 GMT+08:00
Go
Example |
|
---|---|
Environment |
go1.17.1. Install the Go 211.7628.1 plug-in on IntelliJ IDEA (2021.1.3 version). |
- Sending SMSs shows an example of sending group SMSs with a single template. Sending SMSs in batches shows an example of sending group SMSs with multiple templates.
- The examples described in this document may involve the use of personal data. You are advised to comply with relevant laws and regulations and take measures to ensure that personal data is fully protected.
- The examples described in this document are for demonstration purposes only. Commercial use of the examples is prohibited.
- Information in this document is for your reference only. It does not constitute any offer or commitment.
Download required SDKs and demos for Go. Replace the content of the demo.go file with the following code example.
Modify the content of the go.mod file at the first layer as follows:
1 2 3 4 5 6 7 |
module huaweicloud.com/apig/go/signer require huaweicloud.com/apig/signer v0.0.0 replace huaweicloud.com/apig/signer v0.0.0 => ./core go 1.12 |
Example of Sending SMSs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 |
package main import ( "bytes" "crypto/tls" "fmt" core "huaweicloud.com/apig/signer" "io/ioutil" "net/http" "net/url" ) func main() { // Mandatory. The values here are example values only. Obtain the actual values based on Development Preparation. appInfo := core.Signer{ // Hard-coded or plaintext appKey/appSecret is risky. For security, encrypt your appKey/appSecret and store them in the configuration file or environment variables. Key: "c8RWg3ggEcyd4D3p94bf3Y7x1Ile", // App Key Secret: "q4Ii87Bh************80SfD7Al", //App Secret } apiAddress := "https://smsapi.ap-southeast-1.myhuaweicloud.com:443/sms/batchSendSms/v1" // Application access address (obtain it from the Application Management page on the console) and API access URI. sender := "csms12345678" // Channel number for Chinese mainland SMS or international SMS templateId := "8ff55eac1d0b478ab3c06c3c6a492300" // Template ID // Mandatory for Chinese mainland SMS. This parameter is valid and mandatory when Template Type corresponding to templateId is Universal template. The signature name must be approved and be the same type as the template. // This parameter is not required for international SMS. signature := "Huawei Cloud SMS test" // Signature // Mandatory. Global number format (including the country code), for example, +86151****6789. Use commas (,) to separate multiple numbers. receiver := "+86151****6789" // Recipient numbers // Optional. Address for receiving SMS status reports. The domain name is recommended. If this parameter is set to an empty value or left unspecified, customers do not receive status reports. statusCallBack := "" /* * Optional. If a non-variable template is used, assign an empty value to this parameter, for example, string templateParas = ""; * Example of a single-variable template: If the template content is "Your verification code is ${NUM_6}", templateParas can be set to '["369751"]'. * Example of a dual-variable template: If the template content is "You have ${NUM_2} delivered to ${TXT_20}", templateParas can be set to '["3","main gate of People's Park"]'. * To view more information, choose Service Overview > Template and Variable Specifications. */ templateParas := "[\"369751\"]" // Template variable. The following uses a single-variable verification code SMS message as an example. The customer needs to generate a 6-digit verification code and define it as a character string to prevent the loss of first digits 0 (for example, 002569 is changed to 2569). body := buildRequestBody(sender, receiver, templateId, templateParas, statusCallBack, signature) resp, err := post(apiAddress, []byte(body), appInfo) if err != nil { return } fmt.Println(resp) } /** * sender, receiver, and templateId cannot be empty. */ func buildRequestBody(sender, receiver, templateId, templateParas, statusCallBack, signature string) string { param := "from=" + url.QueryEscape(sender) + "&to=" + url.QueryEscape(receiver) + "&templateId=" + url.QueryEscape(templateId) if templateParas != "" { param += "&templateParas=" + url.QueryEscape(templateParas) } if statusCallBack != "" { param += "&statusCallback=" + url.QueryEscape(statusCallBack) } if signature != "" { param += "&signature=" + url.QueryEscape(signature) } return param } func post(url string, param []byte, appInfo core.Signer) (string, error) { if param == nil || appInfo == (core.Signer{}) { return "", nil } // In the code example, certificate verification is disabled. You need to enable certificate verification in the commercial environment. tr := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } client := &http.Client{Transport: tr} req, err := http.NewRequest("POST", url, bytes.NewBuffer(param)) if err != nil { return "", err } // Add the content format to the request. The header is fixed. req.Header.Add("Content-Type", "application/x-www-form-urlencoded") // Sign the request using the HMAC algorithm and add the signing result to the Authorization header. appInfo.Sign(req) fmt.Println(req.Header) // Send an SMS request. resp, err := client.Do(req) if err != nil { fmt.Println(err) } // Response to obtaining the SMS message defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { return "", err } return string(body), nil } |
Example of Sending SMSs in Batches
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 |
package main import ( "bytes" "crypto/tls" "encoding/json" "fmt" core "huaweicloud.com/apig/signer" "io/ioutil" "net/http" ) func main() { // Mandatory. The values here are example values only. Obtain the actual values based on Development Preparation. apiAddress := "https://smsapi.ap-southeast-1.myhuaweicloud.com:443/sms/batchSendDiffSms/v1" // Application access address (obtain it from the Application Management page on the console) and API access URI. // Hard-coded or plaintext appKey/appSecret is risky. For security, encrypt your appKey/appSecret and store them in the configuration file or environment variables. appKey := "c8RWg3ggEcyd4D3p94bf3Y7x1Ile" // APP_Key appSecret := "q4Ii87Bh************80SfD7Al" //APP_Secret sender := "csms12345678" // Channel number for Chinese mainland SMS or international SMS templateId1 := "8ff55eac1d0b478ab3c06c3c6a492300" // Template ID1 templateId2 := "8ff55eac1d0b478ab3c06c3c6a492300" // Template ID 2 // Mandatory for Chinese mainland SMS. This parameter is valid and mandatory when Template Type corresponding to templateId is Universal template. The signature name must be approved and be the same type as the template. // This parameter is not required for international SMS. signature1 := "Huawei Cloud SMS test" // Signature 1 signature2 := "Huawei Cloud SMS test" // Signature 2 // Mandatory. Global number format (including the country code), for example, +8615123456789. Use commas (,) to separate multiple numbers. receiver1 := []string{"+86151****6789", "+86152****7890"} // Recipient number of template 1 receiver2 := []string{"+86151****6789", "+86152****7890"} // Recipient number of template 2 // Optional. Address for receiving SMS status reports. The domain name is recommended. If this parameter is set to an empty value or left unspecified, customers do not receive status reports. statusCallBack := "" /** * Optional. If a non-variable template is used, assign an empty value to this parameter, for example, templateParas := []string{}. * Example of a single-variable template: If the template content is "Your verification code is ${NUM_6}", templateParas can be set to []string{"369751"}. * Example of a dual-variable template: If the template content is "You have ${NUM_2} delivered to ${TXT_20}", templateParas can be set to []string{"3","main gate of People's Park"}. * ${DATE}${TIME} cannot be empty. You can use spaces or dots (.) to replace the empty value of ${TXT_20} and use 0 to replace the empty value of ${NUM_6}. * To view more information, choose Service Overview > Template and Variable Specifications. */ templateParas1 := []string{"123456"} // Template 1 variable. The following uses a single-variable verification code SMS message as an example. The customer needs to generate a 6-digit verification code and define it as a character string to prevent the loss of first digits 0 (for example, 002569 is changed to 2569). templateParas2 := []string{"234567"} // Template 2 variable. The following uses a single-variable verification code SMS message as an example. The customer needs to generate a 6-digit verification code and define it as a character string to prevent the loss of first digits 0 (for example, 002569 is changed to 2569). item1 := initDiffSms(receiver1, templateId1, templateParas1, signature1) item2 := initDiffSms(receiver2, templateId2, templateParas2, signature2) item := []map[string]interface{}{item1, item2} body := buildRequestBody(sender, item, statusCallBack) appInfo := core.Signer{ Key: appKey, // App Key Secret: appSecret, // App Secret } resp, err := post(apiAddress, []byte(body), appInfo) if err != nil { return } fmt.Println(resp) } func buildRequestBody(sender string, item []map[string]interface{}, statusCallBack string) []byte { body := make(map[string]interface{}) body["smsContent"] = item body["from"] = sender if statusCallBack != "" { body["statusCallback"] = statusCallBack } res, _ := json.Marshal(body) return res } func initDiffSms(reveiver []string, templateId string, templateParas []string, signature string) map[string]interface{} { diffSms := make(map[string]interface{}) diffSms["to"] = reveiver diffSms["templateId"] = templateId if templateParas != nil && len(templateParas) > 0 { diffSms["templateParas"] = templateParas } if signature != "" { diffSms["signature"] = signature } return diffSms } func post(url string, param []byte, appInfo core.Signer) (string, error) { if param == nil || appInfo == (core.Signer{}) { return "", nil } // In the code example, certificate verification is disabled. You need to enable certificate verification in the commercial environment. tr := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } client := &http.Client{Transport: tr} req, err := http.NewRequest("POST", url, bytes.NewBuffer(param)) if err != nil { return "", err } // Add the content format to the request. The header is fixed. req.Header.Add("Content-Type", "application/json") // Sign the request using the HMAC algorithm and add the signature to the Authorization header. appInfo.Sign(req) fmt.Println(req.Header) // Send an SMS request. resp, err := client.Do(req) if err != nil { fmt.Println(err) } // Receive the SMS response. defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { return "", err } return string(body), nil } |
Receiving Status Reports
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
package main import ( "fmt" "net/url" "strings" ) func main() { // Data example (urlencode) of the status report reported by the SMS platform //success_body := "sequence=1&total=1&updateTime=2018-10-31T08%3A43%3A41Z&source=2&smsMsgId=2ea20735-f856-4376-afbf-570bd70a46ee_11840135&status=DELIVRD"; failed_body := "orgCode=E200027&sequence=1&total=1&updateTime=2018-10-31T08%3A43%3A41Z&source=2&smsMsgId=2ea20735-f856-4376-afbf-570bd70a46ee_11840135&status=RTE_ERR"; //onSmsStatusReport(success_body); onSmsStatusReport(failed_body); } func onSmsStatusReport(data string) { ss, _ := url.QueryUnescape(data) params := strings.Split(ss, "&") keyValues := make(map[string]string) for i := range params { temp := strings.Split(params[i],"=") keyValues[temp[0]] = temp[1]; } /** * Example: Parsing status is used as an example. * * 'smsMsgId': Unique ID of an SMS * 'total': Number of SMS segments * 'sequence': Sequence number of an SMS after splitting * 'source': Status report source * 'updateTime': Resource update time * 'status': Enumeration values of the status report * 'orgCode': Status code */ status := keyValues["status"]; if status == "DELIVRD" { fmt.Println("Send sms success. smsMsgId: " + keyValues["smsMsgId"]) } else { fmt.Println("Send sms failed. smsMsgId: " + keyValues["smsMsgId"]) fmt.Println("Failed status: " + keyValues["status"]) fmt.Println("Failed orgCode: " + keyValues["orgCode"]) } } |
Parent topic: AK/SK Authentication (Recommended)
Feedback
Was this page helpful?
Provide feedbackThank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
The system is busy. Please try again later.
For any further questions, feel free to contact us through the chatbot.
Chatbot