<?php /** * Created by ghostsf * Date: 2016/4/20 */ namespace app\admin\controller; use app\admin\model\Config; use app\admin\model\Personalconfig; use think\Controller; use think\Db; require 'qiniu/autoload.php'; use Qiniu\Auth; use Qiniu\Storage\UploadManager; use Qiniu\Processing\PersistentFop; use think\Config as redis; /** * 公共 * Class Common * @package app\admin\controller */ class CommonController extends Controller { // 定义配置项 private $config=array( 'APPID' => 'wx12fe768e213a0476', // 微信支付APPID. 'MCHID' => '1508786811', // 微信支付MCHID 商户收款账号 'KEY' => '', // 微信支付KEY 'APPSECRET' => '', // 公众帐号secert (公众号支付专用) 'NOTIFY_URL' => 'http://mms.mangmeshi.com/admin/Apiauth/huidiao', // 接收支付状态的连接 ); public $redis; /** * 拦截器 * * @return bool */ public function _initialize() { //session过期验证 if (!isset($_SESSION['loginSession'])) { header("http/1.1", true, 389); //389 http状态码 session过期 return false; } } /** * 七牛云存储 */ // public function qiniuCommon($type,$rand,$exe,$filePath) public function qiniuCommonVideo() { $name = $_FILES['video']['name']; $type = 5; $rand = date('YmdHis').rand(100000,999999); $filePath = $_FILES['video']['tmp_name']; $exe = explode('.',$name); $exe = end($exe); if($type == 2){ if($exe != 'jpg' && $exe != 'gif' && $exe != 'png'){ $return = array('status'=>0,'msg'=>'请上传图片'); return $return; } } if($type == 3){ if($exe != 'xls' && $exe != 'xlsx' && $exe != 'zip' && $exe != 'docx' && $exe != 'pdf'){ $return = array('status'=>0,'msg'=>'请上传正确的文件格式'); return $return; } } if($type == 4){ if($exe != 'mp3' && $exe != 'm4a' && $exe != 'wav'){ $return = array('status'=>0,'msg'=>'请上传正确的音频格式'); return $return; } } if($type == 5){ if($exe != 'mp4' && $exe != 'mov' && $exe != 'mkv' && $exe != 'flv' && $exe != '3gp' && $exe != 'wmv' && $exe != 'rmvb' && $exe != 'avi'){ $return = array('status'=>0,'msg'=>'请上传正确的视频格式'); return $return; } } $accessKey = 'nEztET3cvxjK87xXvVSOohxPd39zJTlO04jLgD74'; $secretKey = 'ThogMprroyhdDO5q163ClfRQ_CBn8yXRsHAx1_Qk'; $bucket = 'mangmeshi'; $auth = new Auth($accessKey, $secretKey); $returnBody = '{"key":"$(key)","mimeType":"$(mimeType)","vtime":"$(avinfo.video.duration)","atime":"$(avinfo.audio.duration)","fsize":$(fsize),"width":"$(imageInfo.width)","height":"$(imageInfo.height)","height":"$(imageInfo.height)","format":"$(imageInfo.format)"}'; $policy = array( 'returnBody' => $returnBody ); $expires = 3600; $token = $auth->uploadToken($bucket, null, $expires, $policy, true); // $filePath = $_FILES['file444']['tmp_name']; // 上传到七牛后保存的文件名 $key = $rand.'.'.$exe; // 初始化 UploadManager 对象并进行文件的上传。 $uploadMgr = new UploadManager(); //用 UploadManager 的 putFile 方法进行文件的上传 list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath); if ($err !== null) { if($exe == 'mp4'){ return json_encode(['status'=>200,'msg'=>'http://paz3uzuv1.bkt.clouddn.com/'.$key.'mp4']); }else{ $res = $this->qnCommon1($key); if(isset($res['err'])){ return json_encode(['status'=>0,'msg'=>'转码失败']); }else{ return json_encode(['status'=>200,'msg'=>'http://paz3uzuv1.bkt.clouddn.com/'.$res['rand'].'mp4']); } } // $info = $err; } else { return json_encode(['status'=>0,'msg'=>'上传失败']); } // $info['status'] = 200; // var_dump($info);die; // return $info; } public function qnCommon1($key) { // $key = "zhouyang.avi"; $accessKey = 'nEztET3cvxjK87xXvVSOohxPd39zJTlO04jLgD74'; $secretKey = 'ThogMprroyhdDO5q163ClfRQ_CBn8yXRsHAx1_Qk'; $bucket = 'mangmeshi'; // $accessKey = '62pzsS8cWNBVDOVRxhJNejBzQCbCkAKIS5Oy0lOn'; // $secretKey = '5HvPUZ0EzObz9z261EK5AuJntP5OT0_LV9ScDNnv'; // $bucket = 'nanyibucketby2017year'; $auth = new Auth($accessKey, $secretKey); $pipeline = 'mang_mp4'; $force = false; $notifyUrl = 'http://mms.mangmeshi.com/admin/Api/index'; $config = new \Qiniu\Config(); $pfop = new PersistentFop($auth, $config); $rand = date('YmdHis').rand(100000,999999); $fops = "avthumb/mp4/s/640x360/vb/1.4m|saveas/" . \Qiniu\base64_urlSafeEncode($bucket . ":".$rand.'.mp4'); list($id, $err) = $pfop->execute($bucket, $key, $fops, $pipeline, $notifyUrl, $force); if ($err != null) { $info['err'] = $err; $info['rand'] = $rand; } else { $info['id'] = $id; $info['rand'] = $rand; } // var_dump($info);die; return $info; // list($ret, $err) = $pfop->status($id); // echo "\n====> pfop avthumb status: \n"; // if ($err != null) { // var_dump($err); // } else { // var_dump($ret); // } } /** * @return string * get七牛token */ public function getQiniuToken(){header("Access-Control-Allow-Origin:*"); $accessKey = 'nEztET3cvxjK87xXvVSOohxPd39zJTlO04jLgD74'; $secretKey = 'ThogMprroyhdDO5q163ClfRQ_CBn8yXRsHAx1_Qk'; $auth = new Auth($accessKey, $secretKey); $bucket = 'mangmeshi'; // 生成上传Token $token = $auth->uploadToken($bucket); return json_encode(['status'=>200,'msg'=>$token]); } /** * 发送短信 * @param $phone * @param $num * @return mixed */ public function duaxin($phone,$num){ $body_json = array( 'sid'=>'2010a51e49df34754c876fbe910061a4', 'token'=>'01528a612dab2ad66f70fca870a88078', 'appid'=>'85f7e8ae0e2d4dd6a9d619ccda794047', 'templateid'=>'296258', 'param'=>$num, 'mobile'=>$phone, 'uid'=>'', ); $body = json_encode($body_json); $header = array( 'Accept:application/json', 'Content-Type:application/json;charset=utf-8', ); $url = 'https://open.ucpaas.com/ol/sms/sendsms'; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, $header); curl_setopt($ch,CURLOPT_POST,1); curl_setopt($ch,CURLOPT_POSTFIELDS,$body); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); $result = curl_exec($ch); curl_close($ch); $res = json_decode($result,true); return $res; } /** * 获取融云token * @param $uid * @param $name * @param $imageurl * @return mixed */ public function rongyun($uid=0,$name='',$imageurl=''){//echo 1;die; $appKey = 'n19jmcy5n8l09'; $appSecret = 'P8BCshr6wkp5T'; $body = "userId={$uid}&name={$name}&portraitUri={$imageurl}"; $nonce = mt_rand(); $timeStamp = time(); $sign = sha1($appSecret.$nonce.$timeStamp); $header = array( 'App-Key:'.$appKey, 'Nonce:'.$nonce, 'Timestamp:'.$timeStamp, 'Signature:'.$sign, 'Content-Type: application/x-www-form-urlencoded' ); $url = 'http://api.cn.ronghub.com/user/getToken.json'; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, $header); curl_setopt($ch,CURLOPT_POST,1); curl_setopt($ch,CURLOPT_POSTFIELDS,$body); // curl_setopt($ch, CURLOPT_SSL_VERI/FYPEER, false); // curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); $result = curl_exec($ch); curl_close($ch); $res = json_decode($result,true); return $res; // var_dump($res) ; } public function uploadFile($tmp,$name,$size) { if($size > 2048*1024){ return array('status'=>0,'msg'=>"图片不得超过2M！"); } $imgarray = array('jpg','jpeg','png'); $dir = $_SERVER['DOCUMENT_ROOT']; $url = "http://".$_SERVER['HTTP_HOST']; if($tmp){ //=======重命名===== $rand = date('YmdHis').rand(100000,999999); $exe = explode('.',$name); $exe = end($exe); if(!in_array($exe,$imgarray)){ return array('status'=>0,'msg'=>'图片格式不支持'); } $newName = $rand . '.' .$exe; //======================= if(move_uploaded_file($tmp,"{$dir}/mang/image/{$newName}")){ $imgUrl = "{$url}/mang/image/{$newName}"; return array('status'=>200,'msg'=>$imgUrl); }else{ return array('status'=>0,'msg'=>'图片保存失败'); } }else{ return array('status'=>0,'msg'=>"上传一张图！"); } } function diffBetweenTwoDays ($day2) { $day1 = date('Y-m-d'); $second1 = strtotime($day1); $second2 = strtotime($day2); if ($second1 < $second2) { $tmp = $second2; $second2 = $second1; $second1 = $tmp; } return ($second1 - $second2) / 86400; } /** * 验证唯一性：异地登陆 * @param $uid * @param $time * @param $value * @param $reqKey * @return bool */ public function checkAll($uid,$time,$value,$reqKey){//$uid,$time,$value header("Access-Control-Allow-Origin:*"); if($uid == 0){ return true; }else{ $user = Db::table('ew_u_user')->where('user_id',$uid) ->field('user_id,user_auth,user_auth_date,user_status,user_token')->find(); if($user['user_status'] != 1){//禁用 return false; } //------------------------------------------------------ if($user['user_auth'] > 0){ $today = date('Y-m-d'); if($user['user_auth_date'] < $today){ Db::table('ew_u_user')->where('user_id',$uid)->update(['user_auth'=>0]); } } //------------------------------------------------------ $token = $user['user_token']; $appId = "A6060432236270"; $appkey = "F591B37E-1C61-01C7-57C6-8B2F6D59DCD9"; $myreqKey = md5($appId . 'XW' . $appkey . 'XW' . $time); $myvalue = md5($uid . 'XW' . $token . 'XW' . $time); if($myvalue != $value || $myreqKey != $reqKey){ return false; }else{ return true; } } } public function uuid($prefix = '') { $chars = md5(uniqid(mt_rand(), true)); $uuid = substr($chars,0,8); $uuid .= substr($chars,8,4); $uuid .= substr($chars,12,4); $uuid .= substr($chars,16,4); $uuid .= substr($chars,20,12); return $prefix . $uuid; } /** * @return string */ public function getJobData($type,$where,$page,$self=1){ $orderNum = 1; if(isset($where['order'])){ $orderNum = $where['order']; unset($where['order']); } if($orderNum == 1){ $order = "job_createtime DESC"; }elseif ($orderNum == 2){ $order = "job_createtime ASC"; }elseif ($orderNum == 3){ $order = "distance DESC"; }elseif ($orderNum == 4){ $order = "distance ASC"; }elseif ($orderNum == 5){ $order = "job_zhouqi_order DESC"; }elseif ($orderNum == 6){ $order = "job_zhouqi_order ASC"; }else{ $order = "job_createtime DESC"; } $field = 'job_id,user_id,job_user_id,job_name,job_status,job_type,u.district sheng,ua.district shi,uaa.district qu,job_money_min,job_money_max,job_createtime,job_zhouqi_order'; $field .= ',job_year,job_phone,job_weixin,job_qq,job_school,job_age_min,job_age_max,job_sex,user_username,user_image'; $field .= ',job_peple,job_com_find_zhouqi,job_zhouqi_year,job_zhi,job_whatfor,job_views'; if(isset($where['lat']) && isset($where['lon']) && $where['lat'] && $where['lon']){ $lat = $where['lat']; $lon = $where['lon']; unset($where['lat']); unset($where['lon']); }else{ $lat = 0.1; $lon = 0.1; } $field .= ',ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(('.$lat.'* PI() / 180 - job_lat * PI() / 180) / 2),2) + COS('.$lat.' * PI() / 180) * COS(job_lat * PI() / 180) * POW(SIN(('.$lon.' * PI() / 180 - job_lon * PI() / 180) / 2),2))) * 1000) AS distance'; if($type == 1){ $field .= ',user_one_star'; }elseif($type == 2){ $field .= ',user_company,user_company_logo,job_com_name,user_two_star'; }elseif($type == 3){ $field .= ',user_thr_star'; } if(isset($where['job_name'])){ $search = $where['job_name']; unset($where['job_name']); $data = Db::table('ew_job')->alias('j') ->join('ew_u_user uu','j.job_user_id=uu.user_id','LEFT') ->join('ew_area u','j.job_sheng=u.district_id','LEFT') ->join('ew_area ua','j.job_shi=ua.district_id','LEFT') ->join('ew_area uaa','j.job_qu=uaa.district_id','LEFT') ->where($where) ->where(function ($query) use($search){ $query->where('job_name','like',"%$search%") ->whereOr('job_address','like',"%$search%") ->whereOr('job_com_name','like',"%$search%"); }) ->field($field) ->order($order) ->limit(($page-1)*10,10) ->select(); }else{ $data = Db::table('ew_job')->alias('j') ->join('ew_u_user uu','j.job_user_id=uu.user_id','LEFT') ->join('ew_area u','j.job_sheng=u.district_id','LEFT') ->join('ew_area ua','j.job_shi=ua.district_id','LEFT') ->join('ew_area uaa','j.job_qu=uaa.district_id','LEFT') ->where($where) ->field($field) ->order($order) ->limit(($page-1)*10,10) ->select(); if(!$data && $self==1){ $morenids = Db::table('ew_u_user')->where('user_moren',2)->column('user_id'); if($morenids){ $data = Db::table('ew_job')->alias('j') ->join('ew_u_user uu','j.job_user_id=uu.user_id','LEFT') ->join('ew_area u','j.job_sheng=u.district_id','LEFT') ->join('ew_area ua','j.job_shi=ua.district_id','LEFT') ->join('ew_area uaa','j.job_qu=uaa.district_id','LEFT') ->where('job_type',$type) ->where('job_user_id','in',$morenids) ->field($field) ->order($order) ->limit(($page-1)*10,10) ->select(); } } } return $data; } /** * 获取我的资讯 * */ public function getLifeData($type,$where,$page){ if(isset($where['index_user_id'])){ $user_id = $where['index_user_id']; unset($where['index_user_id']); }else{ $user_id = $where['life_user_id']; } if($type == 4){ $data = Db::table('ew_life') ->alias ('el') ->join('ew_life_type elt','el.life_type=elt.lt_id','left') ->where($where) ->field('el.life_id,life_message,life_new_type,life_zan,el.life_number,el.life_title,el.life_image,el.life_time,elt.lt_id,elt.lt_name') ->page($page,10) ->order("el.life_time desc") ->select(); }else{ $field = "user_id,user_image,user_username,life_new_type,el.life_id,el.life_price,life_message,life_zan,el.life_number,el.life_title,el.life_image,el.life_time"; // if(isset($where['lat']) && isset($where['lon']) && $where['lat'] && $where['lon']){ // $lat = $where['lat']; // $lon = $where['lon']; // unset($where['lat']); // unset($where['lon']); // $field .= ',ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(('.$lat.'* PI() / 180 - life_lat * PI() / 180) / 2),2) + COS('.$lat.' * PI() / 180) * COS(life_lat * PI() / 180) * POW(SIN(('.$lon.' * PI() / 180 - life_lon * PI() / 180) / 2),2))) * 1000) AS distance'; // } $field .= ',life_url,life_content,life_thing,life_address,u.district sheng,ua.district shi,uaa.district qu'; $data = Db::table('ew_life')->alias ('el') ->join('ew_u_user uu','el.life_user_id=uu.user_id','left') ->join('ew_area u','el.life_sheng=u.district_id','LEFT') ->join('ew_area ua','el.life_shi=ua.district_id','LEFT') ->join('ew_area uaa','el.life_qu=uaa.district_id','LEFT') ->where($where) ->field($field) ->page($page,10) ->order("el.life_time desc") ->select(); } $zandata = Db::table('ew_life_zan')->where('lz_user_id',$user_id)->column('lz_life_id'); if($data){ foreach ($data as $k=>$v){ $data[$k]['zan'] = 1;//没有点赞 if($v['life_image']){ $v['life_image'] = trim($v['life_image'],','); $data[$k]['life_image'] = explode(',',$v['life_image']); } if($zandata){ if(in_array($v['life_id'],$zandata)){ $data[$k]['zan'] = 2;//已经点赞 } } } } return $data; } /** redis连接 * @return bool */ public function redis() { $options=redis::get('database'); $redisHost=array_key_exists("redisHost",$options)?$options['redisHost']:"127.0.0.1"; $redisPort=array_key_exists("redisPort",$options)?$options['redisPort']:6379; $redisAuth=array_key_exists("redisAuth",$options)?$options['redisAuth']:''; $redisHost=$redisHost==null?"127.0.0.1":$redisHost; $redisPort=$redisPort==null? 6379:$redisPort; if(extension_loaded("redis")){ $redis= new \redis(); if($redis->connect($redisHost,$redisPort)){ if($redisAuth!=null){ $redis->auth($redisAuth); if(false==$redis->set('ce',1)){ return false; } } $this->redis=$redis; return true; }else{ return false; die; $tishi="redis连接失败原因IP地址连接有误"; die($tishi); } }else{ return false; } } /** * 全局设置 * @param array $arr */ public function setGlobalSettings($arr = []) { foreach ($arr as $name) { $config = Config::get(array("name" => $name)); $this->assign($name, $config->value); } } /** * 个性设置 * @param array $arr */ public function setPersonalSettings($arr = []) { $loginSession = session('loginSession'); $userid = $loginSession['id']; foreach ($arr as $name) { $personalConfig = Personalconfig::get(array("name" => $name, "userid" => $userid)); if ($personalConfig) { $this->assign($name, $personalConfig->value); } else { $this->setGlobalSettings([$name]); } } } /** * 根据校区id区分数据显示 */ public function getDataByCampusid($arr = []) { //为空是用来判断添加数据时要不要传参 //$str是专门用于获取数据（其他是campusid 校区管理是id） 针对校区管理 除了校区管理 其他功能不用传 foreach ($arr as $key => $value) { if ($key == 'page') { unset($arr[$key]); } else if ($key == 'rows') { unset($arr[$key]); } else if ($value == '') { unset($arr[$key]); } else if ($value == 'job_shi') { $arr[$key] = $value; } else { $arr[$key] = Array('like', '%' . $value . '%'); } } return $arr; } /** * @param $type * @param $msg * @param $msg_encode * @param $data * @return mixed * 极光推送 */ // public function sendJpush($type,$msg,$msg_encode,$msg1,$data,$code1){ public function sendJpush($token,$msg,$msg_data,$type,$tc=1){ require_once 'jpush/autoload.php'; $ji=array( 'appKey'=>'a76796e479c786ee49c9c94e', 'masterSecret'=>'a432ce71926d1125eda4fbe6', ); $client = new \JPush\Client($ji['appKey'],$ji['masterSecret']); $push = $client->push(); $push->setPlatform('all'); //================== if($type==1){ $push->addAlias($token); }else{ $push->addAllAudience(); } //================== // $push->addAlias($token); $push->iosNotification($msg, array( 'alert'=>$msg, 'badge' => '1', 'extras' => $msg_data, 'sound'=>'default' ) ); $push->androidNotification($msg, array( 'badge' => '1', 'extras' => $msg_data )); //6新农村，7大学生，8二手货，9涨知识 $msg1 = "{tcid:$tc}";//1是职位的和忙友圈的，2是申请好友，6789是资讯的四个 $push->message($msg1, [//透传 // 'title' => 'Hello', 'content_type' => 'text', // 'extras' => [ // 'key' => $code1 // ] ]); return $push->send(); } /** * 知道俩人的状态，是不是好友或其他状态 * uid,user_id */ function getFriendStatus($uid,$user_id){ $who = 0;//不是你的好友 $friend_id = 0;//申请的id if($uid == $user_id){ $who = 6;//我自己 }else{ $mygood1 = Db::table('ew_friend') ->where('friend_user_id',$user_id) ->where('friend_good_user_id',$uid) ->find(); $mygood2 = Db::table('ew_friend') ->where('friend_user_id',$uid) ->where('friend_good_user_id',$user_id) ->find(); if($mygood1){ $who = $mygood1['friend_status'];//对应相应的123 $friend_id = $mygood1['friend_id'];// } if($mygood2){ if($mygood2['friend_status'] == 1){$who = 1;}//已经同意是好友 if($mygood2['friend_status'] == 2){$who = 4;}//你选择同意还是拒接 if($mygood2['friend_status'] == 3){$who = 5;}//你已经拒绝了 $friend_id = $mygood2['friend_id'];//只有同意或者拒绝的时候才有 } } $data = array(); $data['who'] = $who; $data['friend_id'] = $friend_id; return $data; } function fiveWho($i){ $data = array('ok','已经是好友了','您已申请过','对方已拒绝','对方已申请加你','您已拒绝对方的好友申请','不能添加自己为好友'); return $data[$i]; } /** * 压缩图片 * @param $imgsrc:原图片地址（完整的图片路径） * @param $imgdst:压缩后的图片地址，也是完整的 */ function image_png_size_add($imgsrc,$imgdst){ list($width,$height,$type)=getimagesize($imgsrc); switch($type){ case 1: break; case 2: header('Content-Type:image/jpeg'); $image = imagecreatefromjpeg($imgsrc); imagejpeg($image, $imgdst,20); imagedestroy($image); break; case 3: header('Content-Type:image/png'); $image = imagecreatefrompng($imgsrc); imagejpeg($image, $imgdst,20); imagedestroy($image); break; } } /** * 根据经纬度算出两地的距离 * @param $lat1 * @param $lng1 * @param $lat2 * @param $lng2 * @return int */ function getDistance($lat1, $lng1, $lat2, $lng2){ //将角度转为狐度 $radLat1=deg2rad($lat1);//deg2rad()函数将角度转换为弧度 $radLat2=deg2rad($lat2); $radLng1=deg2rad($lng1); $radLng2=deg2rad($lng2); $a=$radLat1-$radLat2; $b=$radLng1-$radLng2; $s=2*asin(sqrt(pow(sin($a/2),2)+cos($radLat1)*cos($radLat2)*pow(sin($b/2),2)))*6378.137; $res = round($s*1000); if($res < 1000){ return $res . 'm'; }else{ return round($res/1000,2) . 'km'; } } /** * 筛选搜索条件不是like是= */ public function searchNotLike($searchPath=[],$postArr=[],$one='',$two='',$three='') { if (isset($searchPath[$one]) && $one != '') { unset($searchPath[$one]); $searchPath[$one] = $postArr[$one]; } if (isset($searchPath[$two]) && $two != '') { unset($searchPath[$two]); $searchPath[$two] = $postArr[$two]; } if (isset($searchPath[$three]) && $three != '') { unset($searchPath[$three]); $searchPath[$three] = $postArr[$three]; } return $searchPath; } /** * +---------------------------------------------------------- * Export Excel | 2016.09.14 * Author:ghostsf <ghostsf@163.com> * +---------------------------------------------------------- * @param $expTitle string File name * +---------------------------------------------------------- * @param $expCellName array Column name * +---------------------------------------------------------- * @param $expTableData array Table data * +---------------------------------------------------------- */ public function exportExcel($expTitle, $expCellName, $expTableData) { $xlsTitle = iconv('utf-8', 'gb2312', $expTitle); //文件表名称 $fileName = $xlsTitle . date('_YmdHis'); //文件名称 $cellNum = count($expCellName); $dataNum = count($expTableData); vendor("phpoffice.phpexcel.Classes.PHPExcel"); $objPHPExcel = new \PHPExcel(); $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ'); //$objPHPExcel->getActiveSheet()->mergeCells('A1:' . $cellName[$cellNum - 1] . '1');//合并单元格 //$objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle . ' Export time:' . date('Y-m-d H:i:s')); $objPHPExcel->getDefaultStyle()->getFont()->setName('微软雅黑'); $objPHPExcel->getDefaultStyle()->getFont()->setSize(12); $objPHPExcel->getActiveSheet()->getStyle('1')->applyFromArray( array( 'font' => array( 'bold' => true ) ) ); for ($i = 0; $i < $cellNum; $i++) { $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i] . '1', $expCellName[$i][1]); $objPHPExcel->getActiveSheet()->getColumnDimension($cellName[$i])->setAutoSize(true); } // Miscellaneous glyphs, UTF-8 for ($i = 0; $i < $dataNum; $i++) { for ($j = 0; $j < $cellNum; $j++) { $objPHPExcel->getActiveSheet()->setCellValue($cellName[$j] . ($i + 2), $expTableData[$i][$expCellName[$j][0]]); } } header('pragma:public'); header('Content-type:application/vnd.ms-excel;charset=utf-8;name="' . $xlsTitle . '.xls"'); header("Content-Disposition:attachment;filename=$fileName.xls"); //attachment新窗口打印inline本窗口打印 $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); $objWriter->save('php://output'); exit; } /** * +---------------------------------------------------------- * Import Excel | 2016.0914 * Author:ghostsf <ghostsf@163.com> * +---------------------------------------------------------- * @param $file upload file $_FILES * +---------------------------------------------------------- * @return array array("error","message") * +---------------------------------------------------------- */ public function read($filename,$encode='utf-8') { vendor("phpoffice.phpexcel.Classes.PHPExcel.IOFactory"); $objReader = \PHPExcel_IOFactory::createReader('Excel5'); $objReader->setReadDataOnly(true); $objPHPExcel = $objReader->load($filename); $objWorksheet = $objPHPExcel->getActiveSheet(); $highestRow = $objWorksheet->getHighestRow(); $highestColumn = $objWorksheet->getHighestColumn(); $highestColumnIndex = \PHPExcel_Cell::columnIndexFromString($highestColumn); $excelData = array(); for ($row = 1; $row <= $highestRow; $row++) { for ($col = 0; $col < $highestColumnIndex; $col++) { $excelData[$row][] =(string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue(); } } return $excelData; } //--------------------------------------------------融云群聊的操作------------------------------------------------ //建群 public function create($uids,$groupid,$name){ $appKey = 'n19jmcy5n8l09'; $appSecret = 'P8BCshr6wkp5T'; $body = "{$uids}groupId=$groupid&groupName=$name"; $nonce = mt_rand(); $timeStamp = time(); $sign = sha1($appSecret . $nonce . $timeStamp); $header = array( 'App-Key:' . $appKey, 'Nonce:' . $nonce, 'Timestamp:' . $timeStamp, 'Signature:' . $sign, 'Content-Type: application/x-www-form-urlencoded' ); $url = 'http://api.cn.ronghub.com/group/create.json'; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, $header); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $body); // curl_setopt($ch, CURLOPT_SSL_VERI/FYPEER, false); // curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); $result = curl_exec($ch); curl_close($ch); $res = json_decode($result, true); return $res; } //加入 /** * @return mixed */ public function joinin($uidstr,$groupid,$name) { $appKey = 'n19jmcy5n8l09'; $appSecret = 'P8BCshr6wkp5T'; $body = "{$uidstr}groupId=$groupid&groupName=$name"; $nonce = mt_rand(); $timeStamp = time(); $sign = sha1($appSecret . $nonce . $timeStamp); $header = array( 'App-Key:' . $appKey, 'Nonce:' . $nonce, 'Timestamp:' . $timeStamp, 'Signature:' . $sign, 'Content-Type: application/x-www-form-urlencoded' ); $url = 'http://api.cn.ronghub.com/group/join.json'; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, $header); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $body); // curl_setopt($ch, CURLOPT_SSL_VERI/FYPEER, false); // curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); $result = curl_exec($ch); curl_close($ch); $res = json_decode($result, true); return $res; } //退出 public function getout($uidstr,$groupid) { $appKey = 'n19jmcy5n8l09'; $appSecret = 'P8BCshr6wkp5T'; $body = "{$uidstr}groupId=$groupid"; $nonce = mt_rand(); $timeStamp = time(); $sign = sha1($appSecret . $nonce . $timeStamp); $header = array( 'App-Key:' . $appKey, 'Nonce:' . $nonce, 'Timestamp:' . $timeStamp, 'Signature:' . $sign, 'Content-Type: application/x-www-form-urlencoded' ); $url = 'http://api.cn.ronghub.com/group/quit.json'; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, $header); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $body); // curl_setopt($ch, CURLOPT_SSL_VERI/FYPEER, false); // curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); $result = curl_exec($ch); curl_close($ch); $res = json_decode($result, true); return $res; } //退出 public function kill($uid,$groupid) { $appKey = 'n19jmcy5n8l09'; $appSecret = 'P8BCshr6wkp5T'; $body = "userId=$uid&groupId=$groupid"; $nonce = mt_rand(); $timeStamp = time(); $sign = sha1($appSecret . $nonce . $timeStamp); $header = array( 'App-Key:' . $appKey, 'Nonce:' . $nonce, 'Timestamp:' . $timeStamp, 'Signature:' . $sign, 'Content-Type: application/x-www-form-urlencoded' ); $url = 'http://api.cn.ronghub.com/group/dismiss.json'; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, $header); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $body); // curl_setopt($ch, CURLOPT_SSL_VERI/FYPEER, false); // curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); $result = curl_exec($ch); curl_close($ch); $res = json_decode($result, true); return $res; } //--------------------*************以下是微信支付相关************----------------------------------- public function WeChatPayReady($order){ // 获取配置项 $weixinpay_config=$this->config; $config=array( 'appid'=>$weixinpay_config['APPID'], 'mch_id'=>$weixinpay_config['MCHID'], 'nonce_str'=>'test', 'spbill_create_ip'=>$_SERVER['REMOTE_ADDR'], 'notify_url'=>$weixinpay_config['NOTIFY_URL'] ); $type = 1; if(!empty($type)){ $config['notify_url']='http://mms.mangmeshi.com/admin/Apiauth/huidiao'; } // 合并配置数据和订单数据 $data=array_merge($order,$config); // 生成签名 $sign=$this->makeSign($data); $data['sign']=$sign; $xml=$this->toXml($data); $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';//接收xml数据的文件 $header[] = "Content-type: text/xml";//定义content-type为xml,注意是数组 $ch = curl_init ($url); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE); curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);//严格校验 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $header); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $xml); $response = curl_exec($ch); if(curl_errno($ch)){ print curl_error($ch); } curl_close($ch); $result=$this->toArray($response); $result['sign']=$sign; $result['nonce_str']='test'; $result2 = $this->getOrder($result['prepay_id']); $res222['status'] = 200; $res222['msg'] = $result2; return $res222; } /** * 输出xml字符 * @throws WxPayException **/ public function toXml($data){ //var_dump($data); if(!is_array($data) || count($data) <= 0){ //throw new WxPayException("数组数据异常！"); } $xml = "<xml>"; foreach ($data as $key=>$val){ if (is_numeric($val)){ $xml.="<".$key.">".$val."</".$key.">"; }else{ $xml.="<".$key."> ".$val." </".$key.">"; } } $xml.="</xml>"; return $xml; } /** * 生成签名 * @return 签名，本函数不覆盖sign成员变量，如要设置签名需要调用SetSign方法赋值 */ public function makeSign($data){ // 去空 $data=array_filter($data); //签名步骤一：按字典序排序参数 ksort($data); $string_a=http_build_query($data); $string_a=urldecode($string_a); //签名步骤二：在string后加入KEY $config=$this->config; $string_sign_temp=$string_a."&key=".$config['KEY']; //签名步骤三：MD5加密 $sign = md5($string_sign_temp); // 签名步骤四：所有字符转为大写 $result=strtoupper($sign); return $result; } /** * 将xml转为array * @param string $xml xml字符串 * @return array 转换得到的数组 */ public function toArray($xml){ //禁止引用外部xml实体 libxml_disable_entity_loader(true); $result= json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true); return $result; } //执行第二次签名，才能返回给客户端使用 public function getOrder($prepayId){ $data["appid"] = $this->config["APPID"]; $data["noncestr"] = $this->getRandChar(32); $data["package"] = "Sign=WXPay"; $data["partnerid"] = $this->config['MCHID']; $data["prepayid"] = $prepayId; $data["timestamp"] = time(); $s = $this->makeSign($data); $data["sign"] = $s; return $data; } //获取指定长度的随机字符串 function getRandChar($length){ $str = null; $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz"; $max = strlen($strPol)-1; for($i=0;$i<$length;$i++){ $str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数 } return $str; } //-----------退款--------- /** * 提现 * 提现的这个如果是201也把状态改了 * 查询的那个如果是200说明已经提现过了，拒绝的时候也要查询一下，200就把状态改了，防止数据出错 */ public function userTiXian($refundNo,$openid,$money){ // $openid = 'ojZJn05cmFfzFmZl35-wU9_xXFow'; $url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers"; $data["mch_appid"] = $this->config['APPID'];//微信开放平台审核通过的应用APPID $data["mchid"] = $this->config['MCHID'];//商户号 $data["nonce_str"] = $this->getRandChar(32);//随机字符串 $data["partner_trade_no"] = $refundNo; $data["openid"] = $openid; $data["check_name"] = 'NO_CHECK'; $data["amount"] = $money*100; $data["desc"] = '提现到账通知'; $data["spbill_create_ip"] = $_SERVER['REMOTE_ADDR']; $sign = $this->makeSign($data); $data['sign'] = $sign; $xml = $this->toXml($data); $response = $this->postXmlCurl($xml, $url, '', true, '/appcert/apiclient_cert.pem', '/appcert/apiclient_key.pem'); $responseArr = $this->toArray($response); if (!is_array($responseArr) || count($responseArr) <= 0) { $return['msg'] = '网络请求繁忙'; $return['status'] = 0; } else if ($responseArr['return_code'] == 'FAIL') { $return['msg'] = $responseArr['return_msg']; $return['status'] = 0; } else { if ($responseArr['result_code'] == 'FAIL') { $return['msg'] = $responseArr['err_code_des']; $return['status'] = 0; } else { $return['text'] = $responseArr; $return['status'] = 200; } } return $return; } /** * 提现查询 */ public function tiXianChaXun($refundNo){ $url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/gettransferinfo"; $data["appid"] = $this->config['APPID'];//微信开放平台审核通过的应用APPID $data["mch_id"] = $this->config['MCHID'];//商户号 $data["nonce_str"] = $this->getRandChar(32);//随机字符串 $data["partner_trade_no"] = $refundNo; $sign=$this->makeSign($data); $data['sign']=$sign; $xml=$this->toXml($data); $response = $this->postXmlCurl($xml, $url,'',true,'/appcert/apiclient_cert.pem','/appcert/apiclient_key.pem'); $responseArr=$this->toArray($response); if(!is_array($responseArr) || count($responseArr)<=0){ $return['msg'] = '网络请求繁忙'; $return['status'] = 0; }else if($responseArr['return_code'] == 'FAIL'){ $return['msg'] = $responseArr['return_msg']; $return['status'] = 0; }else{ if($responseArr['result_code'] == 'FAIL'){ $return['msg'] = $responseArr['err_code_des']; $return['status'] = 0; }else{ $return['text'] = $responseArr; $return['status'] = 200; } } return $return; } function postXmlCurl($xml, $url, $second=30, $useCert=false, $sslcert_path, $sslkey_path) { $ch = curl_init(); //设置超时 curl_setopt($ch, CURLOPT_TIMEOUT, $second); curl_setopt($ch,CURLOPT_URL, $url); //设置header curl_setopt($ch, CURLOPT_HEADER, FALSE); //要求结果为字符串且输出到屏幕上 curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE); curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE); if($useCert == true){ curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false); curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false); // curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,TRUE); // curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,1);//严格校验 //设置证书 $path = $_SERVER['DOCUMENT_ROOT']; curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM'); curl_setopt($ch,CURLOPT_SSLCERT, $path.$sslcert_path); curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM'); curl_setopt($ch,CURLOPT_SSLKEY, $path.$sslkey_path); // curl_setopt($ch,CURLOPT_CAINFO, __DIR__.'/cert/rootca.pem'); } //post提交方式 curl_setopt($ch, CURLOPT_POST, TRUE); curl_setopt($ch, CURLOPT_POSTFIELDS, $xml); //运行curl $data = curl_exec($ch); //返回结果 if($data){ curl_close($ch); return $data; } else { $error = curl_errno($ch); curl_close($ch); return false; } } }
<?php /** * Created by PhpStorm. * User: Kevin * Date: 2018/10/7 * Time: 10:49 */ namespace app\admin\controller; use think\Db; class Money extends Base { public function tixianAgreeShopOrWork($number,$money,$phone,$name,$remark='') // public function tixianAgreeShopOrWork() { header("Content-type:text/html;charset=UTF-8"); // $number='444555661313131316'; // $money='0.1'; // $phone='15895980214'; // $name='麻威我'; // $remark = ''; import('alipay.aop.AopClient',EXTEND_PATH); import('alipay.aop.request.AlipayFundTransToaccountTransferRequest',EXTEND_PATH); $aop = new \AopClient; $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do'; $aop->appId = '2018090761306686'; $aop->rsaPrivateKey = '/o35qU8Sy9f0YSeOq4JRMast8tyj7hqI5ZEb4LCHioFpK76qmUHrsgAXO48NeQ0AZPsNA7jqYVEPHemcpk+Qzva0VkinUhSb+Hvqeam314lQpg0ctpJf73yjIy9ScxCFxNnoDLybWnbptazW3OwhKNdyVQ675kp/GXVU='; $aop->alipayrsaPublicKey = '[binary]'; $aop->apiVersion = '1.0'; $aop->signType = 'RSA2'; $aop->postCharset='UTF-8'; $aop->format='json'; $request = new \AlipayFundTransToaccountTransferRequest; $request->setBizContent("{" . "\"out_biz_no\":\"".$number."\"," . "\"payee_type\":\"ALIPAY_LOGONID\"," . "\"payee_account\":\"".$phone."\"," . "\"amount\":\"".$money."\"," . "\"payer_show_name\":\"红集提现到账\"," . "\"payee_real_name\":\"".$name."\"," . "\"remark\":\"".$remark."\"" . "}"); $result = $aop->execute($request); $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response"; $resultCode = $result->$responseNode->code; if(!empty($resultCode)&&$resultCode == 10000){ $result = array(); $result['status'] = 200; $result['msg'] = 'OK'; return $result; } else { $result = array(); $result['status'] = 0; $result['msg'] = $result->alipay_fund_trans_toaccount_transfer_response->sub_msg; return $result; } } public function chaxunTixianRes($number) { header("Content-type:text/html;charset=UTF-8"); import('alipay.aop.AopClient',EXTEND_PATH); import('alipay.aop.request.AlipayFundTransOrderQueryRequest',EXTEND_PATH); $aop = new \AopClient; $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do'; $aop->appId = '2018090761306686'; $aop->rsaPrivateKey = '[binary]'; $aop->alipayrsaPublicKey = '[binary]'; $aop->apiVersion = '1.0'; $aop->signType = 'RSA2'; $aop->postCharset='UTF-8'; $aop->format='json'; $request = new \AlipayFundTransOrderQueryRequest; $request->setBizContent("{" . "\"out_biz_no\":\"".$number."\"" . " }"); $result = $aop->execute($request); $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response"; $resultCode = $result->$responseNode->code; if(!empty($resultCode)&&$resultCode == 10000){ return true; } else { return false; } } public function WeChatPayReady($order,$type=null){ // 获取配置项 $data=array( 'appid'=>$weixinpay_config2['APPID'], 'mch_id'=>$weixinpay_config2['MCHID'], 'nonce_str'=>'test', 'spbill_create_ip'=>$_SERVER['REMOTE_ADDR'], 'notify_url'=>$weixinpay_config2['NOTIFY_URL'] ); // 生成签名 $sign=$this->makeSign($data); $data['sign']=$sign; $xml=$this->toXml($data); $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';//接收xml数据的文件 $header[] = "Content-type: text/xml";//定义content-type为xml,注意是数组 $ch = curl_init ($url); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE); curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);//严格校验 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $header); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $xml); $response = curl_exec($ch); if(curl_errno($ch)){ print curl_error($ch); } curl_close($ch); $result=$this->toArray($response); if($result['return_code'] == 'FAIL'){ $returnerr['msg'] = $result['return_msg']; $returnerr['type'] = 'error'; return $returnerr; }else{ $result['sign']=$sign; $result['nonce_str']='test'; $result2 = $this->getOrder($result['prepay_id']); return $result2;/// } } /** * 生成签名 * @return 签名，本函数不覆盖sign成员变量，如要设置签名需要调用SetSign方法赋值 */ public function makeSign($data){ // 去空 $data=array_filter($data); //签名步骤一：按字典序排序参数 ksort($data); $string_a=http_build_query($data); $string_a=urldecode($string_a); //签名步骤二：在string后加入KEY $config2=$this->config2; $string_sign_temp=$string_a."&key=".$config2['KEY']; //签名步骤三：MD5加密 $sign = md5($string_sign_temp); // 签名步骤四：所有字符转为大写 $result=strtoupper($sign); return $result; } /** * 输出xml字符 * @throws WxPayException **/ public function toXml($data){ //var_dump($data); if(!is_array($data) || count($data) <= 0){ //throw new WxPayException("数组数据异常！"); } $xml = "<xml>"; foreach ($data as $key=>$val){ if (is_numeric($val)){ $xml.="<".$key.">".$val."</".$key.">"; }else{ $xml.="<".$key."> ".$val." </".$key.">"; } } $xml.="</xml>"; return $xml; } /** * 将xml转为array * @param string $xml xml字符串 * @return array 转换得到的数组 */ public function toArray($xml){ //禁止引用外部xml实体 libxml_disable_entity_loader(true); $result= json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true); return $result; } //获取指定长度的随机字符串 function getRandChar($length){ $str = null; $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz"; $max = strlen($strPol)-1; for($i=0;$i<$length;$i++){ $str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数 } return $str; } // /** 原支付宝提现，打开即用 // * r_id,type 1是同意 2是拒绝,remark(备注) // * @return \think\response\Json // */ // public function agreeOrRefuseTixian($r_id,$type,$remark) // { // $jilu = Db::name('work_jilu')->where('r_id',$r_id)->find(); // if($jilu['r_status'] != 1){ // return ['code'=>0,'msg'=>'已经操作过了，请刷新！']; // }else{ // $today = date('Y-m-d H:i:s'); // if($type == 1){//同意 // $have = $this->chaxunTixianRes($jilu['r_water']); // if($have){ // return ['code'=>0,'msg'=>'此订单号已经体现过了']; // }else{ // $res = $this->tixianAgreeShopOrWork($jilu['r_water'],$jilu['r_money'],$jilu['r_acc_num'],$jilu['r_acc_username'],$remark); // if($res['status'] == 200){ // $last = Db::name('work_jilu')->where('r_id',$r_id) // ->update(['r_status'=>2,'r_remark'=>$remark,'r_res'=>2,'r_dotime'=>$today]);//r_res没用。。。 // if($last){ // //入消息和推送 // if ($jilu['r_type'] == 1) {//商户 // $where = 2; // } else { // $where = 3; // } // //消息和推送 // allInNotice('提现到账通知','您申请的'.$jilu['r_money'].'元的提现，已到账，请注意查收',$jilu['r_user_id']); // sendJpush("{$jilu['r_user_id']}", '您申请的'.$jilu['r_money'].'元的提现，已到账，请注意查收', array('a' => 'b'), 2, 2, $where); // return ['code'=>200,'msg'=>'操作成功']; // }else{ // return ['code'=>0,'msg'=>'提现成功但状态更改失败，请忽略此申请！']; // } // }else{ // return ['code'=>0,'msg'=>$res['msg']]; // } // } // }else{ // Db::startTrans(); // try { // Db::name('work_jilu')->where('r_id', $r_id) // ->update(['r_status' => 3, 'r_remark' => $remark, 'r_res' => 3,'r_dotime'=>$today]);//r_res没用。。。 // if ($jilu['r_type'] == 1) {//商户 // $where = 2; // Db::table('up_shops')->where('s_id', $jilu['r_user_id'])->setInc('s_money', $jilu['r_money']); // } else { // $where = 3; // Db::table('up_work_user')->where('user_id', $jilu['r_user_id'])->setInc('user_money', $jilu['r_money']); // } // Db::commit(); // //消息和推送 // allInNotice('提现驳回通知','您申请的'.$jilu['r_money'].'元的提现申请被驳回，原因：'.$remark,$jilu['r_user_id']); // sendJpush("{$jilu['r_user_id']}", '您申请的'.$jilu['r_money'].'元的提现申请被驳回', array('a' => 'b'), 2, 2, $where); // return ['status' => 200, 'msg' => '操作成功']; // } catch (\Exception $e) { // Db::rollback(); // return ['status' => 0, 'msg' => '操作失败']; // } // } // } // } /** * r_id,type 1是同意 2是拒绝,remark(备注) * @return \think\response\Json */ public function agreeOrRefuseTixian($r_id,$type,$remark) { $jilu = Db::name('work_jilu')->where('r_id',$r_id)->find(); if($jilu['r_where'] == 1){ if($jilu['r_status'] != 1){ return ['code'=>0,'msg'=>'已经操作过了，请刷新！']; }else{ $today = date('Y-m-d H:i:s'); $today2 = date('Y-m-d'); if($type == 1){//同意 $last = Db::name('work_jilu')->where('r_id',$r_id) ->update(['r_status'=>2,'r_remark'=>$remark,'r_res'=>2,'r_dotime'=>$today,'r_dodate'=>$today2,'r_doadmin'=>session('username')]);//r_res没用。。。 if($last){ //入消息和推送 if ($jilu['r_type'] == 1) {//商户 $where = 2; } else { $where = 3; } //消息和推送 // allInNotice('提现到账通知','您申请的'.$jilu['r_money'].'元的提现，已到账，请注意查收',$jilu['r_user_id']); // sendJpush("{$jilu['r_user_id']}", '您申请的'.$jilu['r_money'].'元的提现，已到账，请注意查收', array('a' => 'b'), 2, 2, $where); return ['code'=>200,'msg'=>'操作成功']; }else{ return ['code'=>0,'msg'=>'操作失败！']; } }else{ Db::startTrans(); try { Db::name('work_jilu')->where('r_id', $r_id) ->update(['r_status' => 3, 'r_remark' => $remark, 'r_res' => 3,'r_dotime'=>$today,'r_dodate'=>$today2,'r_doadmin'=>session('username')]);//r_res没用。。。 if ($jilu['r_type'] == 1) {//商户 $where = 2; Db::table('up_shops')->where('s_id', $jilu['r_user_id'])->setInc('s_money', $jilu['r_all_money']); } else { $where = 3; Db::table('up_work_user')->where('user_id', $jilu['r_user_id'])->setInc('user_money', $jilu['r_all_money']); } Db::commit(); //消息和推送 allInNotice('提现驳回通知','您申请的'.$jilu['r_all_money'].'元的提现申请被驳回，原因：'.$remark,$jilu['r_user_id']); sendJpush("{$jilu['r_user_id']}", '您申请的'.$jilu['r_all_money'].'元的提现申请被驳回', array('a' => 'b'), 2, 2, $where); return ['status' => 200, 'msg' => '操作成功']; } catch (\Exception $e) { Db::rollback(); return ['status' => 0, 'msg' => '操作失败']; } } } }else{ return ['status' => 0, 'msg' => '暂未开放支付宝和微信提现']; } } /* * 商户提现 */ public function businessMoney() { if(request()->isAjax ()){ extract(input()); $map = []; if(isset($key)&&$key!="") { $map['r_acc_username|r_water'] = ['like',"%" . $key . "%"]; } if(isset($who)&&$who!="") { $map['r_doadmin'] = $who; } if(isset($start)&&$start!=""&&isset($end)&&$end=="") { $map['r_dodate'] = ['>= time',$start]; } if(isset($end)&&$end!=""&&isset($start)&&$start=="") { $map['r_dodate'] = ['<= time',$end]; } if(isset($start)&&$start!=""&&isset($end)&&$end!="") { $map['r_dodate'] = ['between time',[$start,$end]]; } $map['r_type'] = 1; $Nowpage = input('page') ? input('page'):1; $limits = input("limit")?input("limit"):10;// 获取总条数; $count = Db::name('work_jilu j') ->join('shops u','u.s_id = j.r_user_id','left') ->where($map) ->count(); $lists = Db::name('work_jilu j') ->join('shops u','u.s_id = j.r_user_id','left') ->field('r_id,s_name as user_username,s_phone,r_money,r_all_money,r_status,r_acc_bank,r_time,r_water,r_acc_num,r_acc_username,r_where,r_doadmin') ->where($map) ->page($Nowpage,$limits) ->order('r_time desc') ->select(); return json(['code'=>0,'msg'=>'','count'=>$count,'data'=>$lists]); } $shenhes = $count = Db::name('work_jilu') ->where('r_type',1) ->field('r_doadmin') ->group('r_doadmin') ->select(); $this->assign('shenhes',$shenhes); return $this->fetch('money/business_money'); } /* * 商户提现 */ public function getShopMoney(){ extract(input()); $res = $this->agreeOrRefuseTixian($r_id,$type,$remark); return json($res); } /* * 商户批量提现 */ public function shopBatchMoney(){ extract(input()); if($r_id == ''){ return json(['code'=>100,'msg'=>'请选择要提现的记录！']); } $ids = explode(',',$r_id); foreach($ids as $key=>$vo){ $res = $this->agreeOrRefuseTixian($vo,$type,$remark); if($res['code'] != 200){ return json(['code'=>100,'msg'=>'ID:'.$vo.'商户提现失败']); } } return json(['code'=>200,'msg'=>'批量提现成功']); } /* * 业务员提现 */ public function salesmanMoney() { if(request()->isAjax ()){ extract(input()); $map = []; if(isset($key)&&$key!="") { $map['r_acc_username|r_water'] = ['like',"%" . $key . "%"]; } if(isset($who)&&$who!="") { $map['r_doadmin'] = $who; } if(isset($start)&&$start!=""&&isset($end)&&$end=="") { $map['r_dodate'] = ['>= time',$start]; } if(isset($end)&&$end!=""&&isset($start)&&$start=="") { $map['r_dodate'] = ['<= time',$end]; } if(isset($start)&&$start!=""&&isset($end)&&$end!="") { $map['r_dodate'] = ['between time',[$start,$end]]; } $map['r_type'] = 2; $Nowpage = input('page') ? input('page'):1; $limits = input("limit")?input("limit"):10;// 获取总条数; $count = Db::name('work_jilu j') ->join('work_user u','u.user_id = j.r_user_id','left') ->where($map) ->count(); $lists = Db::name('work_jilu j') ->join('work_user u','u.user_id = j.r_user_id','left') ->field('r_id,user_name,user_phone,r_money,r_all_money,r_status,r_acc_bank,r_time,r_water,r_acc_num,r_acc_username,r_where,r_doadmin') ->where($map) ->page($Nowpage,$limits) ->order('r_time desc') ->select(); return json(['code'=>0,'msg'=>'','count'=>$count,'data'=>$lists]); } $shenhes = $count = Db::name('work_jilu') ->where('r_type',2) ->field('r_doadmin') ->group('r_doadmin') ->select(); $this->assign('shenhes',$shenhes); return $this->fetch('money/salesman_money'); } /* * 业务员提现 */ public function getSaleMoney(){ extract(input()); $res = $this->agreeOrRefuseTixian($r_id,$type,$remark); return json($res); } /* * 业务员批量提现 */ public function shopSaleMoney(){ extract(input()); if($r_id == ''){ return json(['code'=>100,'msg'=>'请选择要提现的记录！']); } $ids = explode(',',$r_id); foreach($ids as $key=>$vo){ $res = $this->agreeOrRefuseTixian($vo,$type,$remark); if($res['code'] != 200){ return json(['code'=>100,'msg'=>'ID:'.$vo.'业务员提现失败']); } } return json(['code'=>200,'msg'=>'批量提现成功']); } }
<?php /** * Created by PhpStorm. * User: 戎大富 * Date: 2018/6/13 * Time: 10:40 */ namespace app\work\controller; use think\Controller; use think\Db; class Base extends Controller { protected $_error; protected $_header;//用户的请求头信息 protected $config = array( 'partner'=>'2088621781822784',//用不着 'seller_id'=>'admin@bagepanzi.com',//用不着 'sign_type'=>'RSA2',// 直接写死了 'it_b_pay'=>'10m',//用不着 'md5'=>'djqm7budkdlki6a76yasuyb9s1riiu1j',//用不着 'ali_public'=>'', 'public_key'=>"", 'private_key'=>'' ); // 定义配置项 private $config2=array( 'APPID' => 'wxa6a14bfed0d430bf', // 微信支付APPID. 'MCHID' => '1515748591', // 微信支付MCHID 商户收款账号 'KEY' => '', // 微信支付KEY 'APPSECRET' => '', // 公众帐号secert (公众号支付专用) 'NOTIFY_URL' => 'http://red.hjv5.com/work/Index/huidiaoWx', // 接收支付状态的连接 ); public function __construct() { // parent::__construct(); } /** * 验证唯一——单点登录 * user_id，time，salt，value * @return string */ public function checkAll($uid,$time,$value,$reqKey){//$uid,$time,$value header("Access-Control-Allow-Origin:*"); if($uid == '0'){ return true; }else{ $user = Db::table('up_work_user')->where('user_id',$uid)->find(); if(!$user){return false;} if($user['user_status'] != 1){ return false; } $token = $user['user_token']; $appId = "A6070308312682"; $appkey = "9AF807B0-BE12-F521-6998-6D57B0CCE8BB"; $myreqKey = md5($appId . 'XW' . $appkey . 'XW' . $time); $myvalue = md5($uid . 'XW' . $token . 'XW' . $time); if($myvalue != $value || $myreqKey != $reqKey){ return false; }else{ return true; } } } /** * 云之讯发送短信 * @param $phone * @param $num * @return mixed */ public function duaxin($phone,$num){ $body_json = array( 'sid'=>'2b6e76df39bef2e4a99eee7b77225c91', 'token'=>'26a41e1a5b90f6a0bd2e4fb4fb6a713e', 'appid'=>'760e6b2f0a45439585835cbed2e12e18', 'templateid'=>'373248', 'param'=>$num, 'mobile'=>$phone, 'uid'=>'', ); $body = json_encode($body_json); $header = array( 'Accept:application/json', 'Content-Type:application/json;charset=utf-8', ); $url = 'https://open.ucpaas.com/ol/sms/sendsms'; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, $header); curl_setopt($ch,CURLOPT_POST,1); curl_setopt($ch,CURLOPT_POSTFIELDS,$body); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); $result = curl_exec($ch); curl_close($ch); $res = json_decode($result,true); return $res; } function diffBetweenTwoDays ($day2) { $day1 = date('Y-m-d'); $second1 = strtotime($day1); $second2 = strtotime($day2); if ($second1 < $second2) { $tmp = $second2; $second2 = $second1; $second1 = $tmp; } return ($second1 - $second2) / 86400; } /** * 获取任意长度的随机字符串 * @param $length * @return string */ // function getRandChar($length) // { // $chars = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', // 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', // 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', // 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', // 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', // '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'); // $char_txt = ''; // for ($i = 0; $i < $length; $i++) { // $char_txt .= $chars[array_rand($chars)]; // } // return $char_txt; // } public function uuid($prefix = '') { $chars = md5(uniqid(mt_rand(), true)); $uuid = substr($chars,0,8); $uuid .= substr($chars,8,4); $uuid .= substr($chars,12,4); $uuid .= substr($chars,16,4); $uuid .= substr($chars,20,12); return $prefix . $uuid; } /** * 获取我的专属编号 * @param $unique_no * @return bool|string */ public function getMyNum($unique_no){ $num = Db::table('up_work_user')->where('user_mynum',$unique_no)->find(); if($num){ $unique_no = substr(base_convert(md5(uniqid(md5(microtime(true)),true)), 16, 10), 0, 5); return $this->getMyNum($unique_no); }else{ return $unique_no; } } /** * 验证码 * @param $length * @return string */ function getCodeChar($length) { $chars = array( '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'); $char_txt = ''; for ($i = 0; $i < $length; $i++) { $char_txt .= $chars[array_rand($chars)]; } return $char_txt; } public function getAcount() { //==========base里放到=============== $zimu = range('a','z'); $one = rand(0,25); $two = rand(0,25); $thr = rand(0,25); $four = rand(0,25); $zimu2 = $zimu[$one].$zimu[$two].$zimu[$thr].$zimu[$four]; $num = rand(100000,999999); return $zimu2.$num; //========================= } /** * @param $no * @param $money * @return string * 支付宝支付 */ public function getParam($no,$money){ // header("Content-type: text/html; charset=utf-8"); require_once '/data/wwwroot/red.hjv5.com/extend/aliqrcode/f2fpay/model/builder/AlipayTradePrecreateContentBuilder.php'; require_once '/data/wwwroot/red.hjv5.com/extend/aliqrcode/f2fpay/service/AlipayTradeService.php'; $outTradeNo = $no; // (必填) 订单标题，粗略描述用户的支付目的。如“xxx品牌xxx门店当面付扫码消费” $subject = '商户入驻'; // (必填) 订单总金额，单位为元，不能超过1亿元 // 如果同时传入了【打折金额】,【不可打折金额】,【订单总金额】三者,则必须满足如下条件:【订单总金额】=【打折金额】+【不可打折金额】 $totalAmount = $money; // 订单描述，可以对交易或商品进行一个详细地描述，比如填写"购买商品2件共15.00元" $body = "商户入驻费用"; // 支付超时，线下扫码交易定义为5分钟 $timeExpress = "5m"; // 创建请求builder，设置请求参数 $qrPayRequestBuilder = new \AlipayTradePrecreateContentBuilder(); $qrPayRequestBuilder->setOutTradeNo($outTradeNo); $qrPayRequestBuilder->setTotalAmount($totalAmount); $qrPayRequestBuilder->setTimeExpress($timeExpress); $qrPayRequestBuilder->setSubject($subject); $qrPayRequestBuilder->setBody($body); // 调用qrPay方法获取当面付应答 $alipay_config = array( 'gatewayUrl'=>'https://openapi.alipay.com/gateway.do',//用不着 'app_id'=>'2018090761306686',//用不着 'sign_type'=>'RSA2',// 直接写死了 'merchant_private_key'=>'[binary]',//用不着 'alipay_public_key'=>'[binary]',//用不着 'charset'=>'UTF-8', 'MaxQueryRetry'=>"5", 'QueryDuration'=>'5', 'notify_url'=>'http://red.hjv5.com/work/Index/huidiao' ); $qrPay = new \AlipayTradeService($alipay_config); $qrPayResult = $qrPay->qrPay($qrPayRequestBuilder); if ($qrPayResult->getTradeStatus() == 'SUCCESS'){ $response = $qrPayResult->getResponse(); $qrcode = $response->qr_code; return array('status'=>200,'msg'=>$qrcode); }else{ return array('status'=>0,'msg'=>'失败'); } } public function checkReturn(){ import('alipay.aop.AopClient',EXTEND_PATH); $aop = new \AopClient; $aop->alipayrsaPublicKey = $this->config['ali_public']; $flag = $aop->rsaCheckV1($_POST, NULL, "RSA2"); if($flag){ return $_POST; }else{ return false; } } /** *支付宝的原路退款接口 */ public function refund($payInfo){ //仨参数：order_id,order_user_pay,order_number import('alipay.aop.AopClient',EXTEND_PATH); import('alipay.aop.request.AlipayTradeRefundRequest',EXTEND_PATH); $aop = new \AopClient; $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do'; $aop->appId = '2018090761306686'; $aop->rsaPrivateKey = $this->config['private_key']; $aop->alipayrsaPublicKey=$this->config['ali_public']; $aop->apiVersion = '1.0'; $aop->signType = 'RSA2'; $aop->postCharset='UTF-8'; $aop->format='json'; $request = new \AlipayTradeRefundRequest; $refundAmount = $payInfo['money']; // $refundAmount = 0.01; $request->setBizContent("{" . "\"out_trade_no\":\"".$payInfo['number']."\"," . "\"trade_no\":\"\"," . "\"refund_amount\":".$refundAmount."," . "\"refund_reason\":\"退款\"" . " }"); $result = $aop->execute($request); $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response"; $resultCode = $result->$responseNode->code; if(!empty($resultCode) && $resultCode == 10000){ return array('status'=>200,'msg'=>'操作成功'); }else{ return array('status'=>0,'msg'=>'调用接口失败'); } } //-------------------------**********************微信支付***********************------------------------------------ //-------------------------**********************微信支付***********************------------------------------------ //-------------------------**********************微信支付***********************------------------------------------ //-------------------------**********************微信支付***********************------------------------------------ public function WeChatPayReady($order,$type=false){ // 获取配置项 $weixinpay_config2=$this->config2; $config2 = array( 'appid'=>$weixinpay_config2['APPID'], 'mch_id'=>$weixinpay_config2['MCHID'], 'nonce_str'=>'test', 'spbill_create_ip'=>$_SERVER['REMOTE_ADDR'], 'notify_url'=>$weixinpay_config2['NOTIFY_URL'] ); if($type){ $config2['notify_url']=$type; } // 合并配置数据和订单数据 $data=array_merge($order,$config2); // 生成签名 $sign=$this->makeSign($data); $data['sign']=$sign; $xml=$this->toXml($data); $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';//接收xml数据的文件 $header[] = "Content-type: text/xml";//定义content-type为xml,注意是数组 $ch = curl_init ($url); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE); curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);//严格校验 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $header); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $xml); $response = curl_exec($ch); if(curl_errno($ch)){ print curl_error($ch); } curl_close($ch); $result=$this->toArray($response); if($result['return_code'] == 'FAIL'){ $returnerr['msg'] = $result['return_msg']; $returnerr['type'] = 'error'; return $returnerr; }else{ $result['sign']=$sign; $result['nonce_str']='test'; $result2 = $this->getOrder($result['prepay_id']); return $result;/// } } /** * 获取时间 * @return array */ public function getDateBytimeDate($string){ $replacement = '-'; $replacement2 = ':'; $a = substr_replace($string, $replacement, 4, 0); $b = substr_replace($a, $replacement, 7, 0); $c = substr_replace($b, ' ', 10, 0); $d = substr_replace($c, $replacement2, 13, 0); $e = substr_replace($d, $replacement2, 16, 0); return $e; } /** * 输出xml字符 * @throws WxPayException **/ public function toXml($data){ //var_dump($data); if(!is_array($data) || count($data) <= 0){ //throw new WxPayException("数组数据异常！"); } $xml = "<xml>"; foreach ($data as $key=>$val){ if (is_numeric($val)){ $xml.="<".$key.">".$val."</".$key.">"; }else{ $xml.="<".$key."> ".$val." </".$key.">"; } } $xml.="</xml>"; return $xml; } /** * 生成签名 * @return 签名，本函数不覆盖sign成员变量，如要设置签名需要调用SetSign方法赋值 */ public function makeSign($data){ // 去空 $data=array_filter($data); //签名步骤一：按字典序排序参数 ksort($data); $string_a=http_build_query($data); $string_a=urldecode($string_a); //签名步骤二：在string后加入KEY $config2=$this->config2; $string_sign_temp=$string_a."&key=".$config2['KEY']; //签名步骤三：MD5加密 $sign = md5($string_sign_temp); // 签名步骤四：所有字符转为大写 $result=strtoupper($sign); return $result; } /** * 将xml转为array * @param string $xml xml字符串 * @return array 转换得到的数组 */ public function toArray($xml){ //禁止引用外部xml实体 libxml_disable_entity_loader(true); $result= json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true); return $result; } //获取指定长度的随机字符串 function getRandChar($length){ $str = null; $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz"; $max = strlen($strPol)-1; for($i=0;$i<$length;$i++){ $str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数 } return $str; } //执行第二次签名，才能返回给客户端使用 public function getOrder($prepayId){ $data["appid"] = $this->config2["APPID"]; $data["noncestr"] = $this->getRandChar(32); $data["package"] = "Sign=WXPay"; $data["partnerid"] = $this->config2['MCHID']; $data["prepayid"] = $prepayId; $data["timestamp"] = time(); $s = $this->makeSign($data, false); $data["sign"] = $s; return $data; } /** * app支付统一退款 */ public function refundWx($payInfo,$refundNo=''){ $refundNo = date('YmdHis') . rand(100000, 999999); //transaction_id,money,number // public function refundWx(){ header("content-type:text/html;charset=utf-8"); $url = "https://api.mch.weixin.qq.com/secapi/pay/refund"; $data["appid"] = $this->config2['APPID'];//微信开放平台审核通过的应用APPID $data["mch_id"] = $this->config2['MCHID'];//商户号 $data["nonce_str"] = $this->getRandChar(32);//随机字符串 $data["out_refund_no"] = $refundNo; $data["refund_fee"] = $payInfo['money']*100; // $data["refund_fee"] = 1;//todo 测试阶段全部按一分进行计算 $data["total_fee"] = $data['refund_fee'];//总金额按乘以100进行计算 $data["transaction_id"] = $payInfo['transaction_id'];//微信官方唯一订单识别号 $data["out_trade_no"] = $payInfo['number']; $data["refund_fee_type"] = "CNY"; $data["refund_account"] = "REFUND_SOURCE_UNSETTLED_FUNDS"; $sign=$this->getSignRefund($data,$this->config2['KEY']); $data['sign']=$sign; $xml=$this->toXml($data); $response = $this->postXmlCurl($xml, $url,'',true,'/workcert/apiclient_cert.pem','/workcert/apiclient_key.pem'); $responseArr=$this->toArray($response); if(!is_array($responseArr) || count($responseArr)<=0){ $return['msg'] = '网络请求繁忙'; $return['status'] = 0; }else if($responseArr['return_code'] == 'FAIL'){ $return['msg'] = $responseArr['return_msg']; $return['status'] = 0; }else{ $chaxun = $this->refundWxChaxun($refundNo); if($chaxun['status'] == 200){ //二次签名 $return['text'] = $responseArr; // 直接返回 $return['status'] = 200; }else{ $return['msg'] = $chaxun['msg']; $return['status'] = 0; } } return $return; } /** * app支付统一退款查询：微信退款就算余额不足也会返回成功，所以要先查询判断 */ public function refundWxChaxun($refundNo){ // public function refundWxChaxun(){ // $refundNo = '4200000209201812224948560415'; // header("content-type:text/html;charset=utf-8"); $url = "https://api.mch.weixin.qq.com/pay/refundquery"; $data["appid"] = $this->config2['APPID'];//微信开放平台审核通过的应用APPID $data["mch_id"] = $this->config2['MCHID'];;//商户号 $data["nonce_str"] = $this->getRandChar(32);//随机字符串 $data["out_refund_no"] = $refundNo; $sign=$this->getSignRefund($data,'MqIgEfTSiVhudPBnp5dyERv6qxi9Ixhq'); $data['sign']=$sign; $xml=$this->toXml($data); $response = $this->postXmlCurl($xml, $url,'',false,'',''); $responseArr=$this->toArray($response); if(!is_array($responseArr) || count($responseArr)<=0){ $return['msg'] = '网络请求繁忙'; $return['status'] = 0; }else if($responseArr['return_code'] == 'FAIL'){ $return['msg'] = $responseArr['return_msg']; $return['status'] = 0; }else{ if($responseArr['result_code'] == 'SUCCESS'){ $return['msg'] = 'ok'; $return['status'] = 200; }else{ if($responseArr['err_code_des'] == 'not exist'){ $responseArr['err_code_des'] = '商户平台余额不足，请联系管理员充值'; } $return['msg'] = $responseArr['err_code_des']; $return['status'] = 0; // $return = $responseArr; } } // dump($return);die; return $return; } /** * app支付统一退款(商户推荐的商户 退款) */ public function refundWxShop($payInfo,$refundNo=''){ $refundNo = date('YmdHis') . rand(100000, 999999); //transaction_id,money,number // public function refundWx(){ header("content-type:text/html;charset=utf-8"); $url = "https://api.mch.weixin.qq.com/secapi/pay/refund"; $data["appid"] = 'wx8ab4cc1831384ba3';//微信开放平台审核通过的应用APPID $data["mch_id"] = '1515746111';//商户号 $data["nonce_str"] = $this->getRandChar(32);//随机字符串 $data["out_refund_no"] = $refundNo; $data["refund_fee"] = $payInfo['money']*100; // $data["refund_fee"] = 1;//todo 测试阶段全部按一分进行计算 $data["total_fee"] = $data['refund_fee'];//总金额按乘以100进行计算 $data["transaction_id"] = $payInfo['transaction_id'];//微信官方唯一订单识别号 $data["out_trade_no"] = $payInfo['number']; $data["refund_fee_type"] = "CNY"; $data["refund_account"] = "REFUND_SOURCE_UNSETTLED_FUNDS"; $sign=$this->getSignRefund($data,'2XWCaOA2m2u1Se2SrMjeNvXSSUcZjMkN'); $data['sign']=$sign; $xml=$this->toXml($data); $response = $this->postXmlCurl($xml, $url,'',true,'/shopcert/apiclient_cert.pem','/shopcert/apiclient_key.pem'); $responseArr=$this->toArray($response); if(!is_array($responseArr) || count($responseArr)<=0){ $return['msg'] = '网络请求繁忙'; $return['status'] = 0; }else if($responseArr['return_code'] == 'FAIL'){ $return['msg'] = $responseArr['return_msg']; $return['status'] = 0; }else{ //二次签名 $return['text'] = $responseArr; // 直接返回 $return['status'] = 200; } return $return; } function getSignRefund($obj, $api_key) { foreach ($obj as $k => $v) { $Parameters[strtolower($k)] = $v; } //签名步骤一：按字典序排序参数 ksort($Parameters); $String = $this->formatBizQueryParaMap($Parameters, false); //签名步骤二：在string后加入KEY $String = $String."&key=".$api_key; //签名步骤三：MD5加密 $result = strtoupper(md5($String)); // $result = hash_hmac("sha256",stringSignTemp,key); return $result; } function formatBizQueryParaMap($paraMap, $urlencode) { $buff = ""; ksort($paraMap); foreach ($paraMap as $k => $v) { if($urlencode) { $v = urlencode($v); } $buff .= strtolower($k) . "=" . $v . "&"; } $reqPar = ''; if (strlen($buff) > 0) { $reqPar = substr($buff, 0, strlen($buff)-1); } return $reqPar; } function postXmlCurl($xml, $url, $second=30, $useCert=false, $sslcert_path, $sslkey_path) { $ch = curl_init(); //设置超时 curl_setopt($ch, CURLOPT_TIMEOUT, $second); curl_setopt($ch,CURLOPT_URL, $url); //设置header curl_setopt($ch, CURLOPT_HEADER, FALSE); //要求结果为字符串且输出到屏幕上 curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE); curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE); if($useCert == true){ curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false); curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false); // curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,TRUE); // curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,1);//严格校验 //设置证书 $path = $_SERVER['DOCUMENT_ROOT']; curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM'); curl_setopt($ch,CURLOPT_SSLCERT, $path.$sslcert_path); curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM'); curl_setopt($ch,CURLOPT_SSLKEY, $path.$sslkey_path); // curl_setopt($ch,CURLOPT_CAINFO, __DIR__.'/cert/rootca.pem'); } //post提交方式 curl_setopt($ch, CURLOPT_POST, TRUE); curl_setopt($ch, CURLOPT_POSTFIELDS, $xml); //运行curl $data = curl_exec($ch); //返回结果 if($data){ curl_close($ch); return $data; } else { $error = curl_errno($ch); curl_close($ch); return false; } } }