生成签名,随机字符串,XML转为数组,数组转XML,json封装,获取IP地址

 
/*
* ******生成签名*********
*/
private function getSign($params)
{
ksort($params); //将参数数组按照参数名ASCII码从小到大排序
foreach ($params as $key => $item) {
if (!empty($item)) { //剔除参数值为空的参数
$newArr[] = $key . '=' . $item; // 整合新的参数数组
}
}
$stringA = implode("&", $newArr); //使用 & 符号连接参数
$stringSignTemp = $stringA . "&key=" . "key";
// key是在商户平台API安全里自己设置的
$stringSignTemp = hash_hmac("sha256",$stringSignTemp,"key"); //将字符串进行MD5加密或hash_hmac加密
$sign = strtoupper($stringSignTemp); //将所有字符转换为大写
return $sign;
}


/*
* ***生成随机字符串,微信所需参数!
*/
function rand_code()
{
$str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';//62个字符
$str = str_shuffle($str);
$str = substr($str, 0, 32);
return $str;
}
/*
* ******传输给微信的参数要组成xml格式发送,传入参数数组
*/
public function ToXml($data = array())
{
if (!is_array($data) || count($data) <= 0) {
return '数组异常';
}
$xml = "<xml>";
foreach ($data as $key => $val) {
if (is_numeric($val)) {
$xml .= "<" . $key . ">" . $val . "</" . $key . ">";
} else {
$xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
}
}
$xml .= "</xml>";
return $xml;
}
 
/*
* ******将xml数据转换为数组,接收微信返回数据时用到*********
*/
public function FromXml($xml)
{
if (!$xml) {
echo "xml数据异常!";
}
//将XML转为array
//禁止引用外部xml实体
libxml_disable_entity_loader(true);
$data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);

return $data;
}
/**
* api 数据返回
* @param [int] $code [结果码 200:正常/4**数据问题/5**服务器问题]
* @param [string] $msg [接口要返回的提示信息]
* @param [array] $data [接口要返回的数据]
* @return [string] [最终的json数据]
*/
 function return_msg($code, $msg = '', $data = []) {
/*********** 组合数据 ***********/
$return_data['code'] = $code;
$return_data['msg'] = $msg;
if(empty($data)){
$return_data['data'] = "";
}else{
$return_data['data'] = $data;
}
/*********** 返回信息并终止脚本 ***********/
// echo json_encode($return_data,JSON_UNESCAPED_UNICODE);die;
echo str_replace(':null',':""',json_encode($return_data,JSON_UNESCAPED_UNICODE));die;//JSON_UNESCAPED_UNUCODE 禁止中文转换
}


/*
* 获取当前用户注册的ip
*/

function get_client_ip($type = 0)
{
$type = $type ? 1 : 0;
static $ip = NULL;
if ($ip !== NULL) return $ip[$type];
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
$pos = array_search('unknown', $arr);
if (false !== $pos) unset($arr[$pos]);
$ip = trim($arr[0]);
} elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (isset($_SERVER['REMOTE_ADDR'])) {
$ip = $_SERVER['REMOTE_ADDR'];
}
// IP地址合法验证
$long = sprintf("%u", ip2long($ip));
$ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
return $ip[$type];
}

猜你喜欢

转载自www.cnblogs.com/Dgaozhen/p/9963428.html
今日推荐