菜鸟教你如何用php写后台API

1. 首先,要设置一个入口文件

入口文件的话会引入到固定的api文件(如下):

<?php

define("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中获取参数,确定模板的使用

如 “http://192.168.56.1:7070/vdg/app_api.php?mobile_action=appapi_designer_list&model=designerku“:

<?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, questRes[“ERROR”]);”或其他错误讯息,当然最重要的,最重要的,最重要的还是类的方法(菜鸟一般写不出来,比如我):

<?
/**
 * activity.php, 活动问答的API
 */
class VActivity
{
    /**
     * 获取所有问题的列表
     *
     * @return array()
     * @static
     */
    public static function getQuestions($withAnswerCounts=false)
    {
        global $DB, $USER;

        // if (!$USER->IsAuthorized()) {
        //     return array();
        // }

        $arSqls["SELECT"]=' ID,TITLE,CONTENT,DATE_CREATE,DATE_UPDATE,CREATED_BY,REWARD ';
        //$arSqls["WHERE"]=" ID='".$DB->ForSql($questID,11)."' ";
        $strSql = "SELECT ".$arSqls["SELECT"]." FROM v_act_question";
        $dbRes = $DB->Query($strSql, false, "File: ".__FILE__."<br>Line: ".__LINE__);
        $questions = array();
        $userIds = array();
        if ($dbRes){
            while ($arr_exp = $dbRes->Fetch()){
                $questions[]=$arr_exp;
                $userIds[] = $arr_exp["CREATED_BY"];
            }
        }
        $userDict = static::getUserDict($userIds);
        for($i = 0;$i<count($questions);$i++) {
            $questions[$i]["CREATED_BY_NAME"] = $userDict[$questions[$i]["CREATED_BY"]];
            if ($withAnswerCounts) {
                $questions[$i]["ANSWERS"] = count(static::getAnswers($questions[$i]["ID"], false));
            }
        }
        return $questions;
    }

    private static function getUserDict($userIds)
    {
        $res = array();
        foreach($userIds as $key => $val) {
            $uRes = CUser::GetByID($val);
            $u = $uRes->Fetch();
            if ($u) {
                $name = $u["NAME"];
                if ($name) {
                    $res[$val] = $name;
                }
                else {
                    $login = $u["LOGIN"];
                    $res[$val] = $login;
                }               

            }
        }
        return $res;
    }

    public static function getQuestion($questionID, $withUserName=true, $arSelect="")
    {
        global $DB, $USER;
        // if (!$USER->IsAuthorized()) {
        //     return array();
        // }
        if (empty($arSelect)) {
            $arSqls["SELECT"]=' ID,TITLE,CONTENT,DATE_CREATE,DATE_UPDATE,CREATED_BY,REWARD ';
        } else {
            $arSqls["SELECT"]=' '.$arSelect.' ';
        }

        $arSqls["WHERE"]=" ID='".$DB->ForSql($questionID,11)."' ";
        $strSql = "SELECT ".$arSqls["SELECT"]." FROM v_act_question WHERE ".$arSqls["WHERE"]." ";
        $dbRes = $DB->Query($strSql, false, "File: ".__FILE__."<br>Line: ".__LINE__);
        if ($dbRes){
            while ($arr_exp = $dbRes->Fetch()){ 
                $quest = $arr_exp;
                if ($withUserName) {
                    $userDict = static::getUserDict(array($arr_exp["CREATED_BY"]));
                    $quest["CREATED_BY_NAME"] = $userDict[$arr_exp["CREATED_BY"]];
                }                
                return $quest;
            }
        }
        return array();
    }

