手機APP接口
api就是接口,其實說白了就是你平時寫的控制器方法,只不過這個方法的數據要加密(api_token),要驗證,是用來把這個方法的url給app或者客戶端以及別人來調的。這個方法就是api接口
接口:客戶端發送一個請求到服務器
接口:1.URL地址:http://域名/控制器/方法 或者 https://
2.test.php處理客戶端發送數據
3.數據返回(json,xml)
json_encode()將數組轉換為字符串
<xml version=’1’>
<root>
<username>張三</username>
</root>
接口:1.開放性接口
2.非開放性接口(例如:微信公眾號)需要api_token
用戶需要到接口平台上注冊一個接口賬號,接口平台會給開發者一個用
戶uid和用戶密鑰secret
Api_token :md5(uid+secret+當前時間)
http://test.com/ api_token 過期時間
http://test.com/返回數據?Uid=xx & api_token=xx
User_token 用戶驗證是否登錄
接口請求方式:get post<form></form>
測試工具
客戶端發送請求內容格式:
1.請求數據格式:Content-type:application/json
請求數據:{‘username’:bobo,’password’:123456}
服務器端:$data = file_get_content(“php://input”)
Json_decode($data,true) 解析json字符串為數組
2.請求數據格式:Content-type:application/x-www-form-urlencoded
相當於form表單,Php會自動解析填充$_POST
請求數據:Username=bobo&password=123456
服務器端獲取數據:1.$_POST
2.file_get_contents(‘php://input’)
3.服務器端通過form表單上傳圖片時:
Content-type:multipart/form-data 圖片 二進制流格式
服務器端:$xrl = file_get_contents(‘php://input’)
File_put_contents(‘圖片.jpg’,$xrl);圖片存儲到服務器
服務器端接收數據:
php://input 獲取來源於任何設備的請求數據
File_get_contents(‘php://input’)
User_id = “wx”.md5(username.rand())
User_secret = md5(username.time().隨機數)
rand()生成隨機數
使用非公共接口
1.先到接口平台注冊賬號,接口平台分配用戶uid和用戶密鑰secret
2.根據用戶id和用戶密鑰secret生成一個api憑證 api_token
http://xxx.test.com/api/index/create_api_token?uid=xx&secret=xx
請求方式:get
返回值:json格式 成功{“status”:200,”api_token”:xxx}
失敗{“status”:201}
備注: api_token 有效期
3.請求接口時,需要帶上api_token
http://xxx.test.com/api/index/get_goods_list?api_token=xxx
請求方式:get
返回值:成功 {“status”=>200} 失敗
4.客戶端向服務器端發送數據 api_token
http://xxx.test.com/api/index/add_goods?api_token=xxx
描述:添加商品信息
數據格式:json {‘goods_name’:商品名稱,’goods_price’:商品價格}
請求方式:post
5.登錄成功生成用戶憑證user_token
http://xxx.test.com/api/index/login?Api_token=xxx
數據格式:{“username”:用戶名,”password”:密碼} post請求
請求成功:{“status”:200m,”token”:用戶憑證,“user”:”用戶信息”}
6.驗證用戶登錄
http://xxx.test.com/api/index/getinfo?User_token=xxx&user_id=xxx
數據格式:json application/json
請求方式:post
非對外接口
1.創建一張存儲接口使用者(開發者)的表 tb_api_user
2.Tb_api_token 用來驗證開發者是否有使用接口的權限
對外接口(公共接口)
http://www.test.com/ 或者 https://
返回到移動端的數據格式都是用json,是一種跨平台的數據格式
Json_encode(數組) 把數組轉化為json字符串
json_decode(json字符串,true) 把json字符串轉換為數組
User_token 用戶憑證:用來驗證用戶是否登錄
User_token = md5(uid.time().隨機數.網站密鑰(固定字符串)) //唯一