PHP后端接口框架和逻辑处理框架之间的数据互通
本地环境:
1.(逻辑框架) 先封装一个公用调用方法类 CommonFun.php
class CommonFun {
public static function postRestful ( $resturl , $postData = array ( ) , $params = array ( ) ) {
$requestUrl = self: : createCommonUrl ( $resturl , $params ) ;
$data = self: : vpost ( $requestUrl , $postData ) ;
return json_decode ( $data , true ) ;
}
private static function createCommonUrl ( $rest , $params = array ( ) ) {
$t = time ( ) ;
$sign = self: : encryptAppKey ( array ( 'appid' = > Yii: : $app - > params [ 'interAppId' ] , 't' = > $t , 'secret' = > Yii: : $app - > params [ 'interAppSecret' ] ) ) ;
$param = "appid=" . Yii: : $app - > params [ 'interAppId' ] . "&sign=" . $sign . "&t=" . $t ;
$requestUrl = Yii: : $app - > params [ 'initUrl' ] . '?s=' . $rest ;
$requestUrl . = '&' . $param ;
if ( $params ) {
$requestUrl . = implode ( '&' , $params ) ;
}
return $requestUrl ;
}
private static function encryptAppKey ( $params ) {
ksort ( $params ) ;
$paramsStrExceptSign = '' ;
foreach ( $params as $val ) {
$paramsStrExceptSign . = $val ;
}
return substr ( md5 ( $paramsStrExceptSign ) , 5 , 17 ) ;
}
public static function vpost ( $url , $data ) {
$curl = curl_init ( ) ;
curl_setopt ( $curl , CURLOPT_URL , $url ) ;
curl_setopt ( $curl , CURLOPT_SSL_VERIFYPEER , FALSE ) ;
curl_setopt ( $curl , CURLOPT_SSL_VERIFYHOST , FALSE ) ;
curl_setopt ( $curl , CURLOPT_USERAGENT , 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)' ) ;
curl_setopt ( $curl , CURLOPT_POST , 1 ) ;
curl_setopt ( $curl , CURLOPT_POSTFIELDS , $data ) ;
curl_setopt ( $curl , CURLOPT_TIMEOUT , 30 ) ;
curl_setopt ( $curl , CURLOPT_HEADER , 0 ) ;
curl_setopt ( $curl , CURLOPT_RETURNTRANSFER , 1 ) ;
$tmpInfo = curl_exec ( $curl ) ;
if ( curl_errno ( $curl ) ) {
echo 'Errno' . curl_error ( $curl ) ;
}
curl_close ( $curl ) ;
return $tmpInfo ;
}
}
2. (逻辑框架)创建请求接口
CommonFun: : postRestful ( 'App/user/add' , [ ] ) ;
3. (接口框架)接收请求并返回数据
namespace App\ Api ;
class user extends Api {
public function add ( ) {
$user_id = $this - > $user_id ;
$sql = "select * from user where user_id = { $user_id } " ;
$res_data = $this - > query ( $sql ) ;
return $res_data ;
}
}