1. 首先,要设置一个入口文件
入口文件的话会引入到固定的api文件(如下):
<?phpdefine("appapi_allow_request_login", 'y'); //是否允许传用户名密码参数的形式登录。如为y则参数用户名密码参数和basic方式都可以,如为n就只能basic方式。//define("site_template_path", '/local/templates/mobile_app_api'); //如不定义,默认是local/templates/bitrix24。可以考虑将/local/templates/mobile_app留给h5前端展示用。新开/local/templates/mobile_app_api给api用。如不指定site_template_path直接includecomponent,则对组件代码进行debug时,会出现web端头部页面。//require_once($_server['document_root'] . '/bitrix/header.php'); //需要模板页面header('access-control-allow-origin: *');header('access-control-allow-headers: origin, content-type, accept');header('x-content-type-options: nosniff');require("remote_auth.php");//app方式每次请求session_id()都会变,导致挂钩在session_id()下面的所有session信息如fix_session_id也都不认。所以登录完毕后要拿到session_id(),并在后续接口一起传给接口,接口再去指定session_id。//$_request['org_sessid']='06q75330o31se1cf4d7vl1bdm4';if(!empty($_request['org_sessid'])){ $org_session_id=$_request['org_sessid']; session_id($org_session_id); session_start(); //echo session_id(); //echo "<pre>";print_r($_session);exit;}require_once($_server["document_root"] . "/bitrix/modules/main/include/prolog_before.php"); //无需模板页面$application->includecomponent("vdg:mobile.data", "", array());exit;?>
2. 其次,在引入的组件的component.php中获取参数,确定模板的使用
<?php...include_once(dirname(__file__) . "/functions.php");//引入类的方法的文件...if ($_request["mobile_action"])//executing some action{ $application->restartbuffer(); $action = $_request["mobile_action"]; //crestutil::sendheaders(); //跨域header $actionlist = new bitrix\mobile\action(); $actionlist->executeaction($action, $arparams); cmain::finalactions(); die();}elseif ($_request["captcha_sid"])//getting captcha image 通过 /vdg/app_api.php?captcha_sid=1 可以得到图形验证码。{ $application->restartbuffer(); $actionlist = new bitrix\mobile\action(); $actionlist->executeaction("get_captcha", $arparams); die();}elseif ($_request["manifest_id"])//getting content of appcache manifest{ include($_server["document_root"] .\bitrix\main\data\appcachemanifest::manifest_check_file); die();}elseif(!$user->isauthorized() || !$issessidvalid){ $application->restartbuffer(); header("http/1.0 401 not authorized"); if(bitrix\mobileapp\mobile::getinstance()->getinstance() != "android") { //header("content-type: application/x-javascript"); header("content-type: application/json"); header("bx-authorize: ".bitrix_sessid()); } jsonerror('201', '请先登陆'); //echo json_encode(array("status" => "failed", "bitrix_sessid"=>bitrix_sessid())); die();}?>
3.在具体的模板中运用类的方法根据参数获取相应的数据,并返回客户端结果
如果成果返回“ jsonsuccess(questions);”如果失败返回“jsonerror(′201′,questions);”
如果失败返回“jsonerror(′201′,questres[“error”]);”或其他错误讯息。
推荐教程:php视频教程
以上就是php后端接口怎么写的详细内容。
