A method of implementing SMS verification Code interface based on PHP

Source: Internet
Author: User
Tags log log
This article steps to explain the SMS Verification Code interface Implementation code, very good, with reference value, interested friends to see it together

Oneself is also just research, hope to also be helpful in the research partner.

Steps:

1, Login Rong Intermodal communication registration Get account SID, AUTH TOKEN, Rest URL (production), AppID (default);

2, registration test mobile phone number (first registered test number can be used);

3. Download the demo sample and put the code in the project (preferably a separate folder store).

Code area:

First, the new test.app.php (test controller)

<?php/** SMS Interface Test */class TESTAPP extends Shoppingbaseapp{public function index () {$this->display (' test.html ');} Public Function Get_info () {include_once (Root_path. ') /includes/rly_message/rest.app.php ');//The introduction of template files//master account, corresponding to open the official account of the main accounts sid$accountsid = ";//Main account command card, corresponding to the official website Developer Master Account AUTH Token$accounttoken = ";//Application ID, click on the application in the official website application list, corresponding application details of the app id//in the development of debugging, you can use the official website automatically assigned to your test demo app id$appid =";/ Request Address/Sandbox environment (for application development Debugging): sandboxapp.cloopen.com//production environment (user application online): App.cloopen.com$serverip = ' app.cloopen.com ';//Request Port, Production environment and sandbox environment consistent $serverport = ' 8883 ';//rest version number, obtained in the official document rest introduction. $softVersion = ' 2013-12-26 ';//global $accountSid, $accountToken, $appId, $serverIP, $serverPort, $softVersion; $phone _ Mob = isset ($_get[' Phone_mob ')? $_get[' phone_mob ': '; if ($phone _mob) {$this->sendtemplatesms ($phone _mob,array (' 3519 ', ' 5 '), "1", $accountSid, $ Accounttoken, $appId, $serverIP, $serverPort, $softVersion);//mobile number, replacement content array, template id}}/*** send template SMS * @param to mobile phone number collection, separated by commas * @param datas Content data format to an array such as: Array (' Marry ', ' Alon '), if no replacement is required please fill in null* @param $Tempid template ID, test application and non-online application Use test template please fill in 1, the official application to fill out the template after applying for approval id*/public function sendtemplatesms ($to, $datas, $tempId, $ Accountsid, $accountToken, $appId, $serverIP, $serverPort, $softVersion) {//Initialize rest sdk$rest = new Restapp ($serverIP, $ ServerPort, $softVersion), $rest->setaccount ($accountSid, $accountToken); $rest->setappid ($APPID);// Send template SMS echo "sending templatesms to $to <br/>"; $result = $rest->sendtemplatesms ($to, $datas, $tempId); if ($ result = = NULL) {echo "result error!"; Exit ();} if ($result->statuscode!=0) {echo "Error code:". $result->statuscode. "<br>"; echo "error msg:". $result->statusmsg. "<br>";//todo add error handling logic}else{echo "Sendind templatesms success!<br/>";//Get return information $smsmessage = $result Templatesms;echo "dateCreated:". $smsmessage->datecreated. " <br/> "; echo" Smsmessagesid: ". $smsmessage->smsmessagesid." <br/> ";//todo add successful Processing logic}}}

Second, template files (rest.app.php can be renamed according to their own framework, you can also directly use the original name of the demo)

<?phpclass Restapp {private $AccountSid; private $AccountToken; private $AppId; private $ServerIP;//= ' App.cloopen. com ' private $ServerPort; = ' 8883 ' private $SoftVersion; = ' 2013-12-26 ' private $Batch; Timestamp private $BodyType = "xml";//package format, can be filled: json, xmlprivate $enabeLog = true; Log switch. Available values: true, private $Filename = "./log.txt"; Log file private $Handle; function __construct ($ServerIP, $ServerPort, $SoftVersion) {$this->restapp ($ServerIP, $ServerPort, $SoftVersion);} function Restapp ($ServerIP, $ServerPort, $SoftVersion) {$this->batch = date ("Ymdhis"); $this->serverip = $ ServerIP; $this->serverport = $ServerPort; $this->softversion = $SoftVersion; $this->handle = fopen ($this Filename, ' a ');} /*** Set Master Account * * @param accountsid Master account * @param accounttoken Master account token*/function Setaccount ($AccountSid, $AccountToken) {$ This->accountsid = $AccountSid; $this->accounttoken = $AccountToken; }/*** Settings App id* @param AppId app id*/function setappid ($AppId) {$this->appid = $AppId;} /*** Print Log * * @param log Log Contents */function Showlog ($log) {if ($this->enabelog) {fwrite ($this->handle, $log. " \ n "); }}/*** initiates HTTPS request */function Curl_post ($url, $data, $header, $post =1) {//Initialize curl$ch = Curl_init ();//Parameter Set $res = curl_setopt ($ch, Curlopt_url, $url); curl_setopt ($ch, Curlopt_ssl_verifyhost, false); curl_setopt ($ch, Curlopt_ssl_verifypeer, false); curl_setopt ($ch, Curlopt_header, 0); curl_setopt ($ch, Curlopt_post, $post); if ($post) {curl_setopt ($ch, Curlopt_postfields, $data);} curl_setopt ($ch, Curlopt_returntransfer, 1); curl_setopt ($ch, Curlopt_httpheader, $header); $result = Curl_exec ($ch); /Connection Failed if ($result = = FALSE) {if ($this->bodytype== ' json ') {$result = "{\" statuscode\ ": \" 172001\ ", \" statusmsg\ ": \" Network error \ "}";} else {$result = "<?xml version=\" 1.0\ "encoding=\" utf-8\ "standalone=\" yes\ "? ><response><statuscode >172001</statusCode><statusMsg> network error </statusMsg></Response> "; }}curl_close ($ch); return $result;} /*** Send template text message * @param to SMS receive a collection of mobile phone numbers, separated by commas * @param datas contentData * @param $tempId template id*/function sendtemplatesms ($to, $datas, $tempId) {//Master account authentication information, the required parameters are empty. $auth = $this->accauth ()//if ($auth! = "") {//return $auth;//}//Stitching Request Package Body if ($this->bodytype== "json") {$data = ""; for ($i =0; $i <count ($datas); $i + +) {$data = $data. "'". $datas [$i]. "',"; } $body = "{' to ': ' $to ', ' TemplateID ': ' $tempId ', ' appId ': ' $this->appid ', ' datas ': [". $data. "]}";} else{$data = ""; for ($i =0; $i <count ($datas); $i + +) {$data = $data. "<data>". $datas [$i]. " </data> "; } $body = "<TemplateSMS><to> $to </to> <appId> $this->appid</appid><templateid > $tempId </templateId><datas> ". $data." </datas></TemplateSMS> ";} $this->showlog ("Request BODY =". $body);//capitalize the sig parameter $sig = Strtoupper (MD5 ($this->accountsid. $this->accounttoken. $this->batch));//Generate request URL $url = "https://$this->serverip: $this->serverport/$this->softversion/ accounts/$this->accountsid/sms/templatesms?sig= $sig "; $this->showlog (" Request URL = ". $url);//Generate Authorization: Master account ID + English colon + timestamp. $authen = Base64_encode ($this->accountsid. ":" . $this->batch);//Generate Header $header = Array ("accept:application/$this->bodytype", "content-type:application/$this- >bodytype;charset=utf-8 "," Authorization: $authen ");//Send Request $result = $this->curl_post ($url, $body, $header); This->showlog ("Response BODY =". $result), if ($this->bodytype== "json") {//json format $datas=json_decode ($result);} else{//xml Format $datas = simplexml_load_string (Trim ($result, "\t\n\r"));} if ($datas = = FALSE) {//$datas = new StdClass ();//$datas->statuscode = ' 172003 ';//$datas->statusmsg = ' return package error '; }//Reload Data if ($datas->statuscode==0) {if ($this->bodytype== "json") {$datas->templatesms = $datas Templatesms;unset ($datas->templatesms); }}return $datas; }/*** Master Account authentication */function Accauth () {if ($this->serverip== "") {$data = new StdClass (); $data->statuscode = ' 172004 '; $ data->statusmsg = ' ip is empty '; return $data;} if ($this->serverport<=0) {$data = new StdClass (); $data-&GT;statuscode = ' 172005 '; $data->statusmsg = ' port error (less than or equal to 0) '; return $data;} if ($this->softversion== "") {$data = new StdClass (); $data->statuscode = ' 172013 '; $data->statusmsg = ' version number is empty '; return $data;} if ($this->accountsid== "") {$data = new StdClass (); $data->statuscode = ' 172006 '; $data->statusmsg = ' master account is empty '; return $data;} if ($this->accounttoken== "") {$data = new StdClass (); $data->statuscode = ' 172007 '; $data->statusmsg = ' main account command is empty ' ; return $data;} if ($this->appid== "") {$data = new StdClass (); $data->statuscode = ' 172012 '; $data->statusmsg = ' Application id is empty '; return $ data;} }}?>

Third, the front desk template code (test.html)

<p style= "height:100px;border:1px solid gray;text-align:center;padding-top:20px;" ><form action= "" method= "POST" > Please enter phone number: <input type= "text" name= "Phone_mob" ><input type= "button" Name= "BTN" value= "Click to get Verification code" ><br/> Enter Captcha: <input type= "text" name= "Yzm" value= "><br/><input Type= "Submit" Name= "SBT" value= "Submission" ></form></p>

Four, JS code

<script type= "Text/javascript" >$ (function () {$ (' input[name=btn] '). On (' click ', function () {var phone_mob = $ (' Input[name=phone_mob]. val (); $.ajax ({type: "GET", url: "Index.php?app=test&act=get_info",// Request background URL address datatype: "JSON", data:{' Phone_mob ': phone_mob},success:function (data) {if (Data.done && Data.retval) {//console.log (data.retval); alert (' Success! ');}}});}); });</script>

Summary: The above is the entire content of this article, I hope to be able to help you learn.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.