Java PHP Python实现短信验证码和国际短信群发功能

来源:互联网 发布:淘宝运动装女士 编辑:程序博客网 时间:2024/05/22 08:21

最近由于公司的业务拓展,需要给国外用户发送国际短信,像西班牙、葡萄牙、意大利这些国家都要发,还有中国的香港、澳门、台湾(港澳台)这些地区也要发,不过现在已经有许多公司提供国际短信的业务了,之前使用过云片的验证码业务,顺便看到他们也有国际短信的业务,并且更重要的是,不需要修改任何代码,只要添加下国际短信模板,就可以直接使用之前的代码继续发送国际短信,简直太方便了。

废话不多说,直接上代码。

Java

/*** Created by bingone on 15/12/16.*/import org.apache.http.HttpEntity;import org.apache.http.NameValuePair;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;import java.io.IOException;import java.net.URISyntaxException;import java.net.URLEncoder;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;/*** 短信http接口的java代码调用示例* 基于Apache HttpClient 4.3** @author songchao* @since 2015-04-03*/public class JavaSmsApi {    //查账户信息的http地址    private static String URI_GET_USER_INFO = "https://sms.yunpian.com/v2/user/get.json";    //智能匹配模板发送接口的http地址    private static String URI_SEND_SMS = "https://sms.yunpian.com/v2/sms/single_send.json";    //模板发送接口的http地址    private static String URI_TPL_SEND_SMS = "https://sms.yunpian.com/v2/sms/tpl_single_send.json";    //发送语音验证码接口的http地址    private static String URI_SEND_VOICE = "https://voice.yunpian.com/v2/voice/send.json";    //绑定主叫、被叫关系的接口http地址    private static String URI_SEND_BIND = "https://call.yunpian.com/v2/call/bind.json";    //解绑主叫、被叫关系的接口http地址    private static String URI_SEND_UNBIND = "https://call.yunpian.com/v2/call/unbind.json";    //编码格式。发送编码格式统一用UTF-8    private static String ENCODING = "UTF-8";    public static void main(String[] args) throws IOException, URISyntaxException {        //修改为您的apikey.apikey可在官网(http://www.yunpian.com)登录后获取        String apikey = "xxxxxxxxxxxxxxxxxxxxx";        //修改为您要发送的手机号        String mobile = "130xxxxxxxx";        /**************** 查账户信息调用示例 *****************/        System.out.println(JavaSmsApi.getUserInfo(apikey));        /**************** 使用智能匹配模板接口发短信(推荐) *****************/        //设置您要发送的内容(内容必须和某个模板匹配。以下例子匹配的是系统提供的1号模板)        String text = "【云片网】您的验证码是1234";        //发短信调用示例        // System.out.println(JavaSmsApi.sendSms(apikey, text, mobile));        /**************** 使用指定模板接口发短信(不推荐,建议使用智能匹配模板接口) *****************/        //设置模板ID,如使用1号模板:【#company#】您的验证码是#code#        long tpl_id = 1;        //设置对应的模板变量值        String tpl_value = URLEncoder.encode("#code#",ENCODING) +"="        + URLEncoder.encode("1234", ENCODING) + "&"        + URLEncoder.encode("#company#",ENCODING) + "="        + URLEncoder.encode("云片网",ENCODING);        //模板发送的调用示例        System.out.println(tpl_value);        System.out.println(JavaSmsApi.tplSendSms(apikey, tpl_id, tpl_value, mobile));        /**************** 使用接口发语音验证码 *****************/        String code = "1234";        //System.out.println(JavaSmsApi.sendVoice(apikey, mobile ,code));        /**************** 使用接口绑定主被叫号码 *****************/        String from = "+86130xxxxxxxx";        String to = "+86131xxxxxxxx";        Integer duration = 30*60;// 绑定30分钟        //        System.out.println(JavaSmsApi.bindCall(apikey, from ,to , duration));        /**************** 使用接口解绑主被叫号码 *****************/        //        System.out.println(JavaSmsApi.unbindCall(apikey, from, to));    }    /**    * 取账户信息    *    * @return json格式字符串    * @throws java.io.IOException    */    public static String getUserInfo(String apikey) throws IOException, URISyntaxException {        Map<String, String> params = new HashMap<String, String>();        params.put("apikey", apikey);        return post(URI_GET_USER_INFO, params);    }    /**    * 智能匹配模板接口发短信    *    * @param apikey apikey    * @param text    短信内容    * @param mobile  接受的手机号    * @return json格式字符串    * @throws IOException    */    public static String sendSms(String apikey, String text, String mobile) throws IOException {        Map<String, String> params = new HashMap<String, String>();        params.put("apikey", apikey);        params.put("text", text);        params.put("mobile", mobile);        return post(URI_SEND_SMS, params);    }    /**    * 通过模板发送短信(不推荐)    *    * @param apikey    apikey    * @param tpl_id     模板id    * @param tpl_value  模板变量值    * @param mobile     接受的手机号    * @return json格式字符串    * @throws IOException    */    public static String tplSendSms(String apikey, long tpl_id, String tpl_value, String mobile) throws IOException {        Map<String, String> params = new HashMap<String, String>();        params.put("apikey", apikey);        params.put("tpl_id", String.valueOf(tpl_id));        params.put("tpl_value", tpl_value);        params.put("mobile", mobile);        return post(URI_TPL_SEND_SMS, params);    }    /**    * 通过接口发送语音验证码    * @param apikey apikey    * @param mobile 接收的手机号    * @param code   验证码    * @return    */    public static String sendVoice(String apikey, String mobile, String code) {        Map<String, String> params = new HashMap<String, String>();        params.put("apikey", apikey);        params.put("mobile", mobile);        params.put("code", code);        return post(URI_SEND_VOICE, params);    }    /**    * 通过接口绑定主被叫号码    * @param apikey apikey    * @param from 主叫    * @param to   被叫    * @param duration 有效时长,单位:秒    * @return    */    public static String bindCall(String apikey, String from, String to , Integer duration ) {        Map<String, String> params = new HashMap<String, String>();        params.put("apikey", apikey);        params.put("from", from);        params.put("to", to);        params.put("duration", String.valueOf(duration));        return post(URI_SEND_BIND, params);    }    /**    * 通过接口解绑绑定主被叫号码    * @param apikey apikey    * @param from 主叫    * @param to   被叫    * @return    */    public static String unbindCall(String apikey, String from, String to) {        Map<String, String> params = new HashMap<String, String>();        params.put("apikey", apikey);        params.put("from", from);        params.put("to", to);        return post(URI_SEND_UNBIND, params);    }    /**    * 基于HttpClient 4.3的通用POST方法    *    * @param url       提交的URL    * @param paramsMap 提交<参数,值>Map    * @return 提交响应    */    public static String post(String url, Map<String, String> paramsMap) {        CloseableHttpClient client = HttpClients.createDefault();        String responseText = "";        CloseableHttpResponse response = null;            try {                HttpPost method = new HttpPost(url);                if (paramsMap != null) {                    List<NameValuePair> paramList = new ArrayList<NameValuePair>();                    for (Map.Entry<String, String> param : paramsMap.entrySet()) {                        NameValuePair pair = new BasicNameValuePair(param.getKey(), param.getValue());                        paramList.add(pair);                    }                    method.setEntity(new UrlEncodedFormEntity(paramList, ENCODING));                }                response = client.execute(method);                HttpEntity entity = response.getEntity();                if (entity != null) {                    responseText = EntityUtils.toString(entity, ENCODING);                }            } catch (Exception e) {                e.printStackTrace();            } finally {                try {                    response.close();                } catch (Exception e) {                    e.printStackTrace();                }            }            return responseText;        }}

PHP

<?phpheader("Content-Type:text/html;charset=utf-8");$apikey = "xxxxxxxxxxx"; //修改为您的apikey(https://www.yunpian.com)登录官网后获取$mobile = "xxxxxxxxxxx"; //请用自己的手机号代替$text="【云片网】您的验证码是1234";$ch = curl_init();/* 设置验证方式 */curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept:text/plain;charset=utf-8', 'Content-Type:application/x-www-form-urlencoded','charset=utf-8'));/* 设置返回结果为流 */curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);/* 设置超时时间*/curl_setopt($ch, CURLOPT_TIMEOUT, 10);/* 设置通信方式 */curl_setopt($ch, CURLOPT_POST, 1);curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 取得用户信息$json_data = get_user($ch,$apikey);$array = json_decode($json_data,true);echo '<pre>';print_r($array);// 发送短信$data=array('text'=>$text,'apikey'=>$apikey,'mobile'=>$mobile);$json_data = send($ch,$data);$array = json_decode($json_data,true);echo '<pre>';print_r($array);// 发送模板短信// 需要对value进行编码$data=array('tpl_id'=>'1','tpl_value'=>('#code#').'='.urlencode('1234').'&'.urlencode('#company#').'='.urlencode('欢乐行'),'apikey'=>$apikey,'mobile'=>$mobile);print_r ($data);$json_data = tpl_send($ch,$data);$array = json_decode($json_data,true);echo '<pre>';print_r($array);// 发送语音验证码$data=array('code'=>'9876','apikey'=>$apikey,'mobile'=>$mobile);$json_data =voice_send($ch,$data);$array = json_decode($json_data,true);echo '<pre>';print_r($array);curl_close($ch);/***************************************************************************************///获得账户function get_user($ch,$apikey){    curl_setopt ($ch, CURLOPT_URL, 'https://sms.yunpian.com/v2/user/get.json');    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('apikey' => $apikey)));    return curl_exec($ch);}function send($ch,$data){    curl_setopt ($ch, CURLOPT_URL, 'https://sms.yunpian.com/v2/sms/single_send.json');    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));    return curl_exec($ch);}function tpl_send($ch,$data){    curl_setopt ($ch, CURLOPT_URL, 'https://sms.yunpian.com/v2/sms/tpl_single_send.json');    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));    return curl_exec($ch);}function voice_send($ch,$data){    curl_setopt ($ch, CURLOPT_URL, 'http://voice.yunpian.com/v2/voice/send.json');    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));    return curl_exec($ch);}?>

Python

#!/usr/local/bin/python#-*-coding:utf-8-*-#author: jacky# Time: 15-12-15# Desc: 短信http接口的python代码调用示例# https://www.yunpian.com/api/demo.html# https访问,需要安装  openssl-devel库。apt-get install openssl-develimport httplibimport urllibimport json#服务地址sms_host = "sms.yunpian.com"voice_host = "voice.yunpian.com"#端口号port = 443#版本号version = "v2"#查账户信息的URIuser_get_uri = "/" + version + "/user/get.json"#智能匹配模板短信接口的URIsms_send_uri = "/" + version + "/sms/single_send.json"#模板短信接口的URIsms_tpl_send_uri = "/" + version + "/sms/tpl_single_send.json"#语音短信接口的URIsms_voice_send_uri = "/" + version + "/voice/send.json"#语音验证码voiceCode = 1234def get_user_info(apikey):    """    取账户信息    """    conn = httplib.HTTPSConnection(sms_host , port=port)    headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}    conn.request('POST',user_get_uri,urllib.urlencode( {'apikey' : apikey}))    response = conn.getresponse()    response_str = response.read()    conn.close()    return response_strdef send_sms(apikey, text, mobile):    """    通用接口发短信    """    params = urllib.urlencode({'apikey': apikey, 'text': text, 'mobile':mobile})    headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}    conn = httplib.HTTPSConnection(sms_host, port=port, timeout=30)    conn.request("POST", sms_send_uri, params, headers)    response = conn.getresponse()    response_str = response.read()    conn.close()    return response_strdef tpl_send_sms(apikey, tpl_id, tpl_value, mobile):    """    模板接口发短信    """    params = urllib.urlencode({'apikey': apikey, 'tpl_id':tpl_id, 'tpl_value': urllib.urlencode(tpl_value), 'mobile':mobile})    headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}    conn = httplib.HTTPSConnection(sms_host, port=port, timeout=30)    conn.request("POST", sms_tpl_send_uri, params, headers)    response = conn.getresponse()    response_str = response.read()    conn.close()    return response_strdef send_voice_sms(apikey, code, mobile):    """    通用接口发短信    """    params = urllib.urlencode({'apikey': apikey, 'code': code, 'mobile':mobile})    headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}    conn = httplib.HTTPSConnection(voice_host, port=port, timeout=30)    conn.request("POST", sms_voice_send_uri, params, headers)    response = conn.getresponse()    response_str = response.read()    conn.close()    return response_strif __name__ == '__main__':    #修改为您的apikey.可在官网(http://www.yunpian.com)登录后获取    apikey = "xxxxxxxxxxxxxxxx"    #修改为您要发送的手机号码,多个号码用逗号隔开    mobile = "xxxxxxxxxxxxxxxx"    #修改为您要发送的短信内容    text = "【云片网】您的验证码是1234"    #查账户信息    print(get_user_info(apikey))    #调用智能匹配模板接口发短信    print send_sms(apikey,text,mobile)    #调用模板接口发短信    tpl_id = 1 #对应的模板内容为:您的验证码是#code#【#company#】    tpl_value = {'#code#':'1234','#company#':'云片网'}    print tpl_send_sms(apikey, tpl_id, tpl_value, mobile)    #调用模板接口发语音短信    print send_voice_sms(apikey,voiceCode,mobile)

代码看上去有点乱了,不过我们用到的API接口也就那么几个,具体的可以看这篇文章如何使用云片API发送短信验证码,只要把那三个接口搞定了,无论是国际短信、国内短信还是短信验证码、手机验证码,都可以轻松搞定,so easy!

1 0
原创粉丝点击