public async Task SendingSmsMessage() { SmsClient client = InstrumentClient( new SmsClient( TestEnvironment.LiveTestConnectionString, InstrumentClientOptions(new SmsClientOptions()))); try { SmsSendResult result = await client.SendAsync( from : TestEnvironment.FromPhoneNumber, to : TestEnvironment.ToPhoneNumber, message : "Hi"); Console.WriteLine($"Sms id: {result.MessageId}"); assertHappyPath(result); } catch (RequestFailedException ex) { Console.WriteLine(ex.Message); Assert.Fail($"Unexpected error: {ex}"); } catch (Exception ex) { Assert.Fail($"Unexpected error: {ex}"); } }
//internal void send() //{ // try // { // /* 必要步骤: // * 实例化一个认证对象,入参需要传入腾讯云账户密钥对secretId,secretKey。 // * 这里采用的是从环境变量读取的方式,需要在环境变量中先设置这两个值。 // * 你也可以直接在代码中写死密钥对,但是小心不要将代码复制、上传或者分享给他人, // * 以免泄露密钥对危及你的财产安全。 // * CAM密匙查询: https://console.cloud.tencent.com/cam/capi*/ // Credential cred = new Credential // { // SecretId = "我的id", // SecretKey = "密匙" // }; // /* // Credential cred = new Credential { // SecretId = Environment.GetEnvironmentVariable("TENCENTCLOUD_SECRET_ID"), // SecretKey = Environment.GetEnvironmentVariable("TENCENTCLOUD_SECRET_KEY") // };*/ // /* 非必要步骤: // * 实例化一个客户端配置对象,可以指定超时时间等配置 */ // ClientProfile clientProfile = new ClientProfile(); // /* SDK默认用TC3-HMAC-SHA256进行签名 // * 非必要请不要修改这个字段 */ // clientProfile.SignMethod = ClientProfile.SIGN_TC3SHA256; // /* 非必要步骤 // * 实例化一个客户端配置对象,可以指定超时时间等配置 */ // HttpProfile httpProfile = new HttpProfile(); // /* SDK默认使用POST方法。 // * 如果你一定要使用GET方法,可以在这里设置。GET方法无法处理一些较大的请求 */ // httpProfile.ReqMethod = "GET"; // /* SDK有默认的超时时间,非必要请不要进行调整 // * 如有需要请在代码中查阅以获取最新的默认值 */ // httpProfile.Timeout = 10; // 请求连接超时时间,单位为秒(默认60秒) // /* SDK会自动指定域名。通常是不需要特地指定域名的,但是如果你访问的是金融区的服务 // * 则必须手动指定域名,例如sms的上海金融区域名: sms.ap-shanghai-fsi.tencentcloudapi.com */ // httpProfile.Endpoint = "sms.tencentcloudapi.com"; // // 代理服务器,当你的环境下有代理服务器时设定 // httpProfile.WebProxy = Environment.GetEnvironmentVariable("HTTPS_PROXY"); // clientProfile.HttpProfile = httpProfile; // /* 实例化要请求产品(以sms为例)的client对象 // * 第二个参数是地域信息,可以直接填写字符串ap-guangzhou,或者引用预设的常量 */ // SmsClient client = new SmsClient(cred, "ap-guangzhou", clientProfile); // /* 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数 // * 你可以直接查询SDK源码确定SendSmsRequest有哪些属性可以设置 // * 属性可能是基本类型,也可能引用了另一个数据结构 // * 推荐使用IDE进行开发,可以方便的跳转查阅各个接口和数据结构的文档说明 */ // SendSmsRequest req = new SendSmsRequest(); // /* 基本类型的设置: // * SDK采用的是指针风格指定参数,即使对于基本类型你也需要用指针来对参数赋值。 // * SDK提供对基本类型的指针引用封装函数 // * 帮助链接: // * 短信控制台: https://console.cloud.tencent.com/sms/smslist // * sms helper: https://cloud.tencent.com/document/product/382/3773 */ // req.SmsSdkAppid = "1400787878"; // /* 短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名,签名信息可登录 [短信控制台] 查看 */ // req.Sign = "雪雪雪个人技术站"; // /* 短信码号扩展号: 默认未开通,如需开通请联系 [sms helper] */ // req.ExtendCode = "x"; // /* 国际/港澳台短信 senderid: 国内短信填空,默认未开通,如需开通请联系 [sms helper] */ // req.SenderId = ""; // /* 用户的 session 内容: 可以携带用户侧 ID 等上下文信息,server 会原样返回 */ // req.SessionContext = ""; // /* 下发手机号码,采用 e.164 标准,+[国家或地区码][手机号] // * 示例如:+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号,最多不要超过200个手机号*/ // req.PhoneNumberSet = new String[] { "+8618030297576" }; // /* 模板 ID: 必须填写已审核通过的模板 ID。模板ID可登录 [短信控制台] 查看 */ // req.TemplateID = "590943"; // /* 模板参数: 若无模板参数,则设置为空*/ // req.TemplateParamSet = new String[] { "666" }; // // 通过client对象调用DescribeInstances方法发起请求。注意请求方法名与请求对象是对应的 // // 返回的resp是一个DescribeInstancesResponse类的实例,与请求对象对应 // SendSmsResponse resp = client.SendSmsSync(req); // // 输出json格式的字符串回包 // Console.WriteLine(AbstractModel.ToJsonString(resp)); // } // catch (Exception e) // { // Console.WriteLine(e.ToString()); // } // Console.Read(); //} internal void Send() { try { Credential cred = new Credential { SecretId = "AKIDKeRJuDD5i4AKVjdwvjfLkwrUqMzLdGpW", SecretKey = "avzqRlB44AONALIzJMccMp42jBMwFIzP" }; ClientProfile clientProfile = new ClientProfile(); HttpProfile httpProfile = new HttpProfile(); httpProfile.Endpoint = ("sms.tencentcloudapi.com"); clientProfile.HttpProfile = httpProfile; SmsClient client = new SmsClient(cred, "ap-beijing", clientProfile); SendSmsRequest req = new SendSmsRequest(); string strParams = "{\"PhoneNumberSet\":[\"+8618030297576\"],\"TemplateID\":\"590943\",\"Sign\":\"雪雪雪个人技术站\",\"TemplateParamSet\":[\"123\"],\"SmsSdkAppid\":\"1400358718\"}"; req = SendSmsRequest.FromJsonString <SendSmsRequest>(strParams); SendSmsResponse resp = client.SendSmsSync(req); Console.WriteLine(AbstractModel.ToJsonString(resp)); } catch (Exception e) { Console.WriteLine(e.ToString()); } Console.Read(); }
public async Task SendingSmsMessageToFakeNumber() { SmsClient client = InstrumentClient( new SmsClient( TestEnvironment.LiveTestConnectionString, InstrumentClientOptions(new SmsClientOptions()))); try { SmsSendResult result = await client.SendAsync( from : TestEnvironment.FromPhoneNumber, to : "+15550000000", message : "Hi"); Assert.AreEqual(400, result.HttpStatusCode); } catch (RequestFailedException ex) { Console.WriteLine(ex.Message); Assert.Fail($"Unexpected error: {ex}"); } catch (Exception ex) { Assert.Fail($"Unexpected error: {ex}"); } }
public virtual async Task HandleEventAsync(UserUpdatedEventData eventData) { var user = await _userManager.GetUserByIdAsync(eventData.UserId); user.Surname = eventData.PhoneNumber; await _userManager.UpdateAsync(user); await _userManager.ChangePhoneNumberAsync(user, eventData.PhoneNumber, string.Empty); try { Credential cred = new Credential { SecretId = "AKID1sZ03uwxf9Ub", SecretKey = "JEyWwAA0bxBE4jAML" }; ClientProfile clientProfile = new ClientProfile(); HttpProfile httpProfile = new HttpProfile(); httpProfile.Endpoint = ("sms.tencentcloudapi.com"); clientProfile.HttpProfile = httpProfile; SmsClient client = new SmsClient(cred, "ap-shanghai", clientProfile); SendSmsRequest req = new SendSmsRequest(); string strParams = "{\"PhoneNumberSet\":[\"+8618538705067\"],\"TemplateID\":\"186797\",\"Sign\":\"江南艺考\",\"TemplateParamSet\":[\"王彤\",\"最近学习好\",\"成绩提升很快\"],\"SmsSdkAppid\":\"1466134967\"}"; req = SendSmsRequest.FromJsonString <SendSmsRequest>(strParams); SendSmsResponse resp = client.SendSms(req).ConfigureAwait(false).GetAwaiter().GetResult();; Logger.Info(AbstractModel.ToJsonString(resp)); } catch (Exception e) { Logger.Error(e.ToString()); } }
public void get_user_info() { var smsClient = new SmsClient("**", "**"); var result = smsClient.GetUserInfo(ActionTypes.UserInfo); Console.WriteLine(result); }
/// <summary> /// 发送短信 /// </summary> /// <param name="mobile">手机号码,多个号码使用半角逗号分割</param> /// <param name="content">短信内容</param> /// <param name="sendTime">定时发送,若为null则立即发送</param> /// <returns></returns> private bool SendCommonSms(string mobile, string content, DateTime?sendTime) { if (string.IsNullOrEmpty(content)) { Alert("短信内容为空"); return(false); } SmsClient smsClient = new SmsClient(AppConfig.SmsCode, AppConfig.SmsPwd); smsClient.ServiceUrl = AppConfig.SmsServiceUrl; if (!smsClient.SendSms(mobile, content, sendTime)) { if (smsClient.Result == null) { log.Info($"发送短信失败[mobile={mobile}&content={content}&sendTime={sendTime}]:{Environment.NewLine},smsClient.Result结果为空 "); Alert("发送短信失败"); return(false); } log.Info($"发送短信失败[mobile={mobile}&content={content}&sendTime={sendTime}]:{Environment.NewLine}" + $"BatchID={smsClient.Result.BatchID}&Code={smsClient.Result.Code}&Description={smsClient.Result.Description}"); Alert(smsClient.Result.Description); return(false); } return(true); }
/// <summary> /// 发送短信通知 /// </summary> /// <param name="cellphone">手机号</param> /// <param name="templateId">模板Id</param> /// <param name="args">模板参数</param> /// <returns></returns> public static bool SendSms(string cellphone, int templateId, params string[] args) { try { using (var smsClient = new SmsClient()) { var sendResult = smsClient.SendSms( new Service.Utility.Request.SendTemplateSmsRequest { Cellphone = cellphone, TemplateId = templateId, TemplateArguments = args }); if (!sendResult.Success || sendResult.Result < 1) { _logger.Warn( $"{jobName} SmsClient => SendSmsAsync => {cellphone} {templateId} 失败。{sendResult.ErrorCode} {sendResult.ErrorMessage} {sendResult.Exception?.Message}"); return(false); } return(true); } } catch (Exception ex) { _logger.Error( $" {jobName}异常 {cellphone} {templateId},{ex.Message + ex.StackTrace} ", ex); } return(false); }
static async Task Main(string[] args) { try { //Authentication var smsClient = await SmsClient.Authenticate("{{authorization_header}}"); Console.WriteLine("Account authenticated"); PrintSeparator(); //Send an sms await SendingSms(smsClient); PrintSeparator(); //View Balance await VerifyingBalance(smsClient); PrintSeparator(); //View SMS Usage statistics await GettingStatistics(smsClient); PrintSeparator(); //View purchase history await GetPurchaseHistory(smsClient); PrintSeparator(); } catch (Exception ex) { Console.WriteLine($"Exception:{ex.Message}"); } }
//Public Method SendSMS public string SendSMS(string mobileno, string message) { if (CheckConnection()) { try { SmsClient.ServerAddress = ServerAddress; SmsClient.Port = Convert.ToInt32(ServerPort); SmsClient.HttpProxy.ProxyMode = HttpProxyMode.AutoDetect; //SmsClient.HttpProxy.Host = ProxyAddress; //SmsClient.HttpProxy.Port = Convert.ToInt32(ProxyPort); SmsClient sms = new SmsClient(Username, Password); try { SendMessageResult result = sms.SendMessage(mobileno, message); return(result.TaskId + "|" + result.MessageId); } catch (Exception ex) { return(ex.Message); } } catch (Exception ex) { return(ex.Message); } } else { return("Error"); } }
public static void Run([EventGridTrigger] EventGridEvent eventGridEvent, ILogger log) { log.LogInformation(eventGridEvent.Data.ToString()); SMSReceived smsReceived = JsonConvert.DeserializeObject <SMSReceived>(eventGridEvent.Data.ToString()); string returnMessage = string.Empty; switch (smsReceived.message) { case "Use Case 1": returnMessage = "Results for Use Case 1"; break; case "Use Case 2": returnMessage = "Results for Use Case 2"; break; default: returnMessage = "I didn't understand"; break; } SmsClient smsClient = new SmsClient(Settings.ACSConnectionString); smsClient.Send( from: new PhoneNumber(Settings.ACSPhoneNumber), to: new PhoneNumber(Settings.ConsumerPhoneNumber), message: returnMessage, new SendSmsOptions { EnableDeliveryReport = true } // optional ); }
public async static void TextMessageViaCommunicationService(IConfiguration configuration, string PhoneNumber, string Message) { string connectionString = "endpoint=https://smsforwlctest.communication.azure.com/;accesskey=ir/swruC+focwatNzk+379NVuhj0+UdlUMZ6Qa9mzi+XbNplGJPewqduDUPZwYtweeeuW3YDKwPnbfuvph46pw=="; string Key = "ir/swruC+focwatNzk+379NVuhj0+UdlUMZ6Qa9mzi+XbNplGJPewqduDUPZwYtweeeuW3YDKwPnbfuvph46pw=="; string endPoint = "https://smsforwlctest.communication.azure.com/"; SmsClient smsClient = new SmsClient(connectionString); smsClient.Send( from: new Azure.Communication.PhoneNumber("503-816-9054"), to: new Azure.Communication.PhoneNumber(PhoneNumber), message: Message, new SendSmsOptions { EnableDeliveryReport = true } // optional ); //var identityResponse = await client.CreateUserAsync(); //var identity = identityResponse.Value; //Console.WriteLine($"\nCreated an identity with ID: {identity.Id}"); //// Issue an access token with the "voip" scope for an identity //var tokenResponse = await client.IssueTokenAsync(identity, scopes: new[] { CommunicationTokenScope.VoIP }); //var token = tokenResponse.Value.Token; //var expiresOn = tokenResponse.Value.ExpiresOn; //Console.WriteLine($"\nIssued an access token with 'voip' scope that expires at {expiresOn}:"); //Console.WriteLine(token); }
protected void Send_Click(object sender, EventArgs e) { Page.Validate(); if (!Page.IsValid) { Output.Style.Add("color", "black"); Output.Text = "-"; return; } // Create the client. SmsClient client = new SmsClient(USERNAME, PASSWORD, URL); // Create new message with one recipient. TextMessage textMessage = new TextMessage(Int64.Parse(Recipient.Text), Text.Text); try { // Send the message. MessageResponse response = client.Send(textMessage, MAX_SMS_PER_MESSAGE, TEST_MESSAGE); // Print the response. Output.Style.Add("color", "black"); Output.Text = response.statusMessage; Text.Text = ""; } catch (Exception ex) { // Handle exceptions. Output.Style.Add("color", "red"); Output.Text = ex.Message; } }
/// <summary> /// Checks whether the entered settings are valid and saves them. /// </summary> void acceptButton_Click(object sender, EventArgs e) { endpointTextBox.Text = endpointTextBox.Text.Trim(); if (endpointTextBox.Text.Length == 0) { ShowError("You have to enter the queue endpoint."); endpointTextBox.Focus(); return; } if (tokenTextBox.Text.Length == 0) { ShowError("You have to enter the security token."); tokenTextBox.Focus(); return; } if (!SmsClient.Test(endpointTextBox.Text, tokenTextBox.Text)) { ShowError("The endpoint or token you have specified is invalid."); return; } Save(); DialogResult = DialogResult.OK; }
/// <summary> /// Try to retrieve a list of messages from the queue. /// </summary> /// <returns></returns> public List <Message> FetchMessages() { var client = new SmsClient(Endpoint); var messages = new List <Message>(); var data = client.Retrieve(Token); foreach (var sms in data) { var message = new Message( Guid.ToString(), sms.Number, sms.Message); if (IsMessageAllowed(message)) { if (message.Body.Length > maxLength) { if (SplitLargeMessages) { messages.AddRange(SplitMessage(message)); } } else { messages.Add(message); } } } return(messages); }
public async Task SendingSmsMessageFromFakeNumber() { SmsClient client = InstrumentClient( new SmsClient( TestEnvironment.LiveTestConnectionString, InstrumentClientOptions(new SmsClientOptions()))); try { SmsSendResult result = await client.SendAsync( from : "+15550000000", to : TestEnvironment.ToPhoneNumber, message : "Hi"); } catch (RequestFailedException ex) { Assert.IsNotEmpty(ex.Message); Assert.True(ex.Message.Contains("400")); Console.WriteLine(ex.Message); } catch (Exception ex) { Assert.Fail($"Unexpected error: {ex}"); } }
//Private Method CheckConnection private bool CheckConnection() { try { SmsClient.ServerAddress = ServerAddress; SmsClient.Port = Convert.ToInt32(ServerPort); SmsClient.HttpProxy.ProxyMode = HttpProxyMode.AutoDetect; //SmsClient.HttpProxy.Host = ProxyAddress; //SmsClient.HttpProxy.Port = Convert.ToInt32(ProxyPort); SmsClient sms = new SmsClient(Username, Password); if (sms.TestConnection()) { return(true); } else { return(false); } } catch (Exception ex) { return(false); } }
/// <summary> /// 发送短信 /// </summary> /// <param name="smsContent"></param> /// <param name="Mobile"></param> private void SendSms(string smsContent, string Mobile) { Logger.Write(Log.Log_Type.Debug, "发送SMS"); if (smsContent == null || Mobile == null) { throw new ArgumentNullException("smsContent"); } try { var s = new SmsClient(); var argsu = new SmsMessageArgs { Content = smsContent, Mobiles = Mobile, }; var result = s.SendSms(argsu); if (result == null) { throw new ArgumentNullException("发送失败,返回空数据"); } if (!result.Success) { throw new ArgumentNullException(result.Code, result.Message); } Logger.Write(Log.Log_Type.Debug, "发送SMS success"); } catch (Exception ex) { Logger.Write(Log.Log_Type.Debug, "发送sms失败"); } }
public async Task SendingSmsMessage() { SmsClient client = InstrumentClient( new SmsClient( TestEnvironment.ConnectionString, InstrumentClientOptions(new SmsClientOptions()))); #region Snippet:Azure_Communication_Sms_Tests_Troubleshooting try { #region Snippet:Azure_Communication_Sms_Tests_SendAsync SmsSendResult result = await client.SendAsync( //@@ from: "+18001230000" // Phone number acquired on your Azure Communication resource //@@ to: "+18005670000", /*@@*/ from : TestEnvironment.FromPhoneNumber, /*@@*/ to : TestEnvironment.ToPhoneNumber, message : "Hi"); Console.WriteLine($"Sms id: {result.MessageId}"); #endregion Snippet:Azure_Communication_Sms_Tests_SendAsync /*@@*/ Assert.IsFalse(string.IsNullOrWhiteSpace(result.MessageId)); /*@@*/ Assert.AreEqual(202, result.HttpStatusCode); /*@@*/ Assert.IsTrue(result.Successful); } catch (RequestFailedException ex) { Console.WriteLine(ex.Message); } #endregion Snippet:Azure_Communication_Sms_Tests_Troubleshooting catch (Exception ex) { Assert.Fail($"Unexpected error: {ex}"); } }
//Private Method CheckConnection private bool CheckConnection() { try { SmsClient.ServerAddress = ServerAddress; SmsClient.Port = Convert.ToInt32(ServerPort); SmsClient.HttpProxy.ProxyMode = HttpProxyMode.AutoDetect; //SmsClient.HttpProxy.Host = ProxyAddress; //SmsClient.HttpProxy.Port = Convert.ToInt32(ProxyPort); SmsClient sms = new SmsClient(Username, Password); if (sms.TestConnection()) { return true; } else { return false; } } catch (Exception ex) { return false; } }
//Public Method SendSMS public string SendSMS(string mobileno, string message) { if (CheckConnection()) { try { SmsClient.ServerAddress = ServerAddress; SmsClient.Port = Convert.ToInt32(ServerPort); SmsClient.HttpProxy.ProxyMode = HttpProxyMode.AutoDetect; //SmsClient.HttpProxy.Host = ProxyAddress; //SmsClient.HttpProxy.Port = Convert.ToInt32(ProxyPort); SmsClient sms = new SmsClient(Username, Password); try { SendMessageResult result = sms.SendMessage(mobileno, message); return result.TaskId + "|" + result.MessageId; } catch (Exception ex) { return ex.Message; } } catch (Exception ex) { return ex.Message; } } else { return "Error"; } }
public static int SendFailSMS(Record record) { Credential cred = new Credential { SecretId = "AKIDqZ1DBslX2NUSJvv0U4RYP0LJ4YEeEnTu", SecretKey = "PULL6aoKagW5PSFp0sUqxiDSRGpg6EBu" }; ClientProfile clientProfile = new ClientProfile(); HttpProfile httpProfile = new HttpProfile(); httpProfile.Endpoint = ("sms.tencentcloudapi.com"); clientProfile.HttpProfile = httpProfile; SmsClient client = new SmsClient(cred, "ap-nanjing", clientProfile); SendSmsRequest req = new SendSmsRequest(); req.PhoneNumberSet = new String[] { "+86" + record.phone }; req.TemplateID = "692782"; req.SmsSdkAppid = "1400410910"; req.Sign = "EVA记录"; req.TemplateParamSet = new String[] { record.name }; SendSmsResponse resp = client.SendSmsSync(req); if (resp.SendStatusSet[0].Code == "Ok") { return(1); } else { return(0); } }
public static int SendQueRenSms(Record record, InterviewTime interview) { Credential cred = new Credential { SecretId = "*******************", SecretKey = "**********************" }; ClientProfile clientProfile = new ClientProfile(); HttpProfile httpProfile = new HttpProfile(); httpProfile.Endpoint = ("sms.tencentcloudapi.com"); clientProfile.HttpProfile = httpProfile; SmsClient client = new SmsClient(cred, "ap-nanjing", clientProfile); SendSmsRequest req = new SendSmsRequest(); req.PhoneNumberSet = new String[] { "+86" + record.phone }; req.TemplateID = "724175"; req.SmsSdkAppid = "1400410910"; req.Sign = "EVA记录"; req.TemplateParamSet = new String[] { record.name, interview.Day + " " + interview.BeginTime, interview.Place + "室" }; SendSmsResponse resp = client.SendSmsSync(req); if (resp.SendStatusSet[0].Code == "Ok") { return(1); } else { return(0); } }
public async Task SendingSmsMessageToGroupWithOptions() { SmsClient client = CreateSmsClient(); try { var response = await client.SendAsync( from : TestEnvironment.FromPhoneNumber, to : new string[] { TestEnvironment.ToPhoneNumber, TestEnvironment.ToPhoneNumber }, message : "Hi", options : new SmsSendOptions(enableDeliveryReport: true) // OPTIONAL { Tag = "marketing", // custom tags }); foreach (SmsSendResult result in response.Value) { Console.WriteLine($"Sms id: {result.MessageId}"); assertHappyPath(result); } } catch (RequestFailedException ex) { Console.WriteLine(ex.Message); Assert.Fail($"Unexpected error: {ex}"); } catch (Exception ex) { Assert.Fail($"Unexpected error: {ex}"); } }
public async Task SendingAnSmsMessage() { SmsClient client = InstrumentClient( new SmsClient( TestEnvironment.ConnectionString, InstrumentClientOptions(new SmsClientOptions()))); #region Snippet:Azure_Communication_Sms_Tests_Troubleshooting try { #region Snippet:Azure_Communication_Sms_Tests_SendAsync SendSmsResponse result = await client.SendAsync( //@@ from: new PhoneNumber("+18001230000"), // Phone number acquired on your Azure Communication resource //@@ to: new PhoneNumber("+18005670000"), /*@@*/ from : new PhoneNumberIdentifier(TestEnvironment.PhoneNumber), /*@@*/ to : new PhoneNumberIdentifier(TestEnvironment.PhoneNumber), message : "Hi"); Console.WriteLine($"Sms id: {result.MessageId}"); #endregion Snippet:Azure_Communication_Sms_Tests_SendAsync /*@@*/ Assert.IsFalse(string.IsNullOrWhiteSpace(result.MessageId)); } catch (RequestFailedException ex) { Console.WriteLine(ex.Message); } #endregion Snippet:Azure_Communication_Sms_Tests_Troubleshooting catch (Exception ex) { Assert.Fail($"Unexpected error: {ex}"); } }
public async Task SendingTwoSmsMessages() { SmsClient client = CreateSmsClient(); try { SmsSendResult firstMessageResult = await client.SendAsync( from : TestEnvironment.FromPhoneNumber, to : TestEnvironment.ToPhoneNumber, message : "Hi"); SmsSendResult secondMessageResult = await client.SendAsync( from : TestEnvironment.FromPhoneNumber, to : TestEnvironment.ToPhoneNumber, message : "Hi"); Assert.AreNotEqual(firstMessageResult.MessageId, secondMessageResult.MessageId); assertHappyPath(firstMessageResult); assertHappyPath(secondMessageResult); } catch (RequestFailedException ex) { Console.WriteLine(ex.Message); Assert.Fail($"Unexpected error: {ex}"); } catch (Exception ex) { Assert.Fail($"Unexpected error: {ex}"); } }
public static async Task <bool> SubmitVerficationCodeAsync(string cellphone, string verifyCode) { if (String.IsNullOrWhiteSpace(cellphone) || String.IsNullOrWhiteSpace(verifyCode)) { return(false); } try { using (var client = new SmsClient()) { var result = await client.SubmitVerificationCodeAsync(cellphone, verifyCode); // 记录 elk 日志 Logger.Log(Level.Info, $"SubmitVerificationCodeAsync 提交短信验证码:手机号:{cellphone},验证码:{verifyCode},响应信息:{JsonConvert.SerializeObject(result)}"); if (result.Success && result.Result > 0) { return(true); } else { Logger.Log(Level.Error, "SubmitVerificationCodeAsync 提交短信验证码失败,手机号:{0},异常信息:{1}", cellphone, result.Exception?.InnerException?.Message ?? result.ErrorMessage); return(false); } } } catch (Exception ex) { Logger.Log(Level.Error, "SendVerificationCodeSmsMessageAsync 发送验证码短信异常,手机号:{0},异常信息:{1}", cellphone, ex.InnerException?.Message); return(false); } }
private void SendSms(string Mobileno, string msg) { if (Debuger.IsDebug || string.IsNullOrEmpty(msg) || string.IsNullOrEmpty(Mobileno)) { return; } try { using (SmsClient client = new SmsClient(AppConfig.SMS_UserCode, AppConfig.SMS_UserPwd)) { client.SendSms(Mobileno, msg, null); Log.Info("给手机号[" + Mobileno + "]发送短信成功"); } //TODO:接入消息中心 //messageModel model = new messageModel() //{ // Receiver = Mobileno, // msg = msg, // TemplateNo = AppConfig.SMSTemplateNo //}; //MessageCenter message = new MessageCenter(); //if (message.sendMessage(model)) //{ // return; //} } catch (Exception ex) { Log.Error(ex); } }
public ActionResult SendMessage(string phone) { try { if (string.IsNullOrEmpty(phone) || !ValidatePhone(phone)) { return(Json(new { isSuccess = false, status = EntryStatus.FormatError }, JsonRequestBehavior.AllowGet)); } var vCode = GeneraCode(); using (var client = new SmsClient()) { client.SendVerificationCode(new SendVerificationCodeRequest { Cellphone = phone, Host = Request.Url.Host, UserIp = Request.UserIp(), VerificationCode = vCode }).ThrowIfException(true); } var result = SetVcode(phone, vCode); return(Json(new { isSuccess = result }, JsonRequestBehavior.AllowGet)); } catch (Exception ex) { WebLog.LogException(ex); return(Json(new { isSuccess = false, status = EntryStatus.EntryError }, JsonRequestBehavior.AllowGet)); } }
/// <summary> /// 发送模板短信 /// </summary> /// <param name="cellphone">手机号</param> /// <param name="templateId">模板id</param> /// <param name="parameters">模板参数</param> /// <returns></returns> public static async Task <bool> SendTemplateSmsMessageAsync(string cellphone, int templateId, params object[] parameters) { if (String.IsNullOrWhiteSpace(cellphone) || templateId <= 0)//请求参数异常,手机号为空或模板id异常 { return(false); } try { using (var client = new SmsClient()) { var result = await client.SendSmsAsync(cellphone, templateId, parameters.Select(s => s.ToString()).ToArray()); // 记录 elk 日志 Logger.Log(Level.Info, $"SendTemplateSmsMessageAsync 发送模板短信:手机号:{cellphone},模板id:{templateId},参数:{String.Join(",", parameters)},响应信息:{JsonConvert.SerializeObject(result)}"); if (result.Success) { return(result.Result > 0); } else { Logger.Log(Level.Error, $"SendTemplateSmsMessageAsync 发送模板短信发生异常,手机号:{cellphone},异常信息:{result.Exception?.InnerException?.Message ?? result.ErrorMessage}"); } } } catch (Exception ex) { Logger.Log(Level.Error, $"SendTemplateSmsMessageAsync 调用发送模板短信服务异常,手机号:{cellphone},异常信息:{ex.InnerException?.Message}"); return(false); } return(false); }
/* * 获取回复 */ public void testReply(SmsClient smsClient) { //3. 设置请求参数 ReplyRequest request = new ReplyRequest(); request.RegionId = "cn-north-1"; // 设置应用ID 应用管理-文本短信-概览 页面可以查看应用ID request.AppId = "{{AppId}}"; // 设置查询日期 时间格式:2019-09-01 request.DataDate = "{{DataDate}}"; // 设置要查询的手机号列表 非必传 List <string> phoneList = new List <string>() { "13800013800" // , // "phone number" }; request.PhoneList = phoneList; //4. 执行请求 var response = smsClient.Reply(request).Result; Console.WriteLine(JsonConvert.SerializeObject(response)); Console.ReadLine(); }
/* * 获取状态报告 */ public void testStatusReport(SmsClient smsClient) { //3. 设置请求参数 StatusReportRequest request = new StatusReportRequest(); request.RegionId = "cn-north-1"; // 设置要查询的手机号列表 List <string> phoneList = new List <string>() { "13800013800" // , // "phone number" }; request.PhoneList = phoneList; // 设置序列号 // 序列号从下发接口response中获取。response.getResult().getData().getSequenceNumber(); request.SequenceNumber = "{{SequenceNumber}}"; //4. 执行请求 var response = smsClient.StatusReport(request).Result; Console.WriteLine(JsonConvert.SerializeObject(response)); Console.ReadLine(); // Result.Data.Status = 0, 成功 }
/* * 发送短信 */ public void testBatchSend(SmsClient smsClient) { //3. 设置请求参数 BatchSendRequest request = new BatchSendRequest(); request.RegionId = "cn-north-1"; // 设置模板ID 应用管理-文本短信-短信模板 页面可以查看模板ID request.TemplateId = "{{TemplateId}}"; // 设置签名ID 应用管理-文本短信-短信签名 页面可以查看签名ID request.SignId = "qm_0571ace54ebf4b1dbdb2000b4d16dd4a"; // 设置下发手机号list List <string> phoneList = new List <string>() { "13800138000" // , // "phone number" }; request.PhoneList = phoneList; // 设置模板参数,非必传,如果模板中包含变量请填写对应参数,否则变量信息将不做替换 List <string> param = new List <string>() { "123456" }; request.Params = param; //4. 执行请求 var response = smsClient.BatchSend(request).Result; Console.WriteLine(JsonConvert.SerializeObject(response)); Console.ReadLine(); }
/// <summary> /// 发短信 /// </summary> /// <param name="mobile"></param> /// <param name="newCode"></param> private void SendSms(string[] mobile, string newCode) { var sms = new SmsClient(); //string message = "您的验证码是:{0}。请不要把验证码泄露给其他人。"; string message = new UserMessageSmsService().QueryByID(1).Content; message = message.Replace("{0}", newCode); var smsModel = new UserMessageSmsService().QueryByID(1); sms.SmsSend(mobile, message, "1"); }
public static void SendMessageAsync(string AccountUsername, string AccountPassword, string mobileNo, string message, DateTime scheduleTime) { var smsClient = new SmsClient(AccountUsername, AccountPassword); var smsLog = new SmsLog { UserId = Current.User.Id, MobileNo = mobileNo, Message = message, SentTime = DateTime.Now, SmsStatus = SmsStatus.Sending, MessageId = "", TaskId = "", ErrorMsg = "" }; smsLog.Id = (int)Current.DB.SmsLogs.Insert(smsLog); Task.Factory.StartNew(() => { try { SendMessageResult result; if (scheduleTime == DateTime.MinValue) { result = smsClient.SendMessage(mobileNo, message); } else { result = smsClient.SendMessage(mobileNo, message, scheduleTime); } Current.DB.Execute(@"update SmsLogs set SmsStatus=@SmsStatus, MessageId=@MessageId, TaskId=@TaskId where Id = @id", new { SmsStatus = (int)SmsStatus.Success, MessageId = result.MessageId, TaskId = result.TaskId, id = smsLog.Id }); } catch (GatewayException ge) { Current.DB.Execute(@"update SmsLogs set SmsStatus=@SmsStatus, ErrorMsg=@ErrorMsg where Id = @id", new { SmsStatus = (int)SmsStatus.Error, ErrorMsg = ge.Message, id = smsLog.Id }); } catch (Exception ex) { Current.DB.Execute(@"update SmsLogs set SmsStatus=@SmsStatus, ErrorMsg=@ErrorMsg where Id = @id", new { SmsStatus = (int)SmsStatus.Error, ErrorMsg = ex.Message, id = smsLog.Id }); } }); }
public void send_sms() { var smsClient = new SmsClient("*", "*"); var result = smsClient.Send(ActionTypes.SmsToConcat, "Test mesaj", new List<string> { "*" }, "*"); Console.WriteLine(result); }