/// <summary>
        /// 申请验证码
        /// </summary>
        /// <param name="phone"></param>
        /// <returns>开发阶段返回 { phone = xxxx, sentCode = xxxx }</returns>
        public IHttpActionResult Post([FromBody] string phone)
        {
            //1. Generate Verifycode and saved to DB
            //2. Sendout verifycode via SMS provider
            var code    = GenerateRandomNumber(6);
            var message = "【有序科技】您的注册验证码为:" + code + "。请在5分钟内输入";
            var sms     = new SMSSendRequest()
            {
                CreatedOn = DateTime.Now, Message = message, VerifyCode = code, Phone = phone, ValidUntil = DateTime.Now.AddMinutes(5), LastUpdatedOn = DateTime.Now, Status = SMSSendRequest.RequestStatus.Created
            };

            smsRepository.Add(sms);
            unitOfWork.Commit();
            var serviceResult = SmsServiceProvider.SendSms(phone, message);

            if (!serviceResult)
            {
                sms.LastUpdatedOn = DateTime.Now;
                sms.Status        = SMSSendRequest.RequestStatus.Send;
                smsRepository.Update(sms);
                unitOfWork.Commit();
                return(InternalServerError(new Exception("短信发送服务失败")));
            }
            else
            {
                sms.LastUpdatedOn = DateTime.Now;
                sms.Status        = SMSSendRequest.RequestStatus.Send;
                smsRepository.Update(sms);
                unitOfWork.Commit();
#if DEBUG
                return(Ok(new { phone = phone, sentCode = code }));
#endif
                return(Ok());
            }
        }
Exemplo n.º 2
0
        private static void SendSMS(SMSSendRequest smsRequest)
        {
            // Setup a REST client object using the message send URL with our API Space incorporated
            var client  = new RestClient(string.Format("https://api.comapi.com/apispaces/{0}/messages", APISPACE));
            var request = new RestRequest(Method.POST);

            request.AddHeader("cache-control", "no-cache");
            request.AddHeader("content-type", "application/json");
            request.AddHeader("accept", "application/json");
            request.AddHeader("authorization", "Bearer " + TOKEN); // Add the security token

            // Serialise our SMS request object to JSON for submission
            string requestJson = JsonConvert.SerializeObject(smsRequest);

            request.AddParameter("application/json", requestJson, ParameterType.RequestBody);

            // Make the web service call
            IRestResponse response = client.Execute(request);

            if (response.StatusCode != System.Net.HttpStatusCode.Created)
            {
                // Something went wrong.
                throw new InvalidOperationException(string.Format("Call to Comapi failed with status code ({0}), and body: {1}", response.StatusCode, response.Content));
            }
            else
            {
                // Sucess output the response body
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine(FormatJson(response.Content));
                Console.ForegroundColor = ConsoleColor.White;
            }
        }
    //////////////////
    // Private methods
    private static void SendSMS(SMSSendRequest smsRequest)
    {
        // Setup a REST client object using the message send URL with our API Space incorporated
        var client  = new RestClient(string.Format("https://api.comapi.com/apispaces/{0}/messages", APISPACE));
        var request = new RestRequest(Method.POST);

        request.AddHeader("cache-control", "no-cache");
        request.AddHeader("content-type", "application/json");
        request.AddHeader("accept", "application/json");
        request.AddHeader("authorization", "Bearer " + TOKEN); // Add the security token

        // Serialise our SMS request object to JSON for submission
        string requestJson = JsonConvert.SerializeObject(smsRequest, Formatting.None, new JsonSerializerSettings {
            NullValueHandling = NullValueHandling.Ignore
        });

        request.AddParameter("application/json", requestJson, ParameterType.RequestBody);

        // Make the web service call
        IRestResponse response = client.Execute(request);

        if (response.StatusCode != System.Net.HttpStatusCode.Created | response.ErrorException != null)
        {
            // Something went wrong.
            if (response.ErrorException != null)
            {
                throw new InvalidOperationException(string.Format("Call to Comapi failed with error: {0}", response.ErrorException.ToString()));
            }
            else
            {
                throw new InvalidOperationException(string.Format("Call to Comapi failed with status code ({0}), and body: {1}", response.StatusCode, response.Content));
            }
        }
    }
Exemplo n.º 4
0
        public async Task <SMSSendResponse> SendSms(SMSSendRequest sMSSendRequest)
        {
            // TODO : Validar request

            TwilioClient.Init(sMSSendRequest.AccountSID, sMSSendRequest.AuthToken);

            var message = MessageResource.Create(
                body: sMSSendRequest.MessageText,
                from: new PhoneNumber(sMSSendRequest.FromNumber),
                to: new PhoneNumber(sMSSendRequest.ToNumber)
                );

            return(new SMSSendResponse {
                ErrorCode = 0, MessageStatus = "Show de bola!"
            });
        }