    public static function getAnswer($answerID, $withLikes=true, $withUserName=true, $arSelect='')
    {
        global $DB, $USER;
        if (empty($arSelect)) {
            $arSqls["SELECT"]=' ID,CONTENT,DATE_CREATE,DATE_UPDATE,CREATED_BY,REWARD ';
        } else {
            $arSqls["SELECT"] = ' '.$arSelect.' ';
        }

        $arSqls["WHERE"]=" ID='".$DB->ForSql($answerID,11)."' ";
        $strSql = "SELECT ".$arSqls["SELECT"]." FROM v_act_answer WHERE ".$arSqls["WHERE"]." ";
        $dbRes = $DB->Query($strSql, false, "File: ".__FILE__."<br>Line: ".__LINE__);
        $answers = array();

        if ($dbRes){
            while ($item = $dbRes->Fetch()){
                $ansID = $item["ID"];
                if ($withUserName) {
                    $userDict = static::getUserDict(array($item["CREATED_BY"]));
                    $item["CREATED_BY_NAME"] = $userDict[$item["CREATED_BY"]];
                }

                if ($withLikes) {
                    $likeRes = static::getLikes($ansID);
                    $item["LIKES"] = $likeRes["LIKES"];
                }

                return $item;
            }
        }
        return array();
    }

    public static function getAnswers($questionID, $withLikes=true)
    {
        global $DB, $USER;
        $arSqls["SELECT"]=' ID,QUESTION_ID,CONTENT,DATE_CREATE,DATE_UPDATE,CREATED_BY,REWARD ';
        $arSqls["WHERE"]=" QUESTION_ID='".$DB->ForSql($questionID,11)."' ";
        $strSql = "SELECT ".$arSqls["SELECT"]." FROM v_act_answer WHERE ".$arSqls["WHERE"]." ";
        $dbRes = $DB->Query($strSql, false, "File: ".__FILE__."<br>Line: ".__LINE__);
        $answers = array();
        $userIds = array();
        if ($dbRes){
            while ($item = $dbRes->Fetch()){
                $ansID = $item["ID"];
                $userIds[] = $item["CREATED_BY"];
                if ($withLikes) {
                    $likeRes = static::getLikes($ansID);
                    $item["LIKES"] = $likeRes["LIKES"];
                }                
                $answers[] = $item;
            }
        }
        $userDict = static::getUserDict($userIds);
        for($i = 0;$i<count($answers);$i++) {
            $answers[$i]["CREATED_BY_NAME"] = $userDict[$answers[$i]["CREATED_BY"]];
        }
        return $answers;
    }
    /**
     * 创建问题
     *
     * @param int $answerID 回答ID
     * @return array("OK"=>true, "LIKES"=> array(), "ERROR"=>"")
     * @static
     */
    public static function getLikes($answerID)
    {
        $res = array("OK"=>true, "LIKES"=> array(), "ERROR"=>"");
        global $USER, $APPLICATION, $DB;

        // if (!$USER->IsAuthorized()) {
        //     $res["OK"] = false;
        //     $res["ERROR"] = "需要登录";
        //     return $res;
        // }

        if (!$answerID) {
            $res["OK"] = false;
            $res["ERROR"] = "非法答案:"+$answerID;
            return $res;
        }

        $arSqls["SELECT"]=' USER_ID ';
        $arSqls["WHERE"]=" ANSWER_ID='".$DB->ForSql($answerID,11)."' ";
        $strSql = "SELECT ".$arSqls["SELECT"]." FROM v_act_like WHERE ".$arSqls["WHERE"]." ";
        $dbRes = $DB->Query($strSql, false, "File: ".__FILE__."<br>Line: ".__LINE__);
        if ($dbRes){
            while ($item = $dbRes->Fetch()){ 
                $res["LIKES"][] = $item["USER_ID"];
            }
        }

        return $res;

    }
    /**
     * 创建问题
     *
     * @param array $arFields 问题字段列表。TITLE,CONTENT,REWARD
     * @return array("OK"=>true, "QUESTION_ID"=>0, "ERROR"=>"")
     * @static
     */
    public static function createQuestion($arFields=array())
    {
        global $USER, $APPLICATION, $DB;
        $res = array("OK"=>true, "QUESTION_ID"=>0, "ERROR"=>"");

        if (!$USER->IsAuthorized()) {
            $res["OK"] = false;
            $res["ERROR"] = "需要登录";
            return $res;
        }

        if (!$arFields["TITLE"]) {
            $res["OK"] = false;
            $res["ERROR"] = "缺少标题";
            return $res;
        }

        if (!$arFields["CONTENT"]) {
            $res["OK"] = false;
            $res["ERROR"] = "缺少内容: "+print_r($arFields["CONTENT"], true);
            return $res;
        }

        $rewards = 0.00;
        if ($arFields["REWARD"]) {
            $rewards = FloatVal($arFields["REWARD"]);
        }

        $userID = $USER->GetID();
        $fromUser = $userID;
        $toUser = $userID;
        $strSql = "INSERT INTO v_act_question (TITLE,CONTENT,DATE_CREATE,DATE_UPDATE,CREATED_BY,REWARD) VALUES (
             '".$arFields["TITLE"]."'
            , '".$arFields["CONTENT"]."'
            , ".$DB->CurrentTimeFunction()." 
            , ".$DB->CurrentTimeFunction()." 
            , '".$DB->ForSql($userID,11)."'
            , ".$rewards." 
            )";
        $DB->Query($strSql, false, "FILE: ".__FILE__."<br> LINE: ".__LINE__);
        $questID = IntVal($DB->LastID());

