检查API中的必需参数

时间:2014-11-14 08:34:40

标签: php codeigniter api validation

我正在构建一个API,需要一些必要的参数才能发布到它。有大约15个必须参数应该传递给api,我想向开发人员显示相关错误,如果有任何参数丢失,如“可能不处理;电子邮件参数缺失“。

我已经实现了逻辑,但它运行不正常并且似乎编码过多代码。这是当前的方法

 if ($data['email'] AND array_key_exists('email', $data)) {
                if (!validateEmail($data['email'])) {
                    $transaction_error = 'Invalid email';
                }
            } else {
                $transaction_error = 'Parameter email is missing';
            }
            if (!($data['addr'] AND array_key_exists('addr', $data))) {
                $transaction_error= 'Parameter addr is missing';
            }
            if (array_key_exists('show_shipping_addr', $data)) {
                if (!verifyBinary($data['show_shipping_addr'])) {
                    $transaction_error = 'Invalid show_shipping_addr';
                }
            } else {
                $transaction_error = 'Parameter show_shipping_addr is missing';
            }
            if (array_key_exists('authorize_user', $data)) {
                if (!verifyBinary($data['authorize_user'])) {
                    $transaction_error = 'Invalid authorize_user';
                }
            } else {
                $transaction_error = 'Parameter authorize_user is missing';
            }
            if ($data['mobileNo'] AND array_key_exists('mobileNo', $data)) {
                if (!validateMobileNo($data['mobileNo'])) {
                    $transaction_error = 'Invalid mobileNo';
                }
            } else {
                $transaction_error = 'Parameter mobileNo is missing';
            }
            if ($data['currency_code'] AND array_key_exists('currency_code', $data)) {
                if (!validateCurrencyCode($data['currency_code'])) {
                    $transaction_error = 'Invalid currency_code';
                }
            } else {
                $transaction_error = 'Parameter currency_code is missing';
            }
            if ($data['checksum_method'] AND array_key_exists('checksum_method', $data)) {
                if (!validateChecksumMethod($data['checksum_method'])) {
                    $transaction_error = 'Invalid checksum_method';
                }
            } else {
                $transaction_error = 'Parameter checksum_method is missing';
            }
            if ($data['zipcode'] AND array_key_exists('zipcode', $data)) {
                if (!validateZipCode($data['zipcode'])) {
                    $transaction_error = 'Invalid zipcode';
                }
            } else {
                $errors[$i++] = 'Parameter zipcode is missing';
            }
            if ($data['f_name'] AND array_key_exists('f_name', $data)) {
                if (!validateAlphaString($data['f_name'])) {
                    $transaction_error = 'Invalid name';
                }
            } else {
                $transaction_error = 'Parameter f_name is missing';
            }
            if ($data['state'] AND array_key_exists('state', $data)) {
                if (!validateAlphaString($data['state'])) {
                    $transaction_error = 'Invalid state';
                }
            } else {
                $transaction_error = 'Parameter state is missing';
            }
            if ($data['country'] AND array_key_exists('country', $data)) {
                if (!validateAlphaString($data['country'])) {
                    $transaction_error = 'Invalid country';
                }
            } else {
                $transaction_error = 'Parameter country is missing';
            }
            if ($data['city'] AND array_key_exists('city', $data)) {
                if (!validateAlphaString($data['city'])) {
                    $transaction_error = 'Invalid city';
                }
            } else {
                $transaction_error = 'Parameter city is missing';
            }
            /* Validation of mandatory parameters ends here */
            /* Validation of optional parameters starts here
             *shipping_email
             *shipping_mobileNo
             *shipping_zipcode
             *l_name
             *shipping_addr 
             *shipping_city
             *shipping_state
             *shipping_country
             *surl
             *furl
             *rurl
             */
            if (array_key_exists('l_name', $data)) {
                if (!validateAlphaString($data['l_name'])) {
                    $transaction_error = 'Invalid l_name';
                }
            }
            if (array_key_exists('shipping_addr', $data)) {
                if (!$data['shipping_addr']) {
                    $transaction_error = 'Parameter shipping_addr is missing';
                }
            }
            if (array_key_exists('shipping_mobileNo', $data)) {
                if (!validateMobileNo($data['shipping_mobileNo'])) {
                    $transaction_error = 'Invalid shipping_mobileNo';
                }
            }
            if (array_key_exists('shipping_city', $data)) {
                if (!validateAlphaString($data['shipping_city'])) {
                    $transaction_error = 'Invalid shipping_city';
                }
            }
            if (array_key_exists('shipping_state', $data)) {
                if (!validateAlphaString($data['shipping_state'])) {
                    $transaction_error = 'Invalid shipping_state';
                }
            }
            if (array_key_exists('shipping_country', $data)) {
                if (!validateAlphaString($data['shipping_country'])) {
                    $transaction_error = 'Invalid shipping_country';
                }
            }
            if (array_key_exists('shipping_zipcode', $data)) {
                if (!validateZipCode($data['shipping_zipcode'])) {
                    $transaction_error = 'Invalid shipping_zipcode';
                }
            }

            if(isset($api_error)) // IF there are API error pages are rendered
            {
                $api_error_array['api_error'] = $api_error;
                $this->render_api_errors($api_error_array);
            }
            else if (isset($transaction_error)) { //If there are transactional errors,user is redirected back to mercahnt response url
                $api_data = $this->paymentgateway->getAPIData($data['app_used'], $data['apikey']);
                $data['response_url'] = $api_data['response_url'];
                $data['transaction_errors'] = $transaction_error;
                $this->paymentgateway->logApiRequest($data['app_used'], $transaction_error, 'Notice', $data['ip_address'], $data['ip_address_customer']);
                $this->redirect_transactional_error($data);
            } else {
                $this->process($data); //Calls the process function when everything is done
            }