Exemplo n.º 5
0
        private async static void SendSMS(SMSSendRequest smsRequest)
        {
            // Setup a REST client object using the message send URL with our API Space incorporated
            var options = new RestClientOptions(string.Format("https://api.comapi.com/apispaces/{0}/messages", CUSTOMER_APISPACE))
            {
                ThrowOnAnyError = false,
                Timeout         = 30000
            };

            var client = new RestClient(options);

            client.AddDefaultHeader("Content-Type", "application/json");
            client.AddDefaultHeader("Accept", "application/json");

            var request = new RestRequest();

            request.AddHeader("Cache-Control", "no-cache");
            request.AddHeader("authorization", "Bearer " +
                              CreateImpersonationToken(
                                  CUSTOMER_ACCOUNT_ID,
                                  RESELLER_ACCOUNT_ID,
                                  RESELLER_TOKEN_ISSUER,
                                  RESELLER_TOKEN_SECRET)); // Add the security token

            // Serialise our SMS request object to JSON for submission
            string requestJson = JsonConvert.SerializeObject(smsRequest, Formatting.None, new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore
            });

            request.AddParameter("application/json", requestJson, ParameterType.RequestBody);

            // Make the web service call
            var response = await client.ExecutePostAsync(request);

            if (response.StatusCode != System.Net.HttpStatusCode.Created)
            {
                // Something went wrong.
                throw new InvalidOperationException(string.Format("Call to Dotdigital Eneterprise Communications API failed with status code ({0}), and body: {1}", response.StatusCode, response.Content));
            }
            else
            {
                // Sucess output the response body
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine(FormatJson(response.Content));
                Console.ForegroundColor = ConsoleColor.White;
            }
        }
    public static void Send(SqlString phoneNumber, SqlString from, SqlString message)
    {
        // Set the channel options; optional step, comment out to use a local number to send from automatically
        var myChannelOptions = new SMSSendRequest.channelOptionsStruct();

        myChannelOptions.sms = new SMSSendRequest.smsChannelOptions()
        {
            from = from.Value, allowUnicode = true
        };

        // Send the messages
        var myRequest = new SMSSendRequest();

        myRequest.to             = new SMSSendRequest.toStruct(phoneNumber.Value);
        myRequest.body           = message.Value;
        myRequest.channelOptions = myChannelOptions;

        // Send it.
        SendSMS(myRequest);
    }
Exemplo n.º 7
0
        private static void SendSMS(SMSSendRequest smsRequest)
        {
            // Setup a REST client object using the web service URI and our API credentials
            var client = new RestClient(@"https://api-cpaas.dotdigital.com/cpaas/messages");

            client.Authenticator = new HttpBasicAuthenticator(API_USERNAME, API_PASSWORD);

            var request = new RestRequest(Method.POST);

            request.AddHeader("cache-control", "no-cache");
            request.AddHeader("content-type", "application/json");
            request.AddHeader("accept", "application/json");

            // Serialise our SMS request object to JSON for submission
            string requestJson = JsonConvert.SerializeObject(smsRequest, Formatting.None, new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore
            });

            request.AddParameter("application/json", requestJson, ParameterType.RequestBody);

            // Make the web service call
            IRestResponse response = client.Execute(request);

            if (response.StatusCode != System.Net.HttpStatusCode.Created)
            {
                // Something went wrong.
                throw new InvalidOperationException(string.Format("Call to Engagement Cloud CPaaS failed with status code ({0}), and body: {1}", response.StatusCode, response.Content));
            }
            else
            {
                // Sucess output the response body
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine(response.Content);
                Console.ForegroundColor = ConsoleColor.White;
            }
        }
Exemplo n.º 8
0
        static async Task Main(string[] args)
        {
            try
            {
                // Ensure we use later versions of TLS for security
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072 | (SecurityProtocolType)768;

                // Start the console
                Console.ForegroundColor = ConsoleColor.Blue;
                Console.WriteLine("Dotdigital enterprise Communications API SMS send example");
                Console.ForegroundColor = ConsoleColor.White;

                string         input, mode = null;
                SMSSendRequest myRequest = null;

                // Ask the user what demo mode they want
                do
                {
                    Console.WriteLine("Send a `single` message or a `batch`, enter your choice now?");
                    input = Console.ReadLine().ToLower();
                    switch (input)
                    {
                    case "s":
                    case "single":
                        mode = "single";
                        Console.WriteLine("Performing a single send");
                        break;

                    case "b":
                    case "batch":
                        mode = "batch";
                        Console.WriteLine("Performing a batch send of {0} messages", BATCH_SIZE);
                        break;
                    }

                    if (!string.IsNullOrEmpty(mode))
                    {
                        break;
                    }
                } while (true);

                // Set the channel options; optional step, comment out to use a local number to send from automatically
                var myChannelOptions = new SMSSendRequest.channelOptionsStruct();
                myChannelOptions.sms = new SMSSendRequest.smsChannelOptions()
                {
                    from = "Example", allowUnicode = false
                };

                // Send the messages
                switch (mode)
                {
                case "single":
                    // Create an SMS request.
                    myRequest                = new SMSSendRequest();
                    myRequest.to             = new SMSSendRequest.toStruct(MOBILE_NUMBER);
                    myRequest.body           = "This is an SMS via Dotdigital Enterprise Communications API";
                    myRequest.channelOptions = myChannelOptions;

                    // Send it.
                    await SendSMS(myRequest);

                    break;

                case "batch":
                    // Create a couple of requests in an array to create a batch of requests
                    SMSSendRequest[] myBatch = new SMSSendRequest[BATCH_SIZE];

                    for (int i = 0; i < BATCH_SIZE; i++)
                    {
                        // Create a message send request
                        myRequest                = new SMSSendRequest();
                        myRequest.to             = new SMSSendRequest.toStruct(MOBILE_NUMBER);
                        myRequest.body           = "This is message " + i;
                        myRequest.channelOptions = myChannelOptions;

                        // Add to batch array
                        myBatch[i] = myRequest;
                    }

                    // Send them
                    await SendSMSBatch(myBatch);

                    break;
                }

                // All good
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("SMS sent successfully");
                Console.ForegroundColor = ConsoleColor.White;
            }
            catch (Exception ex)
            {
                // Error
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Error: {0}", ex);
                Console.ForegroundColor = ConsoleColor.White;
            }

            // Wait
            Console.WriteLine("Press enter to continue...");
            Console.ReadLine();
        }