App开发(Android与php接口)之:短信验证码

  最近和同学们一起开发一个自主项目,要用到短信验证码,在网上搜索了很久,看到一个推荐贴,提到了很多不错的短信服务商。经过测试,帖子中提到的服务商他们的短信到达率和到达速度也都不错。最后,由于经费问题,我们决定选用云片网络。以下是开发流程:

  首先,注册并登陆到后台,并填写一些信息、申请。获得APIKEY。

  接下来,有了APIKEY就能开发接口了。

<?php
header("Content-Type:text/html;charset=utf-8");
$apikey = "********填入APPKEY********";
$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);
// 发送模板短信
// 需要对value进行编码
$mobile = 12345678910; // 接收短信的手机号
$code = getRandomCheckCode(); // 要发送的验证码
$data=array(
    'tpl_id'    => 5, // 此处为模板id,不设置时默认为1
    'tpl_value'    => urlencode('#code#').'='.urlencode($code)
        .'&'.urlencode('#company#').'='.urlencode('公司名称')
        .'&'.urlencode('#app#').'='.urlencode('app名称'),
    'apikey'    => $apikey,
    'mobile'    =>$mobile
);

curl_setopt ($ch, CURLOPT_URL, 'https://sms.yunpian.com/v1/sms/tpl_send.json');
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
$send_result = json_decode(curl_exec($ch), true);
curl_close($ch);
if(0 == $send_result['code']) { // 成功

} else { // 失败

}
// 此处附上一个验证码生成函数
 function getRandomCheckCode() {
     $chars = '0123456789';
     mt_srand((double)microtime()*1000000*getmypid());
     $CheckCode="";
     while(strlen($CheckCode)<6)
         $CheckCode.=substr($chars,(mt_rand()%strlen($chars)),1);
     return $CheckCode;
 }
?>

 

posted @ 2016-01-18 14:49  仰戈  阅读(3143)  评论(1编辑  收藏  举报