我有一些必填字段和一些非必填字段。如果设置了非必填字段,则需要检查它们的有效性。

请建议一种方便的方式来验证帖子请求,而不会使代码变重。我已经看到以下代码

if($_SERVER['REQUEST_METHOD'] != "POST")
    die("Error: Wrong method");
$fields = array("f1", "f2", "f3", "f4");
$field_names = array("field1", "field2", "field3", "field4");
$length = count($fields);
$missing_input = array();
for($i = 0; $i < $length; $i++)
    if(empty($_POST[$fields[$i]]))
        $missing_input[] = $field_names[$i];
if(!empty($missing_input))
    die("Error: " . implode(", ", $missing_input)");

来自SO,这是有道理的。有些人建议我在API中验证强制参数并在此基础上显示相关错误的最佳实践吗?我可以创建一个单独的函数来检查参数并显示错误?

3 个答案:

答案 0 :(得分:1)

您可以创建一个需要强制/验证的字段名称数组

$validate = array(
  'username' => array('mandatory' => true, 'regex' => '/^[a-z0-9_-]{3,16}$/'),
  'password' => array('mandatory' => true, 'regex' => null),
  // Same like the above example you can create all validation 
)

$missing_input = array();

foreach($_POST as $key => $val){
  $mandatory = isset($validate[$key]) ? $validate[$key] : false;
  if($mandatory && !trim($val)){
    // Manage error here
    $missing_input[] = $key;
  } 
  // Same like above get the regex and validate the field here and manage the error
}

// Return / Print error array
if(!empty($missing_input))
die("Error: " . implode(", ", $missing_input)");

您还可以在$ validate数组中定义最小和最大限制,并在foreach循环内部相应地验证,验证您的需求的简单逻辑。

答案 1 :(得分:1)

$validate = array(
  'username' => array('mandatory' => true, 'regex' => '/^[a-z0-9_-]{3,16}$/'),
  'password' => array('mandatory' => true, 'regex' => null),
  // Same like the above example you can create all validation 
)

$missing_input = array();
$invalid_input = array();

foreach($_POST as $key => $val){  
  $mandatory = isset($validate[$key]['mandatory']) ? $validate[$key]['mandatory'] : false;
  $regex = isset($validate[$key]['regex']) ? $validate[$key]['regex'] : null;
  if($mandatory && !trim($val)){
    // Manage error here
    $missing_input[] = $key;
  } else if($regex != null && trim($val)){
                            if(!preg_match($regex,$val)){
                                $invalid_input[] = $key;
                            }
        } 

}

// Return / Print error array
if(!empty($missing_input))
die("Missing Inputs: " . implode(", ", $missing_input). "Invalid Inputs" . implode(", ", $invalid_input));

答案 2 :(得分:0)

$data = array('addr'=>'test','mobileNo'=>'test');//only for test

$dataMandatory = array('email'=>1,'addr'=>1,'mobileNo'=>1);//array of mandatory field
$transaction_error=array();//array to contain error

foreach($data as $key=>$value){
    if (array_key_exists($key, $dataMandatory)) {
        unset($dataMandatory[$key]);
        if(!call_user_func('validate'.ucfirst($key), $value)){//i call valide method
            $transaction_error[] = 'Invalid '.$key;
        }
    }
}
if(count($dataMandatory)!==0){
    $transaction_error[] = 'Parameter missing : '.implode(',',array_flip ($dataMandatory));
}

优点:仅在数组上进行更改以添加必填字段,无重复代码

缺点:你无法改变功能名称(valideKey)和自定义处理