经过微信开发使用到的curl提交xml数据笔记,用curl的post发送xml,接收返回的xml数据,并解析xml为数组
$url = "http://localhost/response.php";
$xml = '<xml><AppId>wxf8b4f85f3a794e77</AppId><ErrorType>1001</ErrorType><Description>错误描述</Description><AlarmContent>transaction_id=33534453534</AlarmContent><TimeStamp>1393860740</TimeStamp><AppSignature>f8164781a303f4d5a944a2dfc68411a8c7e4fbea</AppSignature><SignMethod>sha1</SignMethod></xml>'; /** * 以post方式提交xml到对应的接口url * @param string $xml 需要post的xml数据 * @param string $url url * @param bool $useCert 是否需要证书,默认不需要 * @param int $second url执行超时时间,默认30s * @throws WxPayException */ private function _postXmlCurl($xml, $url, $useCert = false, $second = 30) { $ch = curl_init(); //设置超时 curl_setopt($ch, CURLOPT_TIMEOUT, $second); $header[] = "Content-type: text/xml";//定义content-type为xml curl_setopt($ch, CURLOPT_HEADER, 0); //定义是否显示状态头 1:显示 ; 0:不显示 curl_setopt($ch, CURLOPT_HTTPHEADER, $header);//定义请求类型 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//定义是否直接输出返回流 这里要注意,如果为0则输入结果为 true|false //如果有配置代理这里就设置代理 if(WxPayConfig::CURL_PROXY_HOST != "0.0.0.0" && WxPayConfig::CURL_PROXY_PORT != 0){ curl_setopt($ch,CURLOPT_PROXY, WxPayConfig::CURL_PROXY_HOST); curl_setopt($ch,CURLOPT_PROXYPORT, WxPayConfig::CURL_PROXY_PORT); } curl_setopt($ch,CURLOPT_URL, $url); curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE); curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);//严格校验 if($useCert == true){ //设置证书 //使用证书:cert 与 key 分别属于两个.pem文件 curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM'); curl_setopt($ch,CURLOPT_SSLCERT, WxPayConfig::SSLCERT_PATH); curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM'); curl_setopt($ch,CURLOPT_SSLKEY, WxPayConfig::SSLKEY_PATH); } //post提交方式 curl_setopt($ch, CURLOPT_POST, TRUE); curl_setopt($ch, CURLOPT_POSTFIELDS, $xml); //运行curl $data = curl_exec($ch); //返回结果 if($data){ curl_close($ch); libxml_disable_entity_loader(true); $xmsToArray = json_decode(json_encode(simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA)), true); //接收到的xml数据转换为数组 return $xmsToArray; } else { $error = curl_errno($ch); curl_close($ch); throw new WxPayException("curl出错,错误码:$error"); } }
接收处理,比如上面请求的接口地址,http://localhost/response.php :代码如下
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
评论已关闭。