        if ($questID > 0) {
            $res["QUESTION_ID"] = $questID;
            static::addNotify("question", $fromUser, $toUser, "创建了问题:".$arFields["TITLE"].";奖赏:¥".$arFields["REWARD"]);
            return $res;
        }
        $res["OK"] = false;
        $res["ERROR"] = "创建问题失败";

        return $res;
    }

    private static function addNotify($eventType, $fromUser, $toUser, $message) {

        CModule::IncludeModule("im");

        $arMessageFields = array(
            "MESSAGE_TYPE" => IM_MESSAGE_SYSTEM,
            "TO_USER_ID" => intval($toUser),
            "FROM_USER_ID" => intval($fromUser),
            "NOTIFY_TYPE" => IM_NOTIFY_FROM,
            "NOTIFY_MODULE" => "main",
            "NOTIFY_EVENT" => $eventType, //"rating_vote",
            //"NOTIFY_TAG" => "RATING|".($arParams['VALUE'] >= 0 ? "" : "DL|").$arParams['ENTITY_TYPE_ID']."|".$arParams['ENTITY_ID'],
            "NOTIFY_MESSAGE" => $message,
            "NOTIFY_MESSAGE_OUT" => $message
        );

        CIMNotify::Add($arMessageFields);

    }

    public static function addAnswer($questionID, $arFields=array())
    {
        global $USER, $APPLICATION, $DB;
        $res = array("OK"=>true, "ANSWER_ID"=>0, "ERROR"=>"");

        if (!$USER->IsAuthorized()) {
            $res["OK"] = false;
            $res["ERROR"] = "需要登录";
            return $res;
        }

        if ($questionID <= 0) {
            $res["OK"] = false;
            $res["ERROR"] = "缺少问题";
            return $res;
        }

        if (!$arFields["CONTENT"]) {
            $res["OK"] = false;
            $res["ERROR"] = "缺少内容";
            return $res;
        }

        $userID = $USER->GetID();
        $fromUser = $userID;
        $toUser = $userID;
        $questionTitle="";
        $quest = static::getQuestion($questionID, false, "TITLE, CREATED_BY");
        if ($quest) {
            $questionTitle = $quest["TITLE"];
            $toUser = IntVal($quest["CREATED_BY"]);
        }


        $strSql = "INSERT INTO v_act_answer (QUESTION_ID,CONTENT,DATE_CREATE,DATE_UPDATE,CREATED_BY,REWARD) VALUES (
             '".$DB->ForSql($questionID,11)."'
            , '".$arFields["CONTENT"]."'
            , ".$DB->CurrentTimeFunction()." 
            , ".$DB->CurrentTimeFunction()." 
            , '".$DB->ForSql($userID,11)."'
            , 0.00 
            )";
        $DB->Query($strSql, false, "FILE: ".__FILE__."<br> LINE: ".__LINE__);
        $answerID = IntVal($DB->LastID());

        if ($answerID > 0) {
            $res["ANSWER_ID"] = $answerID;
            static::addNotify("answer", $fromUser, $toUser, "回答了一道问题:".$questionTitle);
            return $res;
        }
        $res["OK"] = false;
        $res["ERROR"] = "创建问题失败";
        return $res;
    }

    public static function addLike($answerID)
    {
        $res = array("OK"=>true, "ERROR"=>"");
        global $USER, $APPLICATION, $DB;

        if (!$answerID) {
            $res["OK"] = false;
            $res["ERROR"] = "非法答案:"+$answerID;
            return $res;
        }

        if (!$USER->IsAuthorized()) {
            $res["OK"] = false;
            $res["ERROR"] = "需要登录";
            return $res;
        }

        $userID = $USER->GetID();
        $fromUser = $userID;
        $toUser = $userID;
        $arSqls["SELECT"]=' USER_ID ';
        $arSqls["WHERE"]=" ANSWER_ID='".$DB->ForSql($answerID,11)."' AND USER_ID='".$DB->ForSql($userID,11)."' ";
        $strSql = "SELECT ".$arSqls["SELECT"]." FROM v_act_like WHERE ".$arSqls["WHERE"]." ";
        $dbRes = $DB->Query($strSql, false, "File: ".__FILE__."<br>Line: ".__LINE__);

        if ($dbRes){
            while ($dbRes->Fetch()){
                return $res;
            }
        }

        $answer = static::getAnswer($answerID, false, "CREATED_BY");
        if ($answer) {
            $toUser = $answer["CREATED_BY"];
        }

        $strSql = "INSERT INTO v_act_like (ANSWER_ID,USER_ID) VALUES (
             '".$DB->ForSql($answerID,11)."'
            , '".$DB->ForSql($userID,11)."'
            )";
        $DB->Query($strSql, false, "FILE: ".__FILE__."<br> LINE: ".__LINE__);
        // $lastID = $DB->LastID();
        // if (!$lastID) {
        //     $res["OK"] = false;
        //     $res["ERROR"] = "出错:"+print_r($lastID, true);
        //     return $res;
        // }
        static::addNotify("likes", $fromUser, $toUser, "对一个答案表示了喜欢。");
        return $res;
    }

    /**
     * 创建问题
     *
     * @param array $questID 问题ID
     * @param array $arFields 问题字段列表。TITLE,CONTENT,REWARD
     * @return array("OK"=>true, "QUESTION_ID"=>0, "ERROR"=>"")
     * @static
     */
    public static function updateQuestion($questID, $arFields = array())
    {
        $res = array("OK"=>true, "QUESTION_ID"=>$questID, "ERROR"=>"");
        global $USER, $APPLICATION, $DB;
        if (!$USER->IsAuthorized()) {
            $res["OK"] = false;
            $res["ERROR"] = "需要登录";
            return $res;
        }

        $userId = $USER->GetID();

        $arSqls["SELECT"]=' ID,CREATED_BY ';
        $arSqls["WHERE"]=" ID='".$DB->ForSql($questID,11)."' ";
        $strSql = "SELECT ".$arSqls["SELECT"]." FROM v_act_question WHERE ".$arSqls["WHERE"]." ";
        $dbRes = $DB->Query($strSql, false, "File: ".__FILE__."<br>Line: ".__LINE__);
        $ques_info = array();
        if ($dbRes){
            while ($arr_exp = $dbRes->Fetch()){ 
                $ques_info['CREATED_BY']=$arr_exp['CREATED_BY'];
            }
        }

        if(empty($ques_info)){
            $res["OK"] = false;
            $res["ERROR"] = '没找到该问题';
            return $res;
        }

        if($ques_info['CREATED_BY']!=$userId){
            $res["OK"] = false;
            $res["ERROR"] = '您不是问题的创建者';
            return $res;
        }

        $strSql = "UPDATE v_act_question SET DATE_UPDATE=".$DB->CurrentTimeFunction()."";

        if(!empty($arFields["TITLE"])){
            $strSql .= " ,TITLE='".$arFields["TITLE"]."' ";
        }
        if(!empty($arFields["CONTENT"])){
            $strSql .= " ,CONTENT='".$arFields["CONTENT"]."' ";
        }
        if(!empty($arFields["REWARD"])){
            $strSql .= " ,REWARD='".$arFields["REWARD"]."' ";
        }


        $strSql .= " where ID='".$DB->ForSql($questID,11)."' AND CREATED_BY='".$DB->ForSql($userId,11)."' ";

        $DB->Query($strSql, false, "FILE: ".__FILE__."<br> LINE: ".__LINE__);

        return $res;

    }

    public static function updateAnswer($ID, $arFields)
    {
        $res = array("OK"=>true, "ANSWER_ID"=>$ID, "ERROR"=>"");
        global $USER, $APPLICATION, $DB;
        if (!$USER->IsAuthorized()) {
            $res["OK"] = false;
            $res["ERROR"] = "需要登录";
            return $res;
        }

        $userId = $USER->GetID();
        $fromUser = $userId;
        $toUser = $userId;

        $arSqls["SELECT"]=' ID,CREATED_BY,REWARD,QUESTION_ID ';
        $arSqls["WHERE"]=" ID='".$DB->ForSql($ID,11)."' ";
        $strSql = "SELECT ".$arSqls["SELECT"]." FROM v_act_answer WHERE ".$arSqls["WHERE"]." ";
        $dbRes = $DB->Query($strSql, false, "File: ".__FILE__."<br>Line: ".__LINE__);
        $info = array();
        $oldRewards = 0.0;
        if ($dbRes){
            while ($arr_exp = $dbRes->Fetch()){ 
                $info['CREATED_BY']=$arr_exp['CREATED_BY'];
                $oldRewards = FloatVal($arr_exp['REWARD']);
                $quest = static::getQuestion(IntVal($arr_exp["QUESTION_ID"]), false, "ID,CREATED_BY");
                if (!$quest) {
                    $res["OK"] = false;
                    $res["ERROR"] = '未找到答案对应的问题';
                    return $res;
                } 
                if($quest['CREATED_BY']!=$userId){
                    $res["OK"] = false;
                    $res["ERROR"] = '您不是问题的创建者';
                    return $res;
                }
                $toUser = $info['CREATED_BY'];
            }
        }

        if(empty($info)){
            $res["OK"] = false;
            $res["ERROR"] = '没找到该答案';
            return $res;
        }



        $strSql = "UPDATE v_act_answer SET DATE_UPDATE=".$DB->CurrentTimeFunction()."";

        if(!empty($arFields["CONTENT"])){
            $strSql .= " ,CONTENT='".$arFields["CONTENT"]."' ";
        }
        if(!empty($arFields["REWARD"])){
            $strSql .= " ,REWARD='".$arFields["REWARD"]."' ";
        }


        $strSql .= " where ID='".$DB->ForSql($ID, 11)."' AND CREATED_BY='".$DB->ForSql($userId,11)."' ";

        $DB->Query($strSql, false, "FILE: ".__FILE__."<br> LINE: ".__LINE__);

        if (abs($oldRewards-FloatVal($arFields["REWARD"])) > 0.01) {
            static::addNotify("answer", $fromUser, $toUser, "对一个回答进行了赞赏,金额为:¥".StrVal($arFields["REWARD"]));
        }

        return $res;
    }
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值