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
extern crate reqwest;
extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;

use std::collections::HashMap;

#[derive(Debug, Deserialize)]
struct SingleSendResult {
    code: i64,
    msg: String,
    /// how many messages are sent
    count: i64,
    /// 70 chinese characters per message,
    /// if exceeding 70 characters, then as 67 per message.
    fee: f64,
    unit: String,
    /// mobile phone sent
    mobile: String,
    /// short message id
    sid: i64,
}

pub struct Yunpian {
    api_key: String,
    client: reqwest::Client,
}

impl Yunpian {
    pub fn new(key: &str) -> Yunpian {
        Yunpian {
            api_key: key.to_string(),
            client: reqwest::ClientBuilder::new().expect("failed to create Yunpian client")
                        .timeout(std::time::Duration::from_secs(10))
                        .build().expect("failed to create Yunpian client"),
        }
    }

    /// send a single short message,
    /// returns true if it successfully sends out, otherwise false.
    pub fn send_single(&mut self, text: &str, mobile: &str) -> bool {
        match self.send_single_impl(text, mobile) {
            Ok(result) => { result.code == 0 }
            Err(_) => { false }
        }
    }
    fn send_single_impl(&mut self, text: &str, mobile: &str) -> Result<SingleSendResult, reqwest::Error> {
        let mut param = HashMap::new();
        param.insert("text", text);
        param.insert("mobile", mobile);
        param.insert("apikey", &self.api_key);
        let url = "https://sms.yunpian.com/v2/sms/single_send.json".to_string();
        let json : SingleSendResult = self.client.post(&url)?
            .form(&param)?
            .send()?
            .json()?;
        Ok(json)
    }
}