Implement the SMS Verification Code interface (connection-based communication) and Verification Code transport based on PHP

Source: Internet
Author: User

Implement the SMS Verification Code interface (connection-based communication) and Verification Code transport based on PHP

I have just studied it and hope it will be helpful to my partners.

Steps:

1. log on to the ronglian Yun communication and register to obtain the account sid, auth token, Rest URL (production), and AppID (default );

2. register the mobile phone number for the test (You must register the test number before using it );

3. Download the demo and put the code in the project (it is best to create a folder for Storage separately ).

Code area:

1. Create test. app. php (Controller for testing)

<? Php/** text message 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 '); // introduce the template file // primary ACCOUNT, corresponding to the account sid $ accountSid = ''under the primary ACCOUNT of the sender on the official website; // primary ACCOUNT token, corresponding to the auth token $ accountToken = ''under the primary account of the official website developer; // Application Id. Click the application in the Application List of the official website, corresponding app id in application details // during development and debugging, you can use the app id $ appId = ''of the test Demo automatically assigned to you on the official website ''; // request address // sandbox environment (for application development Try): sandboxapp.cloopen.com//production environment (used for app launch): app.cloopen.com $ serverIP = 'app .cloopen.com '; // request port. The production environment and sandbox environment are consistent. $ serverPort = '123 '; // The REST version number, which is obtained in the REST section of the official website. $ SoftVersion = '1970-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 ('123', '5 '), "1", $ accountSid, $ accountToken, $ appId, $ serverIP, $ serverPort, $ softVersion); // cell phone number, replacing the content array, template ID}/*** send template SMS * @ param to mobile phone number set, separated by commas (,) * @ param datas the data format of the content. For example, array ('marry ', 'on'). If you do not need to replace it, enter null * @ param $ tempId template Id. For test applications and offline applications, enter 1 as the test template, enter the template ID */public function sendTemplateSMS ($ to, $ datas, $ tempI D, $ accountSid, $ accountToken, $ appId, $ serverIP, $ serverPort, $ softVersion) {// initialize the rest sdk $ rest = new RestApp ($ serverIP, $ serverPort, $ softVersion); $ rest-> setAccount ($ accountSid, $ accountToken); $ rest-> setAppId ($ appId ); // send template text message 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 the returned information $ smsmessage = $ result-> TemplateSMS; echo" dateCreated :". $ smsmessage-> dateCreated. "<br/>"; echo "smsMessageSid :". $ smsmessage-> smsMessageSid. "<br/>"; // processing logic added to TODO }}}

Ii. template file (you can rename rest. app. php based on your own framework, or directly use the original demo name)

<? Phpclass RestApp {private $ AccountSid; private $ AccountToken; private $ AppId; private $ ServerIP; // = 'app .cloopen.com 'private $ ServerPort; // = '000000' private $ SoftVersion; // = '2017-12-26 'private $ Batch; // timestamp private $ BodyType = "xml"; // package format, which can be filled in: json, xmlprivate $ enabeLog = true; // log switch. Optional values: true and 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 Set primary account ** @ param AccountSid primary account * @ param AccountToken primary account Token */function setAccount ($ AccountSid, $ AccountToken) {$ this-> AccountSid = $ AccountSid; $ this-> AccountToken = $ AccountToken;}/*** set the Application ID * @ param AppId Application ID */function setAppId ($ AppId) {$ this-> AppId = $ AppId;}/*** print log ** @ param log Content */function showlog ($ log) {if ($ this-> enabeLog) {fwrite ($ this-> Handle, $ log. "\ n") ;}}/*** initiate HTTPS Request */function curl_p Ost ($ url, $ data, $ header, $ post = 1) {// initialize curl $ ch = curl_init (); // set the parameter $ res = curl_setopt ($ ch, CURLOPT_URL, $ url); curl_setopt ($ ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt ($ ch, success, 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, CURLOP T_HTTPHEADER, $ header); $ result = curl_exec ($ ch); // connection failure 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 set the receiver's mobile phone number for Receiving text messages, separate the * @ param datas content data * @ param $ tempId template Id */function sendTemplateSMS ($ to, $ datas, $ tempId) {// verify the authentication information of the primary account, empty the required parameter. // $ Auth = $ this-> accAuth (); // if ($ auth! = "") {// Return $ auth; //} // concatenate the 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); // upper case sig parameter $ sig = strtoupper (md5 ($ this-> AccountSid. $ this-> AccountToken. $ this-> Batch); // generate the request URL $ url = "https: // $ this-> ServerIP: $ this-> ServerPort/$ this-> SoftVersion/Accounts/$ this-> AccountSid/SMS/TemplateSMS? Sig = $ sig "; $ this-> showlog (" request url = ". $ url); // generate authorization: primary account Id + English colon + timestamp. $ Authen = base64_encode ($ this-> AccountSid. ":". $ this-> Batch); // generate the header $ header = array ("Accept: application/$ this-> BodyType", "Content-Type: application/$ this-> BodyType; charset = UTF-8 "," Authorization: $ authen "); // send a 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 = '000000'; // $ datas-> statusMsg = 'Return package error '; //} // reload the data if ($ datas-> statusCode = 0) {if ($ this-> BodyType = "json ") {$ datas-> TemplateSMS = $ datas-> templateSMS; unset ($ datas-> templateSMS) ;}} return $ datas ;} /*** primary account authentication */function accAuth () {if ($ this-> ServerIP = "") {$ data = new stdClass (); $ data-> statu SCode = '000000'; $ data-> statusMsg = 'IP blank '; return $ data;} if ($ this-> ServerPort <= 0) {$ data = new stdClass (); $ data-> statusCode = '000000'; $ data-> statusMsg = 'port error (less than or equal to 0) '; return $ data ;} if ($ this-> SoftVersion = "") {$ data = new stdClass (); $ data-> statusCode = '000000 '; $ data-> statusMsg = 'version number is blank '; return $ data;} if ($ this-> AccountSid = "") {$ data = new stdClass (); $ data-> statusCode = '000000'; $ data-> statusMsg =' The primary account is blank; return $ data;} if ($ this-> AccountToken = "") {$ data = new stdClass (); $ data-> statusCode = '000000'; $ data-> statusMsg = 'Primary account token is blank '; return $ data ;} if ($ this-> AppId = "") {$ data = new stdClass (); $ data-> statusCode = '000000 '; $ data-> statusMsg = 'application ID is blank '; return $ data ;}}?>

Three steps front template code (test.html)

<Div style = "height: 100px; border: 1px solid gray; text-align: center; padding-top: 20px; "> <form action =" "method =" post "> enter the mobile phone number: <input type = "text" name = "phone_mob"> <input type = "button" name = "btn" value = "click to obtain the verification code"> <br/> enter the verification code: <input type = "text" name = "yzm" value = ""> <br/> <input type = "submit" name = "sbt" value = "submit"> </form> </div>

Iv. 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 ", // the URL of the request background dataType:" json ", data: {'phone _ mob': phone_mob}, success: function (data) {if (data. done & data. retval) {// console. log (data. retval); alert ('success! ') ;}}}) ;}) ;}}); </Script>

The above section describes the PHP-based SMS Verification Code interface (for cross-transport communication). I hope it will be helpful to you. If you have any questions, please leave a message for me, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!

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.