![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <?php 2 3 /** 4 * API 5 * User: sgfoot 6 * Date: 2017/3/20 7 * Time: 18:05 8 */ 9 class apiCurl 10 { 11 private $config = array( 12 'key' => '7D86A79BA5C4C278E5264D5E910B3A64', 13 ); 14 public function execute($url, $params) 15 { 16 $baseParams = $this->getParams(); 17 $apiPrams = array_merge($baseParams, $params); 18 $apiPrams['sign'] = $this->getSign($apiPrams); 19 $xml = $this->arrayToXml($apiPrams); 20 $xml_result = Cpost($url, $xml); 21 $result = $this->xmlToArray($xml_result); 22 return $result; 23 } 24 25 /** 26 * 获取基础参数 27 * @author: wzl 28 * @date: 2017 29 * @return array 30 */ 31 protected function getParams() 32 { 33 $params = array( 34 'nonce_str' => $this->getNonce(), 35 'sign_type' => 'MD5', 36 ); 37 return $params; 38 } 39 40 /** 41 * 作用:生成签名 42 */ 43 protected function getSign($Obj) 44 { 45 foreach ($Obj as $k => $v) { 46 $Parameters[$k] = $v; 47 } 48 //签名步骤一:按字典序排序参数 49 ksort($Parameters); 50 $String = $this->formatBizQueryParaMap($Parameters, false); 51 //echo '【string1】'.$String.'</br>'; 52 //签名步骤二:在string后加入KEY 53 $String = $String . "&key=" . $this->config['key']; 54 //echo "【string2】".$String."</br>"; 55 //签名步骤三:MD5加密 56 $String = md5($String); 57 //echo "【string3】 ".$String."</br>"; 58 //签名步骤四:所有字符转为大写 59 $result_ = strtoupper($String); 60 //echo "【result】 ".$result_."</br>"; 61 return $result_; 62 } 63 64 /** 65 * 作用:格式化参数,签名过程需要使用 66 */ 67 protected function formatBizQueryParaMap($paraMap, $urlencode) 68 { 69 $buff = ""; 70 ksort($paraMap); 71 foreach ($paraMap as $k => $v) { 72 if ($urlencode) { 73 $v = urlencode($v); 74 } 75 $buff .= $k . "=" . $v . "&"; 76 } 77 $reqPar = ''; 78 if (strlen($buff) > 0) { 79 $reqPar = substr($buff, 0, strlen($buff) - 1); 80 } 81 return $reqPar; 82 } 83 /** 84 * 作用:将xml转为array 85 */ 86 protected function xmlToArray($xml) 87 { 88 //将XML转为array 89 $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true); 90 return $array_data; 91 } 92 /** 93 * 作用:array转xml 94 */ 95 protected function arrayToXml($arr) 96 { 97 $xml = "<xml>"; 98 foreach ($arr as $key=>$val) 99 { 100 if (is_numeric($val)) 101 { 102 $xml.="<".$key.">".$val."</".$key.">"; 103 104 } 105 else 106 $xml.="<".$key."><![CDATA[".$val."]]></".$key.">"; 107 } 108 $xml.="</xml>"; 109 return $xml; 110 } 111 }