<?php
/**
* 关于微信退款的说明
* 1.微信退款要求必传证书,需要到https://pay.weixin.qq.com 账户中心->账户设置->API安全->下载证书,证书路径在第119行和122行修改
* 2.错误码参照 :https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_4
*/
header('Content-type:text/html; Charset=utf-8');
$mchid = ''; //微信支付商户号 PartnerID 通过微信支付商户资料审核后邮件发送
$appid = ''; //微信支付申请对应的公众号的APPID
$apiKey = ''; //https://pay.weixin.qq.com 帐户设置-安全设置-API安全-API密钥-设置API密钥
$orderNo = ''; //商户订单号(商户订单号与微信订单号二选一,至少填一个)
$wxOrderNo = ''; //微信订单号(商户订单号与微信订单号二选一,至少填一个)
$totalFee = 0.20; //订单金额,单位:元
$refundFee = 0.20; //退款金额,单位:元
$refundNo = 'refund_'.uniqid(); //退款订单号(可随机生成)
$wxPay = new WxpayService($mchid,$appid,$apiKey);
$result = $wxPay->doRefund($totalFee, $refundFee, $refundNo, $wxOrderNo,$orderNo);
if($result===true){
echo 'refund success';exit();
}
echo 'refund fail';
class WxpayService
{
protected $mchid;
protected $appid;
protected $apiKey;
public $data = null;
public function __construct($mchid, $appid, $key)
{
$this->mchid = $mchid; //https://pay.weixin.qq.com 产品中心-开发配置-商户号
$this->appid = $appid; //微信支付申请对应的公众号的APPID
$this->apiKey = $key; //https://pay.weixin.qq.com 帐户设置-安全设置-API安全-API密钥-设置API密钥
}
/**
* 退款
* @param float $totalFee 订单金额 单位元
* @param float $refundFee 退款金额 单位元
* @param string $refundNo 退款单号
* @param string $wxOrderNo 微信订单号
* @param string $orderNo 商户订单号
* @return string
*/
public function doRefund($totalFee, $refundFee, $refundNo, $wxOrderNo='',$orderNo='')
{
$config = array(
'mch_id' => $this->mchid,
'appid' => $this->appid,
'key' => $this->apiKey,
);
$unified = array(
'appid' => $config['appid'],
'mch_id' => $config['mch_id'],
'nonce_str' => self::createNonceStr(),
'total_fee' => floatval($totalFee) * 100, //订单金额 单位 转为分
'refund_fee' => floatval($refundFee) * 100, //退款金额 单位 转为分
'sign_type' => 'MD5', //签名类型 支持HMAC-SHA256和MD5,默认为MD5
'transaction_id'=>$wxOrderNo, //微信订单号
'out_trade_no'=>$orderNo, //商户订单号
'out_refund_no'=>$refundNo, //商户退款单号
'refund_desc'=>'商品已售完', //退款原因(选填)
);
$unified['sign'] = self::getSign($unified, $config['key']);
$responseXml = $this->curlPost('https://api.mch.weixin.qq.com/secapi/pay/refund', self::arrayToXml($unified));
$unifiedOrder = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA);
if ($unifiedOrder === false) {
die('parse xml error');
}
print_r($unifiedOrder);
if ($unifiedOrder->return_code != 'SUCCESS') {
die($unifiedOrder->return_msg);
}
if ($unifiedOrder->result_code != 'SUCCESS') {
die($unifiedOrder->err_code);
}
return true;
}
public static function curlGet($url = '', $options = array())
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
if (!empty($options)) {
curl_setopt_array($ch, $options);
}
//https请求 不验证证书和host
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
public function curlPost($url = '', $postData = '', $options = array())
{
if (is_array($postData)) {
$postData = http_build_query($postData);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
if (!empty($options)) {
curl_setopt_array($ch, $options);
}
//https请求 不验证证书和host
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
//第一种方法,cert 与 key 分别属于两个.pem文件
//默认格式为PEM,可以注释
curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/apiclient_cert.pem');
//默认格式为PEM,可以注释
curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
curl_setopt($ch,CURLOPT_SSLKEY,getcwd().'/apiclient_key.pem');
//第二种方式,两个文件合成一个.pem文件
// curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/all.pem');
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
public static function createNonceStr($length = 16)
{
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$str = '';
for ($i = 0; $i < $length; $i++) {
$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
}
return $str;
}
public static function arrayToXml($arr)
{
$xml = "<xml>";
foreach ($arr as $key => $val) {
if (is_numeric($val)) {
$xml .= "<" . $key . ">" . $val . "</" . $key . ">";
} else
$xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
}
$xml .= "</xml>";
return $xml;
}
public static function getSign($params, $key)
{
ksort($params, SORT_STRING);
$unSignParaString = self::formatQueryParaMap($params, false);
$signStr = strtoupper(md5($unSignParaString . "&key=" . $key));
return $signStr;
}
protected static function formatQueryParaMap($paraMap, $urlEncode = false)
{
$buff = "";
ksort($paraMap);
foreach ($paraMap as $k => $v) {
if (null != $v && "null" != $v) {
if ($urlEncode) {
$v = urlencode($v);
}
$buff .= $k . "=" . $v . "&";
}
}
$reqPar = '';
if (strlen($buff) > 0) {
$reqPar = substr($buff, 0, strlen($buff) - 1);
}
return $reqPar;
}
}
?>
PHP 日志类
<?php
class Libs_Log_Logger {
const TRANSFER_ERROR = 'LOG转换失败,非LOG信息';
const LOG_FILENAME = 'output.log';
/**
* 本函数用于取代系统的error_log错误日志记录函数
* @param string|array|object|bool|int $log 需要记录的错误信息,可以是格式良好的任意类型
* @param string $filename 保存日志信息的文件名,默认存储路径为sites/app/storage/log/output.log
* @param bool $append 是否以追加的形式添加日志信息,默认追加
*/
public static function outputLog($log, $filename = self::LOG_FILENAME, $append = true) {
if (!plum_setmod_dir(PLUM_APP_LOG)) {
return;
}
$filename = PLUM_APP_LOG . '/' . $filename;
$mode = $append ? 'a' : 'w';
if (!($handler = @fopen($filename, $mode))) {
//文件流打开失败时触发错误,并退出
trigger_error('LOG日志文件打开失败', E_USER_WARNING);
return;
}
//获取调用跟踪
$trace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1);
$debug = self::log_format(array('file' => $trace[0]['file'], 'line' => $trace[0]['line']));
$info = self::log_format($log);
//开始写入
if (($write_byte = fwrite($handler, $debug.$info)) === false) {
$error_msg = 'LOG日志写入失败';
//检查磁盘空间
$free_space = disk_free_space(PLUM_APP_LOG);
//磁盘空间不足
if ($free_space && $write_byte > $free_space) {
$error_msg .= '磁盘空间不足';
}
//写入失败时,触发错误并退出
trigger_error($error_msg, E_USER_WARNING);
fclose($handler);
return;
}
//关闭文件流
fclose($handler);
}
/**
* 输出信息到控制台
*/
public static function outputConsoleLog($log) {
//非控制台调用直接退出
if (php_sapi_name() != 'cli') {
//die('请在控制台下执行脚本');
return;
}
$info = self::log_format($log);
fwrite(STDOUT, $info);
}
/**
* 返回格式化的LOG日志信息
* @param $log
* @return string
*/
private static function log_format($log) {
$log_type = 'Unknown';
if (is_array($log)) {
//数组进行json序列化
$log_type = 'Array';
$loginfo = self::json_encode_helper($log);
} else if (is_object($log)) {
$log_type = 'Object';
$loginfo = self::json_encode_helper($log);
} else if (is_string($log)) {
$log_type = 'String';
$loginfo = $log;
} else if (is_bool($log)) {
$log_type = 'Bool';
$loginfo = $log ? 'true' : 'false';
} else if (is_numeric($log)) {
$log_type = 'Number';
$loginfo = strval($log);
} else if (is_null($log)) {
$log_type = 'Null';
$loginfo = 'null';
} else {
$loginfo = strval($log);
}
//再一次判断,排查转换出错的情况
if (!is_string($loginfo)) {
$errno = json_last_error();
switch ($errno) {
default :
$loginfo = self::TRANSFER_ERROR.";错误号:{$errno};错误信息:".json_last_error_msg();
break;
}
}
//添加换行符
$loginfo .= "\n";
$format = "[".date('Y/m/d H:i:s', time())."] $log_type: $loginfo";
return $format;
}
/*
* utf8格式转换
*/
private static function utf8ize( $mixed ) {
if (is_array($mixed)) {
foreach ($mixed as $key => $value) {
$mixed[$key] = self::utf8ize($value);
}
} elseif (is_string($mixed)) {
//$mixed = mb_convert_encoding($mixed, "UTF-8", "UTF-8");
$mixed = utf8_encode($mixed);
} elseif (is_object($mixed)) {
foreach ($mixed as $key => $value) {
$mixed->$key = self::utf8ize($value);
}
}
return $mixed;
}
private static function json_encode_helper($var) {
switch (gettype($var)) {
case 'boolean':
return $var ? 'true' : 'false'; // Lowercase necessary!
case 'integer':
case 'double':
return $var;
case 'resource':
case 'string':
// Always use Unicode escape sequences (\u0022) over JSON escape
// sequences (\") to prevent browsers interpreting these as
// special characters.
$replace_pairs = array(
// ", \ and U+0000 - U+001F must be escaped according to RFC 4627.
'\\' => '\u005C',
'"' => '\u0022',
"\x00" => '\u0000',
"\x01" => '\u0001',
"\x02" => '\u0002',
"\x03" => '\u0003',
"\x04" => '\u0004',
"\x05" => '\u0005',
"\x06" => '\u0006',
"\x07" => '\u0007',
"\x08" => '\u0008',
"\x09" => '\u0009',
"\x0a" => '\u000A',
"\x0b" => '\u000B',
"\x0c" => '\u000C',
"\x0d" => '\u000D',
"\x0e" => '\u000E',
"\x0f" => '\u000F',
"\x10" => '\u0010',
"\x11" => '\u0011',
"\x12" => '\u0012',
"\x13" => '\u0013',
"\x14" => '\u0014',
"\x15" => '\u0015',
"\x16" => '\u0016',
"\x17" => '\u0017',
"\x18" => '\u0018',
"\x19" => '\u0019',
"\x1a" => '\u001A',
"\x1b" => '\u001B',
"\x1c" => '\u001C',
"\x1d" => '\u001D',
"\x1e" => '\u001E',
"\x1f" => '\u001F',
// Prevent browsers from interpreting these as as special.
"'" => '\u0027',
'<' => '\u003C',
'>' => '\u003E',
'&' => '\u0026',
// Prevent browsers from interpreting the solidus as special and
// non-compliant JSON parsers from interpreting // as a comment.
//'/' => '\u002F',
// While these are allowed unescaped according to ECMA-262, section
// 15.12.2, they cause problems in some JSON parsers.
"\xe2\x80\xa8" => '\u2028', // U+2028, Line Separator.
"\xe2\x80\xa9" => '\u2029', // U+2029, Paragraph Separator.
);
return '"' . strtr($var, $replace_pairs) . '"';
case 'array':
// Arrays in JSON can't be associative. If the array is empty or if it
// has sequential whole number keys starting with 0, it's not associative
// so we can go ahead and convert it as an array.
if (empty($var) || array_keys($var) === range(0, sizeof($var) - 1)) {
$output = array();
foreach ($var as $v) {
$output[] = self::json_encode_helper($v);
}
return '[ ' . implode(', ', $output) . ' ]';
}
// Otherwise, fall through to convert the array as an object.
case 'object':
$output = array();
foreach ($var as $k => $v) {
$output[] = self::json_encode_helper(strval($k)) . ':' . self::json_encode_helper($v);
}
return '{' . implode(', ', $output) . '}';
default:
return 'null';
}
}
}
PHP 微信支付-商家转账到零钱-单文件版
<?php
class App_Helper_WxTransfer
{
const AUTH_TAG_LENGTH_BYTE = 16;
/**
* @notes 商家转账到零钱
* @param $batch_no //提现订单号
* @param $left_money //提现金额 单位 元
* @param $user_openid //用户openID
* @param $withdraw_name //提现金额大于200,用户真实名字必填
* @return bool
* @throws \Exception
* @author ljj
* @date 2022/9/27 4:40 下午
*/
public static function transfer($appid,$mchid,$cert_client,$cert_key,$v3key,$batch_no, $left_money, $user_openid, $withdraw_name = '',$b_name,$b_remark,$t_remark)
{
$config = [
'app_id' => $appid,
'mch_id' => $mchid, //商户ID
'cert_client' => getcwd().$cert_client, //cert证书地址//绝对路径
'cert_key' => getcwd().$cert_key, //key支付证书绝对地址
];
//获取微信支付平台证书序列号(不是API证书序列号)
$url = 'https://api.mch.weixin.qq.com/v3/certificates';
$wx_cert = json_decode(self::https_request_without_wechatpay_serial($url, self::token($url, 'GET', array(), $config)),true);
//设置加密密钥v3 6efd7276408a3334c7fa3e740c3ec964
$associated_data = $wx_cert['data'][0]['encrypt_certificate']['associated_data'];
$nonce = $wx_cert['data'][0]['encrypt_certificate']['nonce'];
$ciphertext = $wx_cert['data'][0]['encrypt_certificate']['ciphertext'];
$wx_cert_public_key = self::decryptToString($v3key, $associated_data, $nonce, $ciphertext);
$wx_cert_sn = $wx_cert['data'][0]['serial_no'];
// Libs_Log_Logger::outputLog($wx_cert,"wx_transfer1");
//请求URL
$url = 'https://api.mch.weixin.qq.com/v3/transfer/batches';
//请求方式
$http_method = 'POST';
//请求参数
$data = [
'appid' => $config['app_id'], //申请商户号的appid或商户号绑定的appid(企业号corpid即为此appid)
'out_batch_no' => $batch_no, //商户系统内部的商家批次单号,要求此参数只能由数字、大小写字母组成,在商户系统内部唯一
'batch_name' => $b_name, //该笔批量转账的名称
'batch_remark' => $b_remark, //转账说明,UTF8编码,最多允许32个字符
'total_amount' => $left_money * 100, //转账金额单位为“分”。转账总金额必须与批次内所有明细转账金额之和保持一致,否则无法发起转账操作
'total_num' => 1, //一个转账批次单最多发起三千笔转账。转账总笔数必须与批次内所有明细之和保持一致,否则无法发起转账操作
'transfer_detail_list' => [
[ //发起批量转账的明细列表,最多三千笔
'out_detail_no' => $batch_no, //商户系统内部区分转账批次单下不同转账明细单的唯一标识,要求此参数只能由数字、大小写字母组成
'transfer_amount' => $left_money * 100, //转账金额单位为分
'transfer_remark' => $t_remark, //单条转账备注(微信用户会收到该备注),UTF8编码,最多允许32个字符
'openid' => $user_openid, //openid是微信用户在公众号appid下的唯一用户标识(appid不同,则获取到的openid就不同),可用于永久标记一个用户
]
]
];
$data['transfer_detail_list'][0]['user_name'] = self::getEncrypt($withdraw_name, $wx_cert_public_key);
$token = self::token($url, $http_method, $data, $config);
//获取token
$result = self::https_request($url, json_encode($data), $token, $wx_cert_sn);
//发送请求
$result_arr = json_decode($result, true);
if (!isset($result_arr['create_time'])) {
//批次受理失败
Libs_Log_Logger::outputLog($result_arr,"wx_transfer");
}
// 成功返回信息 {"batch_id":"1030001036201351072852022101201442513049","create_time":"2022-10-12T22:08:21+08:00","out_batch_no":"20221011004103000000146822"}
//批次受理成功,更新提现申请单为提现中状态
//业务修改为提现中
return json_encode($result_arr);
}
/**
* @notes 签名生成
* @param $url
* @param $http_method
* @param $data
* @param $config
* @return string
* @author ljj
* @date 2022/9/27 4:14 下午
*/
public static function token($url, $http_method, $data, $config)
{
$timestamp = time();
//请求时间戳
$url_parts = parse_url($url);
//获取请求的绝对URL
$nonce = $timestamp . rand('10000', '99999');
//请求随机串
$body = empty($data) ? '' : json_encode((object)$data);
//请求报文主体
$stream_opts = [
"ssl" => [
"verify_peer" => false,
"verify_peer_name" => false,
]
];
$apiclient_cert_arr = openssl_x509_parse(file_get_contents($config['cert_client'], false, stream_context_create($stream_opts)));
$serial_no = $apiclient_cert_arr['serialNumberHex'];
//Libs_Log_Logger::outputLog($serial_no,"wx_transfer");
//证书序列号
$mch_private_key = file_get_contents($config['cert_key'], false, stream_context_create($stream_opts));
//密钥
$merchant_id = $config['mch_id'];
//商户id
$canonical_url = ($url_parts['path'] . (!empty($url_parts['query']) ? "?${url_parts['query']}" : ""));
$message = $http_method . "\n" .
$canonical_url . "\n" .
$timestamp . "\n" .
$nonce . "\n" .
$body . "\n";
openssl_sign($message, $raw_sign, $mch_private_key, 'sha256WithRSAEncryption');
$sign = base64_encode($raw_sign);
//签名
$schema = 'WECHATPAY2-SHA256-RSA2048';
$token = sprintf(
'mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"',
$merchant_id,
$nonce,
$timestamp,
$serial_no,
$sign
);
//微信返回token
return $schema . ' ' . $token;
}
/**
* @notes 发送请求
* @param $url
* @param $data
* @param $token
* @return bool|string
* @author ljj
* @date 2022/9/27 4:15 下午
*/
public static function https_request($url, $data, $token, $wechatpay_serial)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, (string)$url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
if (!empty($data)) {
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//添加请求头
$headers = [
'Authorization:' . $token,
'Accept: application/json',
'Content-Type: application/json; charset=utf-8',
'User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
'Wechatpay-Serial:'.$wechatpay_serial,
];
if (!empty($headers)) {
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
}
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
/**
* @notes 发送请求
* @param $url
* @param $data
* @param $token
* @return bool|string
* @author ljj
* @date 2022/9/27 4:15 下午
*/
public static function https_request_without_wechatpay_serial($url, $token)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, (string)$url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//添加请求头
$headers = [
'Authorization:' . $token,
'Accept: application/json',
'Content-Type: application/json; charset=utf-8',
'User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
];
if (!empty($headers)) {
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
}
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
/**
* @notes 敏感信息加解密
* @param $str
* @param $config
* @return string
* @throws \Exception
* @author ljj
* @date 2022/9/27 3:53 下午
*/
public static function getEncrypt($str, $public_key)
{
//$str是待加密字符串
$encrypted = '';
if (openssl_public_encrypt($str, $encrypted, $public_key, OPENSSL_PKCS1_OAEP_PADDING)) {
//base64编码
$sign = base64_encode($encrypted);
} else {
//Libs_Log_Logger::outputLog($result_arr,"wx_transfer");
throw new \Exception('encrypt failed');
}
return $sign;
}
public static function decryptToString($aesKey, $associatedData, $nonceStr, $ciphertext)
{
$ciphertext = \base64_decode($ciphertext);
if (strlen($ciphertext) <= self::AUTH_TAG_LENGTH_BYTE) {
return false;
}
// ext-sodium (default installed on >= PHP 7.2)
if (function_exists('\sodium_crypto_aead_aes256gcm_is_available') && \sodium_crypto_aead_aes256gcm_is_available()) {
return \sodium_crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, $aesKey);
}
// ext-libsodium (need install libsodium-php 1.x via pecl)
if (function_exists('\Sodium\crypto_aead_aes256gcm_is_available') && \Sodium\crypto_aead_aes256gcm_is_available()) {
return \Sodium\crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, $aesKey);
}
// openssl (PHP >= 7.1 support AEAD)
if (PHP_VERSION_ID >= 70100 && in_array('aes-256-gcm', \openssl_get_cipher_methods())) {
$ctext = substr($ciphertext, 0, -self::AUTH_TAG_LENGTH_BYTE);
$authTag = substr($ciphertext, -self::AUTH_TAG_LENGTH_BYTE);
return \openssl_decrypt($ctext, 'aes-256-gcm', $aesKey, \OPENSSL_RAW_DATA, $nonceStr,
$authTag, $associatedData);
}
throw new \RuntimeException('AEAD_AES_256_GCM需要PHP 7.1以上或者安装libsodium-php');
}
/**
* @notes 商家明细单号查询明细单API
* @param $withdrawApply
* @param $config
* @return mixed
* @author ljj
* @date 2022/9/27 5:54 下午
*/
public static function details($appid,$mchid,$cert_client,$cert_key,$outbatchno,$outdetailno)
{
$config = [
'app_id' => $appid,
'mch_id' => $mchid, //商户ID
'cert_client' => getcwd().$cert_client, //cert证书地址//绝对路径
'cert_key' => getcwd().$cert_key, //key支付证书绝对地址
];
//请求URL
$url = 'https://api.mch.weixin.qq.com/v3/transfer/batches/out-batch-no/' . $outbatchno . '/details/out-detail-no/' . $outdetailno;
//请求方式
$http_method = 'GET';
//请求参数
$data = [];
$token = self::token($url, $http_method, $data, $config);
//获取token
$result = self::https_request($url, $data, $token);
//发送请求
$result_arr = json_decode($result, true);
return $result_arr;
}
}
Java Unicode类
public class UnicodeUtil {
//字符串转换unicode
public static String stringToUnicode(String string) {
StringBuffer unicode = new StringBuffer();
for (int i = 0; i < string.length(); i++) {
char c = string.charAt(i); // 取出每一个字符
unicode.append("\\u" +Integer.toHexString(c));// 转换为unicode
}
return unicode.toString();
}
//unicode 转字符串
public static String unicodeToString(String unicode) {
StringBuffer string = new StringBuffer();
String[] hex = unicode.split("\\\\u");
for (int i = 1; i < hex.length; i++) {
int data = Integer.parseInt(hex[i], 16);// 转换出每一个代码点
string.append((char) data);// 追加成string
}
return string.toString();
}
}