【thinkphp】app接口簽名+驗證簽名
app接口簽名+驗證簽名
比較簡單 求各位大牛指教
IndexController.class.phpjavascript
<?php namespace Home\Controller; use Think\Controller; class IndexController extends Controller { public function index(){ //緩存token過時時間 F(session_id().'tokenTime',time() + 1200); $this->display(); } /* * 接受數據 */ public function getMas(){ //接受token參數,強制轉換字符串 $token=I('post.token/s'); //驗證 $check=checkToken($token); if ($check== 10001){ $this->ajaxReturn("接口時間過時"); }elseif ($check== 10002){ $this->ajaxReturn("非法調用接口"); }elseif ($check== 10003){ $this->ajaxReturn("正常!"); } } }
Common\function.phpphp
/* * 驗證token * 10001 時間過時 * 10002 簽名失敗 * 10003 驗證經過 */ function checkToken($token){ //生成當前要驗證的token $check=md5(session_id().'str1'); //取過時時間 $tokenTime=S(session_id().'tokenTime'); //截取接收到的token裏面的時間 $time=substr($token,32); //截取接收到的token md5 $token=substr($token,0,32); //判斷是否過時 if ($tokenTime>$time){ //沒有過時 if ($check == $token){ //更新token過時時間 F(session_id().'tokenTime',time() + 1200); //返回正常 return 10003; }else { //簽名驗證失敗 return 10002; } }else { //返回過時,而且清空緩存 S(session_id().'tokenTime',NULL); return 10001; } }
模板寫法css
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>測試</title> <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js" type="text/javascript" charset="utf-8"></script> </head> <body> <input type="text" name="mas" id="mas" value="" /> <input type="button" id="tijiao" value="點擊發送" onclick="getMasg()" /> <input type="hidden" name="token" id="token" value="{:md5(session_id().'str1').base64_encode(time())}" /> <p>回覆的消息:<span id="str"></span></p> </body> <script type="text/javascript"> function getMasg(){ $.ajax({ url:'{:U('Home/Index/getMas')}', type:'POST', //GET data:{ token:$("#token").val(), }, success:function(data){ $("#str").text(data) console.log(data) }, }); } </script> </html>
各位大牛看看有何問題沒有 求指教html