· 6 years ago · Jan 22, 2020, 11:40 PM
1?
2 class Shop extends Mysql {
3 var $orderNo;
4 var $objSF;
5 var $objSM;
6 var $isGroupShipping;
7 var $isBanderAccountSend;
8
9 function userPathLog($ip, $uri, $session){
10 $sql = "insert into sf_user_path_log set ip='".$ip."', url='".$uri."', session_info='".$session."'";
11 $this->query($sql);
12 }
13 // 1,0,,new,1,24
14 function getGoodsList($cate=0,$cate2=0,$cond,$order="",$page,$limit) {
15 global $shop_info;
16 $cond = "a.gs_stats='1'".$cond;
17 $cond .= " and gs_nation='".$_SESSION[lang]."'";
18 $join = 'left join sf_order b on a.gs_idx=b.goods_idx ';
19 $addSelect = '';
20 $order_origin = $order;
21
22 # Custom Category
23 if(is_numeric($order)) {
24 $cond.=" and a.gs_cate_adm='".$order."'";
25 }
26
27 # Category
28 if($cate > 0) {
29 $cond .= " and a.gs_cate='".$cate."'";
30 }
31 if($cate2 > 0) {
32 $cond .= " and a.gs_cate2='".$cate2."'";
33 }
34
35 # order bys & conditions
36 switch($order) {
37 case "new_category" : $order = "order by a.gs_idx desc"; break;
38 case "new" : $order = "order by a.gs_idx desc"; break;
39 case "price_a" : $order = "order by a.gs_price"; break;
40 case "price_d" : $order = "order by a.gs_price desc"; break;
41 case "dfree" : $order = "order by count(b.idx) desc,a.gs_idx desc";$cond.=" and a.gs_deliver_free='1' and gs_deliver_free_price=0"; break;
42 case "best" : $order = "order by count(b.idx) desc,a.gs_idx desc"; break;
43 case "date" : $order = "order by gs_regDate desc"; break;
44 default : $order = "order by a.gs_idx desc"; break;
45 }
46
47 # offset
48 if(!$page) $page = 1;
49 if($order!='margin') {
50 $start = ($page-1)*$limit;
51 }
52
53 $uris = explode("/",$_SERVER['REQUEST_URI']);
54
55 # 개인상점 접속시
56 if($_SESSION['private_shop']) {
57 $addSelect .= ",c.seq,c.price as myprice";
58 $join .= "left join sm_mysale c on a.gs_idx=c.pr_idx";
59 //$cond .= " and (c.shop_id='".$_SESSION[private_shop]."' or (find_in_set('".$_SESSION[private_shop]."',a.gs_is_sellers)<>0 and c.shop_id='".$_SESSION[private_shop]."')) ";
60 $cond .= " and c.shop_id='".$_SESSION[private_shop]."'"; // 링크를 이미 펐다는건 내가 판매 가능한 제품임. 고로 이 조건만 있으면 됨
61 $order = "order by c.idx desc";
62 # 셀러가 상품 볼 시
63 } else if(isSellerSession()) {
64 $cond .= " and (find_in_set('".$_SESSION['seller_id']."',a.gs_is_sellers) <> 0 or a.gs_is_sellers ='') ";
65 # 일반 유저 혹은 비회원이 개인상점이 아닌 루트로 왔을시..(주문조회 후 카테고리 클릭)
66 } else {
67 return "0";
68 }
69
70 # 임대몰인 경우와 아닌경우
71 $join .= " left join sf_shop d on a.shop_idx=d.shop_idx";
72 if($shop_info[shop_type]=="2") {
73
74 # 신규기능 - 임대몰인 소마 제품을 보여줄지 여부를 설정하여 소마 상품을 노출, 비노출 할 수 있다. 비노출 시 이때 임대몰은 자기 도메인이 반드시 있어야 하며 180716
75 # 임대몰 제품만 노출시 하위몰이 올린 제품도 함께 노출된다
76 if($shop_info['view_default_goods']=='2') {
77 $cond .= " and (d.shop_idx=".$shop_info['shop_idx']." or a.shop_idx_parent=".$shop_info['shop_idx'].")";
78 }
79
80 # 임대몰일시 먼저 임대몰간 제품공유 설정에 따른 쿼리 로드
81 // if($_SERVER['REMOTE_ADDR']=='221.149.108.241') {
82 $conds = $this->getGroupQuery($shop_info['shop_idx'],$shop_info['view_default_goods']);
83 // }
84 if($conds) {
85 $cond .= $conds;
86 }
87
88 } else {
89 # 방판이 아닌 경우는 방판 제품 판매 불가
90 $cond .= " and d.shop_type='1'";
91 }
92 # 쿼리 생성
93 // if($_SERVER['REMOTE_ADDR']=='221.149.108.241') {
94 $qry = "select a.gs_idx,a.shop_idx,a.gs_cate,a.gs_cate2,a.gs_name,a.gs_price_factory,a.gs_price,a.gs_price_origin,a.gs_price_margin,a.gs_thumbsrc,a.gs_image1,a.gs_image2 $addSelect from sf_goods a $join where $cond group by a.gs_idx $order limit $start,$limit";
95 // } else {
96 // $qry = "select a.* $addSelect from sf_goods a $join where $cond group by a.gs_idx $order limit $start,$limit";
97 // }
98
99 // echo $qry;
100 $res = $this->fetchs($qry);
101 $qry = "select a.gs_idx from sf_goods a $join where $cond group by a.gs_idx";
102 $tRes = $this->numRows($qry);
103 $res[0][list_total] = $tRes;
104 return $res;
105 }
106
107 function getGroupQuery($shop_idx,$default_goods='1') {
108 $gr_info = $this->getGroupAuth($shop_idx);
109 if($default_goods=='2') { // 기본제품 비노출시 해당 벤더 또는 하위벤더 제품만
110 $qry = " and (a.shop_idx=".$shop_idx." or a.shop_idx_parent=".$shop_idx;
111 } else {
112 $qry = " and (d.shop_type='1' or a.shop_idx=".$shop_idx;
113 }
114 if($gr_info['shop_idx'] && $gr_info['shop_id']) { // 제품 공유 데이터가 있을때
115 if(trim($gr_info['shop_idxs'])) { // 몰 전체로부터 공유받은 경우
116 $qry .= " or a.shop_idx in (".$gr_info['shop_idxs'].")";
117 }
118 /* 카테고리 및 제품별 공유 기능은 추후에 필요하면 오픈 [수정 필요할거임] */
119 // if(trim($gr_info[cate_idxs])) {
120 // $arr_cates = explode('|',$gr_info[cate_idxs]);
121 // for($i=0;$i<count($arr_cates);$i++) {
122 // $ex_tmp = explode(',',$arr_cates[$i]);
123 // if($ex_tmp[0] && $ex_tmp[1]) {
124 // $qry .= " or (a.shop_idx=".$ex_tmp[0]." and a.gs_cate='".$ex_tmp[1]."')";
125 // }
126 // }
127 // }
128 // if(trim($gr_info[goods_idxs])) {
129 // $qry .= " or (a.gs_idx in (".$gr_info[goods_idxs]."))";
130 // }
131 }
132 $qry .=")";
133 return $qry;
134 }
135 function getGroupAuth($shop_idx) {
136 return $this->fetch1("select a.*,b.shop_id from sf_goods_auth a left join sf_shop b on a.shop_idx=b.shop_idx where a.shop_idx=".$shop_idx);
137 }
138 ### @ 판매제품 정보 가져오기
139 function getGoodsInfo($gs_idx,$seller_flag='1') {
140 if(!$gs_idx) return false;
141 if($seller_flag=='1') {
142 if($_SESSION[from_seller_id] && $_SESSION[from_seller_gs_seq]) {
143 $q = sprintf("select pr_idx from sm_mysale where seq=%d and shop_id='%s' limit 1",$_SESSION[from_seller_gs_seq],$_SESSION[from_seller_id]);
144 $chk = $this->fetch1($q);
145 if(!$chk[pr_idx]) return false;
146 $gs_idx = $chk[pr_idx];
147 $_SESSION[from_seller_gs_idx] = $gs_idx;
148 }
149 }
150 $q = sprintf("select * from sf_goods where gs_idx=%d limit 1",$gs_idx);
151 $gs_data = $this->fetch1($q);
152 if($gs_data[gs_idx]) {
153 //$arrImgs = array();
154 //$arrImgsColor = array();
155 //$arrSize = explode('[**]',$gs_data[gs_sizeInfo]);
156 //$arrAttr = explode('[**]',$gs_data[gs_attrInfo]);
157 if(trim($gs_data['gs_thumbsrc'])) {
158 $gs_data['thumb'] = $gs_data['gs_thumbsrc'];
159 } else if(trim($gs_data['gs_image1'])) {
160 $gs_data['thumb'] = $_ENV['goods_img_path'].'/'.$gs_idx.'/'.$gs_data['gs_image1'];
161 } else if(trim($gs_data['gs_image2'])) {
162 $gs_data['thumb'] = $_ENV['goods_img_path'].'/'.$gs_idx.'/'.$gs_data['gs_image2'];
163 }
164 // for($i=1;$i<=5;$i++) {
165 // if($gs_data['gs_image'.$i]) {
166 // if(file_exists($_ENV['goods_img_root']."/".$gs_idx."/".$gs_data['gs_image'.$i])) {
167 // array_push($arrImgs,$_ENV['goods_img_path']."/".$gs_idx."/".$gs_data['gs_image'.$i]);
168 // }
169 // }
170 // }
171 // for($i=1;$i<=7;$i++) {
172 // if($gs_data['gs_img_color'.$i]) {
173 // if(file_exists($_ENV['goods_img_root']."/".$gs_idx."/".$gs_data['gs_img_color'.$i])) {
174 // array_push($arrImgsColor,$_ENV['goods_img_path']."/".$gs_idx."/".$gs_data['gs_img_color'.$i]);
175 // }
176 // }
177 // }
178 //$tsp = explode('[**]',$gs_data[gs_img_color_tits]);
179 //$gs_data['thumbs'] = $arrImgs;
180 //$gs_data['thumbs_color'] = $arrImgsColor;
181 //$gs_data['size'] = $arrSize;
182 //$gs_data['attr'] = $arrAttr;
183 //$gs_data['color_tits'] = explode('|',$tsp[0]);
184 //$gs_data['color_tits_sub'] = explode('|',$tsp[1]);
185 $gs_data['now_gs_price'] = $_SESSION[seller] ? $gs_data[gs_price_factory] : $gs_data[gs_price];
186 return $gs_data;
187 } else {
188 return false;
189 }
190 }
191
192 function getGoodsThumbs($gs_data) {
193 $arrImgs = array();
194 for($i=1;$i<=5;$i++) {
195 if($gs_data['gs_image'.$i]) {
196 // if(file_exists($_ENV['goods_img_root']."/".$gs_data[gs_idx]."/".$gs_data['gs_image'.$i])) {
197 array_push($arrImgs,$_ENV['goods_img_path']."/".$gs_data[gs_idx]."/".$gs_data['gs_image'.$i]);
198 // }
199 }
200 }
201 if(count($arrImgs)==0) {
202 if(trim($gs_data['gs_thumbsrc'])) {
203 array_push($arrImgs,$gs_data['gs_thumbsrc']);
204 }
205 }
206 return $arrImgs;
207 }
208
209 function getGoodsDetailImgs($gs_data) {
210 $res = array();
211 if($gs_data['gs_image_detail']) {
212 $ex = explode('|',$gs_data['gs_image_detail']);
213 for($i=0;$i<count($ex);$i++) {
214 // if(file_exists($_ENV['goods_img_root']."/".$gs_data['gs_idx']."/gs_img_detail".($i+1).'.'.$ex[$i])) {
215 if(trim($ex[$i])) {
216 array_push($res,$_ENV['goods_img_path']."/".$gs_data['gs_idx']."/gs_img_detail".($i+1).'.'.$ex[$i]);
217 }
218
219 // } else {
220 // array_push($res,'');
221 // }
222 }
223 }
224 return $res;
225 }
226 function getBrandInfo($idx) {
227 if(is_numeric($idx)) {
228 $q = "select * from sf_goods_brand where brand_idx=".$idx;
229 } else {
230 $q = "select * from sf_goods_brand where brand_name='".$idx."'";
231 }
232 //die($q);
233 return $this->fetchOne($q);
234 }
235
236 function getMarketName($s_id) {
237 $q = "select seller_name from sf_member where seller_id='".$s_id."'";
238 return $this->fetchOne($q);
239 }
240
241 # 카테고리 이름 얻기
242 function getCateName($ct_idx) {
243 if($ct_idx) {
244 if($_SESSION['lang']=='kr') {
245 $f = "ct_name";
246 } else if($_SESSION['lang']=='cn') {
247 $f = "ct_name_cn as ct_name";
248 } else if($_SESSION['lang']=='en') {
249 $f = "ct_name_en as ct_name";
250 }
251 $res = $this->fetchOne("select $f from sf_category where ct_idx=$ct_idx");
252 if($res[ct_name]) return $res[ct_name];
253 }
254 }
255 function getCateName2($name) {
256 //return array('1'=>'시즌 MD 추천제품','2'=>'시즌 신상품','3'=>'디자이너 브랜드 리스트');
257 switch($name) {
258 case "1" : $resName = "시즌 MD 추천제품"; break;
259 case "2" : $resName = "시즌 신상품"; break;
260 case "3" : $resName = "디자이너 브랜드 리스트"; break;
261 }
262 return $resName;
263 }
264
265 function getAgencyFee($seller_id) {
266 $chk = $this->fetch1("select fee from sf_member where seller_id='".$seller_id."'");
267 if($chk['fee'] > 0) {
268 return $chk['fee'];
269 } else {
270 return "0.00";
271 }
272 }
273 function getMallFee($data,$type='1') { // type 1 셀러아이디로 가져오기, 2 임대몰 아이디로 가져오기
274 if($type=='1') {
275 $chk = $this->fetch1("select a.shop_fee from sf_shop a left join sf_member b on a.shop_id=b.seller_recom
276 where b.seller_type='2' and b.seller_id='".$data."' limit 1");
277 } else if($type=='2') {
278 $chk = $this->fetch1("select shop_fee from sf_shop where shop_id='".$data."' limit 1");
279 }
280 if($chk['shop_fee'] > 0) {
281 return $chk['shop_fee'];
282 } else {
283 return "0";
284 }
285 }
286
287
288 function getSellerMargin($goods_idx,$seller_id) {
289 $q = sprintf("select if(b.price > 0,b.price,a.gs_price)-(a.gs_price_factory+a.gs_price_margin) as margin
290 from sf_goods a left join sm_mysale b on a.gs_idx=b.pr_idx
291 where a.gs_idx=%d and b.shop_id='%s'",$goods_idx,$seller_id);
292 $res = $this->fetch1($q);
293 return $res[margin] > 0 ? $res[margin] : 0;
294 }
295 function getSellerPayFromOrder($order_no,$seller_id,$pt_flag='1') {
296 // $pt_flag 가 1이면 포인트를 빼지 않고 2면 빼준다
297 if($pt_flag=='2') {
298 $addJoin = " left join sf_user_point_stack c on a.order_no = c.order_no ";
299 $addQ = " - ifnull(c.point,0)";
300 }
301 if(!$this->isAgency($seller_id)) { // 에이전시가 아닌경우만
302 $recom = $this->isBelongAgency($seller_id);
303 if($recom) { // 에이전시에 속한 아이디면
304 $agency_fee = $this->getAgencyFee($recom);
305 $q = sprintf("select (a.pay_gs_price-a.pay_shipp_price)
306 - ((b.gs_price_factory+b.gs_price_margin)*a.quantity)
307 - (ROUND(b.gs_price*%d)*a.quantity)
308 - ifnull(a.opts_price_factory,0) $addQ as margin
309 from sf_order a
310 left join sf_goods b on a.goods_idx = b.gs_idx
311 $addJoin
312 where a.order_no='%s' and (a.stats='2' or a.stats='3' or a.stats='4')
313 and a.seller_id='%s' and a.seller_id is not null"
314 ,$agency_fee,$order_no,$seller_id);
315 } else { // 일반 셀러
316 $q = sprintf("select (a.pay_gs_price-a.pay_shipp_price)
317 - ((b.gs_price_factory+b.gs_price_margin)*a.quantity)
318 - ifnull(a.opts_price_factory,0) $addQ as margin
319 from sf_order a
320 left join sf_goods b on a.goods_idx = b.gs_idx
321 $addJoin
322 where a.order_no='%s'
323 and (a.stats='2' or a.stats='3' or a.stats='4')
324 and a.seller_id='%s' and a.seller_id is not null
325 "
326 ,$order_no,$seller_id);
327 }
328 $res = $this->fetch1($q);
329 return $res['margin'];
330 }
331 }
332 function getSellerPay($search_year,$search_month,$seller_id) { // 실제 정산용 금액이기에 포인트 빼줘야 함
333 $res = array();
334 $is_saas = $this->isBelongSaas($seller_id);
335 $recom = $this->isBelongAgency($seller_id);
336 $shop_info = $this->getShopInfo($recom);
337 $add_mul_factory_price = 0;
338 if($is_saas) {
339 $mall_fee = $this->getMallFee($seller_id); // 임대몰 수수료가 있는경우
340 if($mall_fee > 0) {
341 $add_mul_factory_price = $mall_fee;
342 $mall_margin = $this->fetch1("select sum((b.gs_price_factory+b.gs_price_margin)*$add_mul_factory_price)*a.quantity as mall_margin from sf_order a left join sf_goods b on a.goods_idx = b.gs_idx left join sf_user_point_stack c on a.order_no = c.order_no
343 where SUBSTRING_INDEX(a.orderTime,'-',1)='".$search_year."' and SUBSTRING_INDEX(SUBSTRING_INDEX(a.orderTime, '-', -2), '-', 1)='".$search_month."'
344 and (a.stats='2' or a.stats='3' or a.stats='4') and
345 a.seller_id<>'' and a.seller_id is not null and seller_id='".$seller_id."'");
346 $mall_margin = $mall_margin['mall_margin'] > 0 ? $mall_margin['mall_margin'] : 0;
347 }
348 }
349 // echo "is Sass : ".$is_saas;
350 // echo "fee : $add_mul_factory_price";
351
352 $q_h = "select sum(a.pay_gs_price-a.pay_shipp_price) as price";
353 $q_margin = ",(sum(a.pay_gs_price-a.pay_shipp_price - (((b.gs_price_factory+b.gs_price_margin)+(b.gs_price_factory+b.gs_price_margin)*$add_mul_factory_price)*a.quantity)) - ifnull(sum(c.point),0) - ifnull(sum(a.opts_price_factory),0))";
354
355 $q_join = ",ifnull(sum(c.point),0) as usePoint
356 from sf_order a
357 left join sf_goods b on a.goods_idx = b.gs_idx
358 left join sf_user_point_stack c on a.order_no = c.order_no";
359 $q_where_date = "SUBSTRING_INDEX(a.orderTime,'-',1)='".$search_year."'
360 and SUBSTRING_INDEX(SUBSTRING_INDEX(a.orderTime, '-', -2), '-', 1)='".$search_month."'";
361 $q_where_common = "and (a.stats='2' or a.stats='3' or a.stats='4')";
362 $q_where_seller = "and a.seller_id<>''
363 and a.seller_id is not null
364 and seller_id='".$seller_id."'";
365
366
367 if($recom) { // 에이전시에 속한 아이디면 마진에서 에이전시 수수료 차감
368 $agency_fee = $this->getAgencyFee($recom);
369 $q_margin .= "- ((sum(a.pay_gs_price-a.pay_shipp_price - (((b.gs_price_factory+b.gs_price_margin)+(b.gs_price_factory+b.gs_price_margin)*$add_mul_factory_price)*a.quantity)) - ifnull(sum(c.point),0) - ifnull(sum(a.opts_price_factory),0))*".$agency_fee.")";
370
371 }
372
373
374 $qry_monthly = "$q_h
375 $q_margin as margin
376 $q_join
377 where $q_where_date $q_where_common $q_where_seller";
378
379
380 $qry_tot = "$q_h
381 $q_margin as margin
382 $q_join
383 where 1=1 $q_where_common $q_where_seller";
384 // echo $qry_tot;
385 $res = $this->fetch1($qry_monthly);
386 $res['tot'] = $this->fetch1($qry_tot);
387
388 if($this->isAgency($seller_id)) { // 에이전시 정산
389 $shop_info = $this->getShopInfo($seller_id);
390 $agency_fee = $this->getAgencyFee($seller_id);
391
392 $q_margin = ",((sum(a.pay_gs_price-a.pay_shipp_price - (((b.gs_price_factory+b.gs_price_margin)+(b.gs_price_factory+b.gs_price_margin)*$add_mul_factory_price)*a.quantity)) - ifnull(sum(c.point),0) - ifnull(sum(a.opts_price_factory),0))*".$agency_fee.")";
393 $q_join .= " left join sf_order_recom r on a.order_no=r.order_no ";
394 $q_where_seller = "and r.recom_id='".$seller_id."'";
395 $q_month_ag = "$q_h
396 $q_margin as margin
397 $q_join where $q_where_date $q_where_common $q_where_seller";
398 $res['ag_month'] = $this->fetch1($q_month_ag);
399
400 $q_tot_ag = "$q_h
401 $q_margin as margin
402 $q_join where 1=1 $q_where_common $q_where_seller";
403
404 $res['ag_tot'] = $this->fetch1($q_tot_ag);
405
406 ### 에이전시 정산에 샘플구매도 추가 - 제품 기본마진에서 * 에이전시 수수료율 한 금액 * 제품수량 ###
407 $q_join .= " left join sf_member m on a.mb_seq=m.mb_seq ";
408 $q_where_seller = "and (m.seller_recom='".$seller_id."' or m.seller_recom2='".$seller_id."') and a.seller_id=''";
409 $q_margin = ",( (b.gs_price - b.gs_price_factory+b.gs_price_margin) * $agency_fee ) * a.quantity";
410 $q_month_ag = "$q_h
411 $q_margin as margin
412 $q_join where $q_where_date $q_where_common $q_where_seller";
413 $tRes = $this->fetch1($q_month_ag);
414 $res['ag_month']['margin'] += $tRes['margin'];
415 }
416 if($mall_margin > 0) {
417 $res['mall_margin'] = $mall_margin;
418 }
419 return $res;
420 }
421
422 function getMallPay($search_year,$search_month,$mall_id) {
423 $mall_fee = $this->getMallFee($mall_id,'2');
424 $res = $this->fetch1("select s.shop_id,sum((g.gs_price_factory+g.gs_price_margin)*$mall_fee)*o.quantity as mall_margin
425 ,sum(o.pay_gs_price-o.pay_shipp_price) as price
426 from sf_order o
427 left join sf_member m on o.seller_id=m.seller_id
428 left join sf_shop s on s.shop_id=m.seller_recom
429 left join sf_goods g on o.goods_idx=g.gs_idx
430 where s.shop_id is not null and s.shop_id<>''
431 and (o.stats='2' or o.stats='3' or o.stats='4') and SUBSTRING_INDEX(o.orderTime,'-',1)='".$search_year."'
432 and SUBSTRING_INDEX(SUBSTRING_INDEX(o.orderTime, '-', -2), '-', 1)='".$search_month."' and s.shop_id='".$mall_id."'
433 group by s.shop_id");
434 return $res;
435 }
436
437 function getShopInfo($shop_id,$shop_type='1') {
438 if($shop_type=='domain') {
439 $q = "select a.*,b.*,a.shop_idx as sidx from sf_shop a
440 left join sf_shop_config b on a.shop_idx=b.shop_idx
441 where a.shop_config_url='".$shop_id."'";
442 $chk = $this->fetch1($q);
443 $chk['shop_idx'] = $chk['sidx'];
444 } else {
445 $chk = $this->fetch1("select * from sf_shop where shop_id='".$shop_id."' and shop_type='".$shop_type."'");
446 }
447 if($chk['shop_idx']) {
448 return $chk;
449 }
450 }
451 function getShopCfg($shop_id,$get_flag='domain') {
452 $get_flag = $get_flag ? $get_flag : 'domain';
453 if($get_flag=='domain') {
454 $chk = $this->fetch1("select a.*,b.* from sf_shop a left join sf_shop_config b on a.shop_idx = b.shop_idx where a.shop_config_url='".$shop_id."' limit 1");
455 }
456 return $chk;
457 }
458 function getDefaultShopInfo () {
459 $chk = $this->fetch1("select a.*,b.* from sf_shop a left join sf_shop_config b on a.shop_idx=b.shop_idx where a.shop_id='starlook'");
460 if($chk[shop_idx]) {
461 return $chk;
462 }
463 }
464 function getSellerInfo($seller_id) {
465 # 셀러정보
466 $agencyCheckQry = sprintf("select * from sf_member where seller_id = '%s'",$seller_id);
467 $agencyCheck = $this->fetch1($agencyCheckQry);
468
469 # 에이전시에 속한 하위 샾인 경우 에이전시샾의 정보를 불러온다?
470 if($agencyCheck['seller_recom']){
471 if($this->isAgency($agencyCheck['seller_recom'])) {
472 $seller_id = $agencyCheck['seller_recom'];
473 }
474 }
475
476 # 밴더셀러 체크
477 $res = $this->fetch1("select a.*,b.*,c.* from sf_member a left join sf_shop b on a.seller_recom = b.shop_id
478 left join sf_shop_config c on b.shop_idx = c.shop_idx where a.seller_id='$seller_id'");
479
480 if($res['mb_seq'])
481 {
482 $accountInfoQry = sprintf("select * from sf_seller_config where mb_seq = '%d'" , $res[mb_seq]);
483 $res2 = $this->fetch1($accountInfoQry);
484
485 if($res2['cfg_idx']) {
486 $res['is_seller_bander'] = '1';
487 }
488 if(trim($res2['footer_cs'])) {
489 $res['footer_cs'] = $res2['footer_cs'];
490 }
491 if(trim($res2['footer_account'])) {
492 $res['footer_account'] = str_replace('|',' ',$res2['footer_account']);
493 }
494 if(trim($res2['footer_email'])) {
495 $res['footer_email'] = $res2['footer_email'];
496 }
497 if(trim($res2['footer_addr'])) {
498 $res['footer_addr'] = $res2['footer_addr'];
499 }
500 if(trim($res2['footer_comnm'])) {
501 $res['footer_comnm'] = $res2['footer_comnm'];
502 }
503 }
504 return $res;
505 }
506 function getFooterInfo($seller_id) {
507
508 //셀러정보
509 $agencyCheckQry = sprintf("select * from sf_member where seller_id = '%s'",$seller_id);
510 $agencyCheck = $this->fetch1($agencyCheckQry);
511
512 // 추천인이 벤더셀러이면 해당 설정을 로드하는듯(푸터용으로)
513 $res = $this->fetch1("select a.*,b.*,c.* from sf_member a left join sf_shop b on a.seller_recom = b.shop_id
514 left join sf_shop_config c on b.shop_idx = c.shop_idx where a.seller_id='$seller_id'");
515
516 // 에이전시 정보 불러오기 전에 개인배너 설정한거 있으면 미리 저장
517 $res['private_shop_banner'] = $agencyCheck['seller_bg'];
518 $res['private_shop_mb_seq'] = $agencyCheck['mb_seq'];
519
520
521 if($res[mb_seq])
522 {
523 $accountInfoQry = sprintf("select * from sf_seller_config where mb_seq = '%d'" , $res[mb_seq]);
524 $res2 = $this->fetch1($accountInfoQry);
525
526 if($res2['cfg_idx']) {
527 $res['is_seller_bander'] = '1';
528 }
529 if(trim($res2['footer_cs'])) {
530 $res['footer_cs'] = $res2['footer_cs'];
531 }
532 if(trim($res2['footer_account'])) {
533 $res['footer_account'] = str_replace('|',' ',$res2['footer_account']);
534 }
535 if(trim($res2['footer_email'])) {
536 $res['footer_email'] = $res2['footer_email'];
537 }
538 if(trim($res2['footer_addr'])) {
539 $res['footer_addr'] = $res2['footer_addr'];
540 }
541 if(trim($res2['footer_comnm'])) {
542 $res['footer_comnm'] = $res2['footer_comnm'];
543 }
544 }
545 return $res;
546 }
547 function getSellerList($agency_id) {
548 global $shop_info;
549 if($shop_info['shop_type']=='2') {
550 $f = 'seller_recom2';
551 } else {
552 $f = 'seller_recom';
553 }
554 return $this->fetchs("select * from sf_member where $f='".$agency_id."'");
555 }
556
557 function setSellerSession() {
558 unset($_SESSION[from_seller_id]);
559 unset($_SESSION[from_seller_gs_seq]);
560 unset($_SESSION[from_seller_gs_idx]);
561 if($_GET[s_id] && $_GET[sp_seq] && $_SERVER[PHP_SELF]=='/goods_detail.php' && $_GET[s_id]!='php' && $_GET[s_id]!='goods') {
562 $_SESSION[from_seller_id] = $_GET[s_id];
563 $_SESSION[from_seller_gs_seq] = $_GET[sp_seq];
564 return $this->setPrivateShop($_GET[s_id]);
565 } else if($_GET[s_id] && $_SERVER[PHP_SELF]=='/goods_list.php') {
566 $_SESSION[from_seller_id] = $_GET[s_id];
567 return $this->setPrivateShop($_GET[s_id]);
568 } else if($_GET[private_unset]=='1') {
569 $_SESSION[private_shop] = '';
570 unset($_SESSION[private_shop]);
571 return true;
572 } else {
573 return true;
574 }
575 }
576
577 function isAgency($id) {
578 $chk = $this->fetch1("select agency from sf_member where seller_id='".$id."'");
579 if($chk['agency']) {
580 return true;
581 }
582 return false;
583 }
584
585 function isBelongAgency($id) {
586 $chk = $this->fetch1("select seller_recom,seller_recom2,seller_type from sf_member where seller_id='".$id."'");
587 if($chk['seller_recom'] || $chk['seller_recom2']) {
588 if($chk['seller_type']=='1') {
589 $recom = $chk['seller_recom'];
590 } else if($chk['seller_type']=='2') {
591 $recom = $chk['seller_recom2']; // 임대몰에 속한 셀러면 recom2 필드가 에이전시 필드임
592 }
593
594 if($this->isAgency($recom)==true) {
595 return $recom;
596 }
597 }
598 return false;
599 }
600
601 function isBelongSaas($id) {
602 $chk = $this->fetch1("select a.shop_idx from sf_shop a left join sf_member b on a.shop_id=b.seller_recom
603 where b.seller_type='2' and b.seller_id='".$id."' limit 1");
604 if($chk['shop_idx']) {
605 return true;
606 }
607 return false;
608 }
609
610 # 샘플구매 권한이 있는지 - 현재는 seller_type = 3이면 판매권한만 있고 샘플구매 권한은 없다
611 function isFactoryBuy($sellr_info = array()) {
612 $user_info = $this->getMyInfo();
613 if($user_info['seller_id'] && $user_info['seller']=='y' && $user_info['seller_type']!=3) {
614 return true;
615 }
616 return false;
617 }
618
619 function calcBox($arrPrices,$ea=1) {
620 // 회사 30 / 셀러 30 / 박스 40
621 if($arrPrices['gs_price'] && $arrPrices['gs_price_factory']) {
622 $margin = $arrPrices['gs_price']-($arrPrices['gs_price_factory']);
623 $res['com_margin'] = round($margin*0.3);
624 $res['seller_margin'] = round($margin*0.3);
625 $res['box'] = floor($margin*0.4/100);
626 return $res;
627 } else {
628 return false;
629 }
630 }
631
632 function updateBoxsFromOrder($seller_id='') {
633 # 저번주 날짜를 구한다
634 $ymd = date("Y-m-d");
635 $time = strtotime($ymd);
636 $today = date("Y-m-d", $time);
637 $tday = date("w", $time);
638 if($tday) $Sun = -2;
639 else $Sun = -1;
640 $last[Sun] = strtotime("{$Sun} Sunday", $time);
641 $last[Sat] = strtotime("previous Saturday", $time);
642 $last[Sun_ymd] = date("Y-m-d", $last[Sun]);
643 $last[Sat_ymd] = date("Y-m-d", $last[Sat]);
644 $st_date = date("Y-m-d", $last['Sun']);
645 $ed_date = date("Y-m-d", $last['Sat']);
646
647 $addCond = '';
648 if($seller_id) {
649 $addCond = " and a.seller_id='".$seller_id."'";
650 }
651 $m_q = "";
652 $q ="select a.idx,a.order_no,a.seller_id,b.bx_idx,a.orderTime
653 from sf_order a
654 left join sf_box_stack b on a.idx=b.order_idx
655 where left(a.orderTime,10) >= '".$st_date."' and left(a.orderTime,10) <= '".$ed_date."'
656 and b.order_idx is null
657 and a.stats in ('2','3','4') and a.order_host='www.by2buy.net'
658 $addCond";
659 //echo $q;
660 //die;
661 $rs = $this->fetchs($q);
662 for ($i=0; $i < count($rs); $i++) {
663 $margin_tmp = $this->getSellerPayFromOrder($rs[$i]['order_no'],$rs[$i]['seller_id']);
664 $com_margin = round($margin_tmp*0.3);
665 $seller_margin = round($margin_tmp*0.3);
666 $box_margin = floor($margin_tmp*0.4/100);
667
668 $m_q .= sprintf("insert into sf_box_stack set
669 order_idx=%d,
670 seller_id='%s',
671 box=%d,
672 margin_com=%d,
673 margin_seller=%d,
674 stack_date='%s';"
675 ,$rs[$i]['idx']
676 ,$rs[$i]['seller_id']
677 ,$box_margin
678 ,$com_margin
679 ,$seller_margin
680 ,$rs[$i]['orderTime']);
681 }
682 if($this->multi_query($m_q)) {
683 return true;
684 }
685
686 return false;
687 }
688
689 function updateBoxsToOpen($seller_id='',$open_seq) {
690 $q ="select a.bx_idx,b.bxop_idx,a.box from sf_box_stack a
691 left join sf_box_open b
692 on a.bx_idx=.b.bx_idx
693 where b.bxop_idx is null $addCond and a.box > 0";
694
695 $addCond = '';
696 if($seller_id) {
697 $addCond = " and a.seller_id='".$seller_id."'";
698 }
699
700 $rs = $this->fetchs($q);
701 for ($i=0; $i < count($rs); $i++) {
702 for ($j=0; $j < $rs[$i]['box']; $j++) {
703 $this->query(sprintf("insert into sf_box_open set
704 bx_idx=%d,
705 open_seq=%d;"
706 ,$rs[$i]['bx_idx']
707 ,$open_seq));
708 }
709 }
710 return false;
711 }
712
713
714 function setPrivateShop($s_id) {
715 # 존재하는 상점인지
716 $chk = $this->fetchOne("select mb_seq,seller_recom,mb_nick from sf_member where seller_id='".$this->escape($s_id)."'");
717 if($chk[mb_seq]) {
718 if($chk['seller_recom']) {
719 $tsp = explode('|',$_ENV['agency']);
720 for ($i=0; $i < count($tsp); $i++) {
721 if($tsp[$i]==$chk['seller_recom']) {
722 $_SESSION['is_agency'] = '1';
723 $_SESSION['agency_id'] = $tsp[$i];
724 break;
725 }
726 }
727 }
728 $_SESSION[private_shop] = $s_id;
729 $_SESSION[private_shop_name] = $chk[mb_nick] ? $chk[mb_nick] : '';
730 return true;
731 } else {
732 $_SESSION[private_shop] = '';
733 unset($_SESSION[private_shop]);
734 return false;
735 }
736 }
737 function getMyInfo($id='') {
738 $id = $id ? $id : $_SESSION[mb_id];
739 $res = $this->fetch1("select a.*,b.* from sf_member a left join sf_seller_config b on a.mb_seq=b.mb_seq where a.mb_email='$id'");
740 return $res;
741 }
742
743 /** Deliver **/
744 function addDeliverInfo($dInfo) {
745 $addrs_inter = '';
746 if($dInfo['addr_inter_st1'] && $dInfo['addr_inter_city']) {
747 $addrs_inter = $dInfo['addr_inter_st1'].'|'.$dInfo['addr_inter_st2'].'|'.$dInfo['addr_inter_city'].'|'.$dInfo['addr_inter_state'].'|'.$dInfo['addr_inter_zipcd'].'|'.$dInfo['addr_inter_country'];
748 } else if($_SESSION['lang']=='cn' && $_SESSION['is_shipp_in_china']==true) { // 중국전용 주소
749 $tmp_ex = explode('|',$dInfo['citycode_china2']);
750 $addr_cn1 = $this->fetchOne("select name_full from sf_shipping_prices_china where id=".$dInfo['citycode_china']);
751 $addr_cn2 = $this->fetchOne("select name_cn from sf_citycode_china where code=".$tmp_ex[1]);
752 $addrs_inter = $addr_cn1['name_full'].'|'.$addr_cn2['name_cn'].'|'.$dInfo['citycode_china3'].'|'.$dInfo['addr_cn'].'|'.$dInfo['zipcode_cn'].'|'.$dInfo['custID_cn'];
753 }
754 if($this->chkDeliverInfo()==true) {
755 $q = "update sf_deliverInfo set modTime='".date("Y-m-d G:i:s")."'";
756 $qf = " where mb_type='".$_SESSION[mb_type]."' and mb_email='".$_SESSION[mb_id]."'";
757 } else {
758 $q = "insert into sf_deliverInfo set mb_type='".$_SESSION[mb_type]."',mb_email='".$_SESSION[mb_id]."'";
759 }
760 if($addrs_inter) {
761 $q.=",name_1='".$dInfo[buyer_name]."',phone_1='".$dInfo[buyer_phone]."',addr_1='".$addrs_inter."',email_1='".$dInfo[buyer_email]."'".$qf;
762 } else {
763 $q.=",name_1='".$dInfo[buyer_name]."',phone_1='".$dInfo[buyer_phone]."',addr_1='".$dInfo[buyer_addr]."',addr_2='".$dInfo[buyer_addr2]."',email_1='".$dInfo[buyer_email]."',zipcode='".$dInfo[buyer_zipcode]."'".$qf;
764 }
765 if($this->query($q)) {
766 return true;
767 } else {
768 Log::write('Err','addDeliverInfo false - '.$q);
769 return false;
770 }
771 }
772 function chkDeliverInfo() {
773 $res = $this->fetchOne("select idx from sf_deliverInfo where mb_type='".$_SESSION[mb_type]."' and mb_email='".$_SESSION[mb_id]."' limit 1");
774 if($res[idx]) { return true;} else { return false;}
775 }
776
777 function getDeliveryInfo() {
778 $res = $this->fetchOne("select * from sf_deliverInfo where mb_type='".$_SESSION[mb_type]."' and mb_email='".$_SESSION[mb_id]."' limit 1");
779 if($res[idx]) { return $res;} else { return false;}
780 }
781 function getAddrStrFromInter($addrStr) {
782 $addr_inter_arr = explode('|',$addrStr);
783 $addrStr = "Street address : ".$addr_inter_arr[1].' '.$addr_inter_arr[0]."<Br>";
784 $addrStr .= "City : ".$addr_inter_arr[2]."<Br>";
785 $addrStr .= "State : ".$addr_inter_arr[3]."<Br>";
786 $addrStr .= "Zip Code : ".$addr_inter_arr[4]."<Br>";
787 $addrStr .= "Country : ".$addr_inter_arr[5]."<Br>";
788 return $addrStr;
789 }
790 function getCreditInfo() {
791 if($_SERVER['HTTP_HOST']!='cn.socialmarket.kr') {
792 if(isSession()) {
793 $t_res = $this->fetchOne("select * from sf_creditcard_info where mb_seq=".$_SESSION['mb_seq']);
794
795 if($t_res['mb_seq']) {
796 $res['c_no'] = aes_decrypt($t_res['card_no'],$t_res['hash_key']);
797 $res['yymm'] = aes_decrypt($t_res['yymm'],$t_res['hash_key']);
798 $res['billkey'] = aes_decrypt($t_res['billkey'],$t_res['hash_key']);
799 return $res;
800 } else { return false;}
801 } else { return false;}
802 } else {
803 return false;
804 }
805 }
806 function setCreditInfo($c_no,$yymm,$billkey='') {
807 if($billkey) {
808 if(isSession()) {
809 $t_res = $this->fetchOne("select mb_seq from sf_creditcard_info where mb_seq=".$_SESSION['mb_seq']);
810 $hash_key = makeRandStr('4');
811 if($t_res['mb_seq']) {
812 $q = sprintf("update sf_creditcard_info set card_no='%s',yymm='%s',billkey='%s',hash_key='%s' where mb_seq=".$_SESSION['mb_seq']
813 ,aes_encrypt($c_no,$hash_key)
814 ,aes_encrypt($yymm,$hash_key)
815 ,aes_encrypt($billkey,$hash_key)
816 ,$hash_key);
817 } else {
818 $q = sprintf("insert into sf_creditcard_info set card_no='%s',yymm='%s',billkey='%s',hash_key='%s',mb_seq=".$_SESSION['mb_seq']
819 ,aes_encrypt($c_no,$hash_key)
820 ,aes_encrypt($yymm,$hash_key)
821 ,aes_encrypt($billkey,$hash_key)
822 ,$hash_key);
823 }
824 if($this->query($q)) {
825 return true;
826 } else {
827 Log::write('cardSaveErr','카드정보 저장 실패 - '.$q);
828 return false;
829 }
830 } else { return false;}
831 } else {
832 if(isSession() && $c_no && $yymm) {
833 $t_res = $this->fetchOne("select mb_seq from sf_creditcard_info where mb_seq=".$_SESSION['mb_seq']);
834 $hash_key = makeRandStr('4');
835 if($t_res['mb_seq']) {
836 $q = sprintf("update sf_creditcard_info set card_no='%s',yymm='%s',hash_key='%s' where mb_seq=".$_SESSION['mb_seq']
837 ,aes_encrypt($c_no,$hash_key)
838 ,aes_encrypt($yymm,$hash_key)
839 ,$hash_key);
840 } else {
841 $q = sprintf("insert into sf_creditcard_info set card_no='%s',yymm='%s',hash_key='%s',mb_seq=".$_SESSION['mb_seq']
842 ,aes_encrypt($c_no,$hash_key)
843 ,aes_encrypt($yymm,$hash_key)
844 ,$hash_key);
845 }
846 if($this->query($q)) {
847 return true;
848 } else {
849 Log::write('cardSaveErr','카드정보 저장 실패 - '.$q);
850 return false;
851 }
852 } else { return false;}
853 }
854 }
855 function isCart($arrData) {
856 $chk = $this->fetchOne("select idx from sf_cart where mb_type='".$_SESSION['mb_type']."'
857 and mb_seq=".$arrData['mb_seq']."
858 and goods_idx='".$arrData['gs_idx']."'
859 and opts='".@implode("|",$arrData['opts'])."'");
860 if($chk[idx]) {
861 return true;
862 }
863 return false;
864 }
865 function emptyCart($mb_seq) {
866 if($mb_seq) {
867 $chk = $this->query("delete from sf_cart where mb_seq=$mb_seq");
868 }
869 }
870
871 function getShippPrice($pid,$price,$arrOrderData=array()) {
872 $this->objSF = new SF;
873 $gdata = $this->objSF->getGoodsInfo($pid);
874 $deliver_price = 0;
875
876 # 해외배송지 배송비 가져오기
877 if($arrOrderData['nation']!='kr' && $gdata['gs_nation']!='kr' && $arrOrderData['nation']) {
878 $chk_area_f = 'area';
879 if(!$gdata['gs_weight']) $gdata['gs_weight'] = 1000; // 무게값이 없을때 기본 1키로로 잡는다
880 $gdata['gs_weight'] = $gdata['gs_weight']*$arrOrderData['quantity']; // 무게에 수량을 곱해준다
881 // if($gdata['gs_weight'] > 3000) { // 3키로 넘을때 예외처리 (현재는 일단 3키로 넘을때 3키로로 해준다)
882 // $gdata['gs_weight'] = 3000;
883 // }
884 # 만약에 배송표에 없는 무게면 가장 가까운 무게로 가져온다
885 $tmp_chk = $this->fetchOne("select grams from sf_shipp_prices where grams >= ".$gdata['gs_weight']." order by grams limit 1");
886 if(!$tmp_chk['grams']) {
887 # 표에 없으면 최고 무게 값으로
888 $tmp_chk = $this->fetchOne("select grams from sf_shipp_prices order by grams desc limit 1");
889 }
890 $gdata['gs_weight'] = $tmp_chk['grams'];
891
892 if($gdata['gs_weight'] > 2000) { // 2키로 넘을때부터는 ems 기준으로 불러온다
893 $chk_area_f = 'area_ems';
894 }
895 //if($_SERVER['REMOTE_ADDR']=='61.74.181.49') {
896 //echo "select ".$arrOrderData['nation']." as shipp from sf_shipp_prices where grams=".$gdata['gs_weight'];
897 //}
898
899 # 1~4지역인지 체크
900 $res = $this->fetchOne("select area,area_ems from nations where nation_cd='".$arrOrderData['nation']."'");
901 if($res[$chk_area_f] && $res[$chk_area_f] > 0) {
902 $res = $this->fetchOne("select AR".trim($res[$chk_area_f])." as shipp from sf_shipp_prices where grams=".$gdata['gs_weight']);
903
904 } else {
905 # 배송비 가격 테이블에 존재하는 필드(나라)인지 먼저 체크해야한다 - 없는 나라는 배송불가지역?
906 $chkF = $this->fetchOne("show columns from sf_shipp_prices like '".$arrOrderData['nation']."'");
907 if($chkF['Field']) {
908 $res = $this->fetchOne("select ".$arrOrderData['nation']." as shipp from sf_shipp_prices where grams=".$gdata['gs_weight']);
909 } else {
910 // 배송불가지역 예외처리
911 return "0";
912 }
913 }
914
915 if($res['shipp'] > 0) {
916 if($price >= $gdata[gs_deliver_free_price]) {
917 $deliver_price = $gdata[gs_deliver_free]=="1" ? "0" : $res['shipp'];
918 } else {
919 $deliver_price = $res['shipp'];
920 }
921 } else {
922 return 15000; // 배송비가 없을시 평균 배송비로 잡는다
923 }
924 } else {
925 if($gdata['gs_idx']) {
926 if($price >= $gdata[gs_deliver_free_price]) {
927 $deliver_price = $gdata[gs_deliver_free]=="1" ? "0" : $gdata[gs_price_shipp];
928 } else {
929 $deliver_price = $gdata[gs_price_shipp];
930 }
931 }
932 }
933 return $deliver_price;
934 }
935 ## 원퉁물류 (중국내 물류공장 배송)API 전용 배송비 계산함수 - return : 중국 인민화
936 function getShippPriceCN($gs_weight,$city_idx) {
937 $shipp_price_info = $this->fetchOne("select default_price,add_price from sf_shipping_prices_china where id=".$city_idx);
938 if($shipp_price_info['default_price'] > 0 ) {
939 if($gs_weight < 1) {
940 return $shipp_price_info['default_price'];
941 } else {
942 return $shipp_price_info['default_price'] + (ceil(($gs_weight+0.1)/1)-1)*$shipp_price_info['add_price']; // 추가배송비 공식. 0.9 까지는 기본, 1이상 2미만 추가금, 2이상 3미만 추가금...
943 }
944 }
945 return false;
946 }
947
948 function getAllShippPrice($pid,$price,$isAdditionAddr = false) {
949 $this->objSF = new SF;
950 $gdata = $this->objSF->getGoodsInfo($pid);
951 $deliver_price = 0;
952 $gs_deliver_price = $gdata[gs_price_shipp] == '0' ? '2500' : $gdata[gs_price_shipp];
953 if($gdata[gs_idx]) {
954 if($price >= $gdata[gs_deliver_free_price]) {
955 $deliver_price = $gdata[gs_deliver_free]=="1" ? "0" : $gs_deliver_price;
956 } else {
957 $deliver_price = $gs_deliver_price;
958 }
959
960 if($isAdditionAddr)
961 $deliver_price = $deliver_price + $gdata[gs_price_shipp_addition];
962 }
963 return $deliver_price;
964 }
965
966 function getAdditionShippPrice($pid, $isAdditionAddr) {
967 $this->objSF = new SF;
968 $gdata = $this->objSF->getGoodsInfo($pid);
969 $deliver_price = 0;
970 if($gdata[gs_idx] && $isAdditionAddr == 1) {
971
972 return $gdata[gs_price_shipp_addition];
973 }
974 return $deliver_price;
975 }
976
977
978 function isFreeShipp($gs_idx,$price,$flag='1') {
979 if($flag=='1') {
980 $rs = $this->fetchOne("select gs_deliver_free,gs_deliver_free_price from sf_goods where gs_idx=$gs_idx");
981 } else if($flag=='b') { // 장바구니에서 같은 브랜드별 배송료 무료조건 체크 - 배송료 무료 조건이 걸린 제품들중에서만 찾는다
982 $rs = $this->fetchOne("select gs_deliver_free,gs_deliver_free_price,gs_price_shipp_addition from sf_goods where gs_brand='".$this->escape($gs_idx)."' and gs_deliver_free=1 and gs_deliver_free_price > 0 order by gs_idx desc limit 1");
983 // debug($rs);
984 }
985
986 // 추가배송비가 0원일 경우만 무료 배송 조건에 해당됨(2017.5.10) - 도서산간 추가 배송비가 있더라도 무료 배송 조건에 충족하면 무료배송으로 변경함 byhun - 180603
987 //if($rs[gs_deliver_free] == '1' && $price>=$rs[gs_deliver_free_price] && $rs[gs_price_shipp_addition] == 0) {
988 if($rs[gs_deliver_free] == '1' && $price>=$rs[gs_deliver_free_price]) {
989 return true;
990 }
991 return false;
992 }
993 function getShippByGoods($gs_idx) {
994 $res = $this->fetchOne("select gs_price_shipp from sf_goods where gs_idx=$gs_idx");
995 if($res[gs_price_shipp]>0) { return $res[gs_price_shipp];} else {return 2500;}
996 }
997 function getAdditionShippByGoods($gs_idx) {
998 $res = $this->fetchOne("select gs_price_shipp_addition from sf_goods where gs_idx=$gs_idx");
999 if($res[gs_price_shipp_addition]>0) { return $res[gs_price_shipp_addition];} else {return 0;}
1000 }
1001
1002 function getCartAdditionShippTot($mb_seq, $isAdditionAddr=false) {
1003 if(!$mb_seq && !is_numeric($mb_seq)) return false;
1004
1005 $shippTot = 0;
1006 $shippArray = array();
1007 $this->isGroupShipping = false;
1008
1009 $gsGrLst = $this->fetchs("select a.goods_idx,sum(a.sale_price) as priceTot from sf_cart a left join sf_goods b
1010 on a.goods_idx=b.gs_idx where a.mb_seq=".$mb_seq." group by a.goods_idx");
1011 for ($i=0; $i < count($gsGrLst); $i++) {
1012 $shippArray[$gsGrLst[$i][goods_idx]] = 0;
1013
1014 if($isAdditionAddr)
1015 $shippArray[$gsGrLst[$i][goods_idx]] += $this->getAdditionShippByGoods($gsGrLst[$i][goods_idx]);
1016 }
1017
1018 # 2 같은 배송료를 가진 것들끼리 묶어 카운팅 한 후
1019 $grCnts = array_count_values($shippArray); // Count same value in array return array
1020 foreach($grCnts as $k => $v) {
1021 $gs_idxs = array_keys($shippArray, $k); // 같은 배송료를 가진 제품들에서 query에 대입시킬 키(gs_idx)만 추출
1022 if($k > 0) { // 배송료가 존재할때
1023 # 2 - 0 배송료가 존재하는 제품들중에서 그룹핑 되는 브랜드가 하나라도 존재시 플래그 추가
1024 $gr_brs = $this->fetchOne("select count(gs_idx) as cnt,gs_brand from sf_goods where gs_idx in(".implode(',',$gs_idxs).") group by gs_brand order by cnt desc limit 1");
1025 if($gr_brs['cnt'] > 1) {
1026 $this->isGroupShipping = true;
1027 }
1028 # 2 - 1 묶음배송 번호를 key로 , 브랜드를 value로 갖는 어레이를 생성
1029 $gr_idxs = $this->fetchs("select gs_shipp_group,gs_brand from sf_goods where gs_idx in(".implode(',',$gs_idxs).")");
1030 $arr_group_shipps = array();
1031 for($j=0;$j<count($gr_idxs);$j++) {
1032 $arr_group_shipps[$gr_idxs[$j]['gs_shipp_group']][$gr_idxs[$j]['gs_brand']] = '1';
1033 }
1034 # 2 - 2 묶음 배송으로 묶여 있는 제품군끼리 서로 같은 브랜드가 있는지 체크하여 최종 묶음 배송비를 계산한다
1035 $addCnt = count($arr_group_shipps);
1036 $chkArr = array();
1037 $tmpSeq = 0;
1038 foreach($arr_group_shipps as $kk => $vv) {
1039 if(count($vv)>1) { // 묶음번호로 묶여있는 제품내에서 같은 브랜드가 1개 이상이면 묶음배송여부 플래그값
1040 $this->isGroupShipping = true;
1041 }
1042 $minFlag = false;
1043 # 브랜드들만 루프돌리면서 같은 브랜드가 있는지 체크
1044 foreach($vv as $key => $val) {
1045 if(!isset($chkArr[$key])) { // 어레이에 처음 들어가는 브랜드
1046 $chkArr[$key] = '1';
1047 } else { // 존재하는 브랜드 어레이(즉 묶음이 존재)
1048 if($tmpSeq>0 && $minFlag==false) {
1049 $this->isGroupShipping = true; // 같은 브랜드로 그룹핑 되는 묶음배송이 있어도 플래그값 설정
1050 $addCnt--;
1051 $minFlag = true;
1052 break;
1053 }
1054 }
1055 }
1056 $tmpSeq++;
1057 }
1058 $shippTot += $addCnt*$k;
1059 }
1060 }
1061 return $shippTot;
1062 }
1063
1064 function getCartShippTot($mb_seq,$isAdditionAddr=false,$arrEtcData = array()) {
1065 if(!$mb_seq && !is_numeric($mb_seq)) return false;
1066 $shippTot = 0;
1067 if($arrEtcData['nation']!='KR' && $arrEtcData['nation']) {
1068 $cart_list = $this->fetchs('select goods_idx,quantity,mb_seq,sale_price from sf_cart where mb_seq='.$mb_seq);
1069 for($i=0;$i<count($cart_list);$i++) {
1070 $arrEtcData['quantity'] = $cart_list[$i]['quantity'];
1071 $shippTot += $this->getShippPrice($cart_list[$i]['goods_idx'], $cart_list[$i]['sale_price'],$arrEtcData);
1072 }
1073 } else {
1074 $shippArray = array();
1075 $this->isGroupShipping = false;
1076 # 1 브랜드별 장바구니에 담긴 합산금액 도출하여 해당 합산금액이 무료배송조건에 충족될 시 묶음배송 조회에서 해당 브랜드를 제외시킨다 (같은 제품별로 묶을 필요는 없는것이 어차피 같은 제품은 같은 브랜드)
1077 $gsBRLst = $this->fetchs("select b.gs_brand,sum(a.sale_price) as priceTot from sf_cart a left join sf_goods b
1078 on a.goods_idx = b.gs_idx where b.gs_remain > 0 and b.gs_stats = '1' and a.mb_seq=".$mb_seq." group by b.gs_brand");
1079
1080 $excep_brs = array();
1081 for ($i=0; $i < count($gsBRLst); $i++) {
1082 if($this->isFreeShipp($gsBRLst[$i]['gs_brand'],$gsBRLst[$i]['priceTot'],'b')) {
1083 array_push($excep_brs, $gsBRLst[$i]['gs_brand']);
1084 $this->isGroupShipping = true;
1085 }
1086 }
1087 $gsGrLst = $this->fetchs("select a.goods_idx,sum(a.sale_price) as priceTot from sf_cart a left join sf_goods b
1088 on a.goods_idx=b.gs_idx where b.gs_remain > 0 and b.gs_stats = '1' and b.gs_brand not in('".implode("','", $excep_brs)."') and a.mb_seq=".$mb_seq." group by a.goods_idx");
1089
1090 for ($i=0; $i < count($gsGrLst); $i++) {
1091 # 1 - 1 해당 제품의 합산이 무료배송을 만족하면 - 필요없는것이 이미 위에서 같은 브랜드(=같은제품도 포함)끼리 무배 조건이 되는 제품을 제외시켯기 때문에..하지만 일단 놔둠
1092 if($this->isFreeShipp($gsGrLst[$i][goods_idx],$gsGrLst[$i][priceTot])) {
1093 $shippArray[$gsGrLst[$i][goods_idx]] = 0;
1094 $this->isGroupShipping = true;
1095 } else {
1096 # 1 -2 해당 제품의 합산이 무배를 충족하지 못하면 (배송료가 존재할시 배송료 배열에 추가)
1097 $shippArray[$gsGrLst[$i][goods_idx]] = $this->getShippByGoods($gsGrLst[$i][goods_idx]);
1098 }
1099
1100 # 1 -3제주지역은 무료배송과 관계 없이 무조건 추가
1101 if($isAdditionAddr)
1102 $shippArray[$gsGrLst[$i][goods_idx]] += $this->getAdditionShippByGoods($gsGrLst[$i][goods_idx]);
1103 }
1104 # 2 같은 배송료를 가진 것들끼리 묶어 카운팅 한 후
1105 $grCnts = array_count_values($shippArray); // Count same value in array return array
1106 foreach($grCnts as $k => $v) {
1107 $gs_idxs = array_keys($shippArray, $k); // 같은 배송료를 가진 제품들에서 query에 대입시킬 키(gs_idx)만 추출
1108 if($k > 0) { // 배송료가 존재할때
1109 # 2 - 0 배송료가 존재하는 제품들중에서 그룹핑 되는 브랜드가 하나라도 존재시 플래그 추가
1110 $gr_brs = $this->fetchOne("select count(gs_idx) as cnt,gs_brand from sf_goods where gs_idx in(".implode(',',$gs_idxs).") group by gs_brand order by cnt desc limit 1");
1111 if($gr_brs['cnt'] > 1) {
1112 $this->isGroupShipping = true;
1113 }
1114 # 2 - 1 묶음배송 번호를 key로 , 브랜드를 value로 갖는 어레이를 생성
1115 $gr_idxs = $this->fetchs("select gs_shipp_group,gs_brand from sf_goods where gs_idx in(".implode(',',$gs_idxs).")");
1116 $arr_group_shipps = array();
1117 for($j=0;$j<count($gr_idxs);$j++) {
1118 $arr_group_shipps[$gr_idxs[$j]['gs_shipp_group']][$gr_idxs[$j]['gs_brand']] = '1';
1119 }
1120 # 2 - 2 묶음 배송으로 묶여 있는 제품군끼리 서로 같은 브랜드가 있는지 체크하여 최종 묶음 배송비를 계산한다
1121 $addCnt = count($arr_group_shipps);
1122 $chkArr = array();
1123 $tmpSeq = 0;
1124 foreach($arr_group_shipps as $kk => $vv) {
1125 if(count($vv)>1) { // 묶음번호로 묶여있는 제품내에서 같은 브랜드가 1개 이상이면 묶음배송여부 플래그값
1126 $this->isGroupShipping = true;
1127 }
1128 $minFlag = false;
1129 # 브랜드들만 루프돌리면서 같은 브랜드가 있는지 체크
1130 if($_SERVER['REMOTE_ADDR']=='211.201.226.186') {
1131 //debug($vv);
1132 }
1133 foreach($vv as $key => $val) {
1134 if(!isset($chkArr[$key])) { // 어레이에 처음 들어가는 브랜드
1135 $chkArr[$key] = '1';
1136 } else { // 존재하는 브랜드 어레이(즉 묶음이 존재)
1137 if($tmpSeq>0 && $minFlag==false) {
1138 $this->isGroupShipping = true; // 같은 브랜드로 그룹핑 되는 묶음배송이 있어도 플래그값 설정
1139 $addCnt--;
1140 $minFlag = true;
1141 break;
1142 }
1143 }
1144 }
1145 $tmpSeq++;
1146 }
1147 $shippTot += $addCnt*$k;
1148 }
1149 }
1150 }
1151
1152
1153 return $shippTot;
1154 }
1155
1156 function addCart($arrData) {
1157 $shipp = $this->getShippPrice($arrData[gs_idx],$arrData[sale_price]);
1158 $seller_id = "";
1159 //if($_SESSION['from_seller_id'])
1160 //$seller_id = $_SESSION['from_seller_id'];
1161 if($_SESSION['private_shop'])
1162 $seller_id = $_SESSION['private_shop']; //셀러지정 상품이 아닌 카테고리를 통해 구매하는 상품
1163 if(!$shipp) $shipp = "0";
1164 // $arrData['sale_price'] += $shipp;
1165 $q = "insert into sf_cart set
1166 mb_type='".$_SESSION['mb_type']."',
1167 mb_seq=".$_SESSION['mb_seq'].",
1168 seller_id='".$seller_id."',
1169 goods_idx='".$arrData['gs_idx']."',
1170 opts_values='".$arrData['opts_values']."',
1171 quantity='".$arrData['tot_qty']."',
1172 opts_ea='".$arrData['opts_qt']."',
1173 opts_dp='".$arrData['opts_dp']."',
1174 sale_price=".$arrData['sale_price'].",
1175 shipp_price=".$shipp;
1176 if($this->query($q)) {
1177 return true;
1178 } else {
1179 Log::write('SQLErr','Order Insert False - '.$q);
1180 return false;
1181 }
1182 }
1183
1184 function removeCart($cidx){
1185 if(!isSession()) return false;
1186 $chk = $this->fetchOne("select idx from sf_cart where mb_type='".$_SESSION['mb_type']."'
1187 and mb_seq=".$_SESSION['mb_seq']);
1188
1189 if($chk[idx]){
1190 $q = "delete from sf_cart where idx=".$cidx;
1191 if($this->query($q)){
1192 return true;
1193 }
1194 }
1195 return false;
1196 }
1197
1198 function removeOrder(){
1199 if($this->orderNo) {
1200 $q = "delete from sf_order where order_no='".$this->orderNo."'";
1201 //die($q);
1202 if($this->query($q)){
1203 return true;
1204 }
1205 }
1206 return false;
1207 }
1208
1209 /** 주문 페이지에 출력되는 계좌번호를 설정 (isBanderAccountSend 변수 설정) **/
1210 function chkIsBanderAccountSend($order_type, $gs_idx){
1211 $this->objSF = new SF;
1212 ## 바로주문
1213 if($order_type=='d') {
1214 $this->isBanderAccountSend = false;
1215 if($_SESSION[private_shop] || $_SESSION[agency_id]){
1216 $shop_id = $_SESSION[agency_id] ? $_SESSION[agency_id] : $_SESSION[private_shop];
1217 $shopInfo = $this->getShopInfo($shop_id);
1218 $goodsInfo = $this->objSF->getGoodsInfo($gs_idx);
1219 if($goodsInfo[shop_idx] == $shopInfo[shop_idx]){
1220 $this->isBanderAccountSend = true;
1221 }
1222 return $goodsInfo[shop_idx]. "/".$shopInfo[shop_idx];
1223
1224 }
1225 }
1226 else{
1227 $list_cart = $this->getOrderPossibleCartList($_SESSION[mb_seq]);
1228 $this->isBanderAccountSend = true;
1229 for($i=0;$i<count($list_cart);$i++) {
1230 if($_SESSION[private_shop] || $_SESSION[agency_id]){
1231 $shop_id = $_SESSION[agency_id] ? $_SESSION[agency_id] : $_SESSION[private_shop];
1232 $shopInfo = $this->getShopInfo($shop_id);
1233 $goodsInfo = $this->objSF->getGoodsInfo($list_cart[$i]['gs_idx']);
1234 if($goodsInfo[shop_idx] != $shopInfo[shop_idx]){
1235 $this->isBanderAccountSend = false;
1236 }
1237 }
1238 }
1239 }
1240 }
1241
1242 /** 주문 입력 **/
1243 function addOrder($arrData,$isPayment=false) {
1244 global $shop_info;
1245 $order_result = array();
1246 $addF = "";
1247 $addF_noChg = ""; // 장바구니 주문, 바로주문에 상관없이 고정으로 들어가는 query
1248 $point_use_flag = false;
1249 $zero_payment_flag = false;
1250 $use_point = 0;
1251 $isAdditionAddr = false;
1252 $this->objSF = new SF;
1253 # 주문유형이 페이팔이면서 페이팔 결제 완료 아이디가 있는경우 일단 결제 완료로 간주
1254 if($arrData['payment_type']=='pp' && $arrData['paypal_payment_id']) {
1255 $isPayment = true;
1256 $addF_noChg .= "paypal_payment_id='".$arrData['paypal_payment_id']."',";
1257 }
1258 $stats = $isPayment==true ? '2' : '1'; // 결제상태
1259 # 주문 유효성 체크 - 결제가 완료된 주문이면 패스한다
1260 if($isPayment==false) {
1261 if(!isSession() && $arrData[just_order]!='1') { // 비회원인데 바로주문 플래그가 없으면 안됨
1262 $order_result[result] = 'false';
1263 return $order_result;
1264 }
1265 }
1266
1267 # 배송정보
1268 if(isSession() && $arrData['just_order']!='1') {
1269 $this->addDeliverInfo($arrData);
1270 $addr = $this->getDeliveryInfo();
1271 } else {
1272 $addr['name_1'] = $arrData['buyer_name'];
1273 $addr['phone_1'] = $arrData['buyer_phone'];
1274 if($_SESSION['lang']!='kr') {
1275 $addr['addr_1'] = $arrData['addr_inter_st1'].'|'.$arrData['addr_inter_st2'].'|'.$arrData['addr_inter_city'].'|'.$arrData['addr_inter_state'].'|'.$arrData['addr_inter_zipcd'].'|'.$arrData['addr_inter_country'];
1276 $addr['addr_2'] = '';
1277 } else if($_SESSION['lang']=='cn' && $_SESSION['is_shipp_in_china']==true) {
1278 $tmp_ex = explode('|',$arrData['citycode_china2']);
1279 $addr_cn1 = $this->fetchOne("select name_full from sf_shipping_prices_china where id=".$arrData['citycode_china']);
1280 $addr_cn2 = $this->fetchOne("select name_cn from sf_citycode_china where code=".$tmp_ex[1]);
1281 $addr['addr_1'] = $addr_cn1['name_full'].'|'.$addr_cn2['name_cn'].'|'.$arrData['citycode_china3'].'|'.$arrData['addr_cn'].'|'.$arrData['zipcode_cn'].'|'.$arrData['custID_cn'];
1282 $addr['addr_2'] = '';
1283 } else {
1284 $addr['addr_1'] = $arrData['buyer_addr'];
1285 $addr['addr_2'] = $arrData['buyer_addr2'];
1286 $addr['zipcode'] = $arrData['buyer_zipcode'];
1287 }
1288 }
1289 # 추가 배송비 여부
1290 if(strstr($addr['addr_1'], '제주')) {
1291 $isAdditionAddr = true;
1292 }
1293 # 포인트
1294 if($arrData[use_point] && $_SESSION['mb_seq']) { // 이젠 셀러도 포인트 사용이 가능하다
1295 if(isSellerSession()) {
1296 $objTagby = new Tagby;
1297 $result_point = $objTagby->getPoint($_SESSION['mb_id']);
1298 if($result_point) {
1299 $arr_point = json_decode($result_point, true);
1300 $user_point = ($arr_point['code'] == '1') ? $arr_point['point'] : 0;
1301 }
1302 } else {
1303 $user_point = $this->getPoint($_SESSION[mb_seq],$arrData['from_seller_id']); # 여기서 셀러랑 일반구매자랑 분기
1304 }
1305 if($arrData[use_point] <= $user_point) {
1306 $point_use_flag = true;
1307 $use_point = $arrData[use_point];
1308 }
1309 }
1310
1311 $order_nos = array();
1312 $mb_seq = $arrData[just_order] ? "0" : $_SESSION['mb_seq'];
1313
1314 ## 바로주문
1315 if($arrData[order_type]=='d') {
1316 if($arrData['amount_shipp'] > 0) {
1317 $shipp = $arrData['amount_shipp'];
1318 } else {
1319 $shipp = $this->getAllShippPrice($arrData[gs_idx],$arrData[sale_price],$isAdditionAddr);
1320 }
1321
1322 $arrData['sale_price'] += $shipp;
1323 # 0 원결제인지 체크 - 현재는 포인트 사용시만 체크한다
1324 //if($point_use_flag == true && $arrData[sale_price]-$use_point==0) {
1325 if($arrData[sale_price]-$use_point==0) {
1326 $zero_payment_flag = true;
1327 }
1328 # 결제비번 체크 - 결제완료시는 패스
1329 if($isPayment==false) {
1330 if($arrData[payment_type]=='cd' && isSession() && $zero_payment_flag == false && $shop_info['shop_config_pg_com']=='2') { // 0원 결제가 아니거나 이니시스 비인증인 경우만 비번 체크
1331 $chk = $this->fetchOne("select mb_seq from sf_member where mb_payment_pwd=password('".$arrData[order_payment_pwd]."') and mb_email='".$_SESSION[mb_id]."' and mb_payment_pwd is not null and mb_payment_pwd<>''");
1332 if(!$chk[mb_seq]) {
1333 $order_result[result] = 'false';
1334 $order_result[resultMsg] = '결제 비밀번호가 맞지 않습니다';
1335 return $order_result;
1336 }
1337 }
1338 }
1339
1340
1341 # 주문정보
1342 $this->setOrderNo();
1343 $order_no = $arrData[order_no] ? $arrData[order_no] : $this->orderNo;
1344 //$shipp = $this->getShippPrice($arrData[gs_idx],$arrData[sale_price]);
1345 $_SESSION[last_order_no] = $order_no;
1346
1347 # 주문번호 유효성
1348 $chk_order = $this->getOrderInfo('1',$order_no);
1349 if($chk_order['idx'] && $arrData['payment_type'] != 'cc') {
1350 $order_result['result'] = '1';
1351 $order_result['resultMsg'] = '주문중 일시적인 오류가 발생했습니다';
1352 Log::write("cardorder","사용자가 카드결제 두번누름 발생");
1353 return $order_result;
1354 }
1355
1356 #주문상품이 현재 접속한 shop의 밴더셀러 등록한 제품인지 확인
1357 #밴더셀러 등록한 제품이 맞으면 무통장입금 신청 시 밴더셀러의 계좌가 발송된다.
1358 #(단 밴더셀러의 계좌가 등록되어 있어야 한다.)
1359 $this->isBanderAccountSend = false;
1360 if($_SESSION[private_shop] || $_SESSION[agency_id]){
1361 $shop_id = $_SESSION[agency_id] ? $_SESSION[agency_id] : $_SESSION[private_shop];
1362 $shopInfo = $this->getShopInfo($shop_id);
1363 $goodsInfo = $this->objSF->getGoodsInfo($arrData['gs_idx']);
1364 if($goodsInfo[shop_idx] == $shopInfo[shop_idx]){
1365 $this->isBanderAccountSend = true;
1366 }
1367 }
1368
1369 # 수량
1370 $qty = $arrData[tot_qty];
1371 if($point_use_flag==true) {
1372 $addF .= "pay_point=".$arrData[use_point].",";
1373 }
1374 if(!isSellerSession()) { // 샘플 구매 아닌경우만 셀러 아이디 입력
1375 if(!$arrData['from_seller_id']) $arrData['from_seller_id'] = $_SESSION['private_shop']; //샵을통해 카테고리 진입 시 from_seller_id가 없어 private_shop으로 대처
1376 $addF .= "seller_id='".$arrData['from_seller_id']."',";
1377 }
1378 # 옵션 추가금액에 대한 공급가 계산
1379 $optFactoryPrice = $this->calcOptFactoryPrice($arrData['gs_idx'],$arrData['opts_dp']);
1380 if($optFactoryPrice > 0 && is_numeric($optFactoryPrice)) {
1381 $addF .= "opts_price_factory=".$optFactoryPrice.",";
1382 }
1383 # 텐핑 세션이 있고 텐핑샵이면
1384 if($_SESSION['tenping_jid'] && $_SESSION['tenping_uid'] && $_SESSION['tenping_at'] && $_SESSION['priavet_shop']=='tenping') {
1385
1386 }
1387
1388 $q = "insert into sf_order set
1389 stats='".$stats."',
1390 pay_gs_price='".$arrData['sale_price']."',
1391 pay_shipp_price='".$shipp."',
1392 mb_type='".$_SESSION['mb_type']."',
1393 mb_seq=".$mb_seq.",
1394 $addF
1395 $addF_noChg
1396 pay_method='".$arrData['payment_type']."',
1397 goods_idx='".$arrData['gs_idx']."',
1398 order_no='".$order_no ."',
1399 opts_values='".$this->escape($arrData['opts_values'])."',
1400 opts_ea='".$arrData['opts_qt']."',
1401 opts_dp='".$this->escape($arrData['opts_dp'])."',
1402 quantity=".$qty.",
1403 account_name='".$arrData['buyer_ac_name']."',
1404 deliver_msg='".$arrData['deliver_msg']."',
1405 receiver_zipcode='".$addr['zipcode']."',
1406 receiver_name='".$addr['name_1']."',
1407 receiver_phone='".$addr['phone_1']."',
1408 receiver_addr='".$this->escape($addr['addr_1'].' '.$addr['addr_2'])."',
1409 order_host='".$_SERVER['HTTP_HOST']."',
1410 receiver_email='".$arrData['buyer_email']."';";
1411
1412 if($arrData['cash_receipt_type'] && $arrData['cash_receipt_type'] != '0') {
1413 $pub_type = $arrData['cash_receipt_type'] == '1' ? '1' : '2';
1414 $idnt_no = $arrData['cash_receipt_type'] == '1' ? $arrData['company_num'] : $arrData['individual_num'];
1415 $gInfo = $this->objSF->getGoodsInfo($arrData['gs_idx']);
1416
1417 $q .= "INSERT INTO `sf_cash_receipt` SET
1418 `stat` = '1',
1419 `order_no` = '" . $order_no . "',
1420 `idnt_no` = '" . $idnt_no . "',
1421 `pub_type` = '" . $pub_type . "',
1422 `req_flag` = '" . $arrData['cash_receipt_type'] . "';";
1423 }
1424
1425 ## 장바구니 주문
1426 } else {
1427 $cart_total_price = 0;
1428 $list_cart = $this->getOrderPossibleCartList($_SESSION[mb_seq]);
1429 if($arrData['amount_shipp'] > 0) {
1430 $shipp_tot = $arrData['amount_shipp']; // 국가선택에 따른 배송료 차이등의 이유때문에 생긴 배송료 전용 파라미터.
1431 $this->isGroupShipping = trim($arrData['isGroupShipping']) ? true : false; // 배송료가 계산될때 묶음배송등이 발생되면 넘어오는 파라미터
1432 } else {
1433 $shipp_tot = $this->getCartShippTot($_SESSION[mb_seq], $isAdditionAddr);
1434 }
1435 $order_no_group = $arrData[order_no_group] ? $arrData[order_no_group] :$this->setGroupOrderNo;
1436 $_SESSION[last_order_no] = $order_no_group;
1437
1438 # 주문번호 유효성
1439 $chk_order = $this->getOrderInfo('3',$order_no_group);
1440 if(count($chk_order) > 0 && $arrData[payment_type] != 'cc') {
1441 $order_result[result] = '1';
1442 $order_result[resultMsg] = '주문중 일시적인 오류가 발생했습니다';
1443 Log::write("cardorder","중복 주문번호 발생 - 장바구니결제 - ".$order_no_group);
1444 return $order_result;
1445 }
1446
1447 $this->isBanderAccountSend = true;
1448
1449 #장바구니 주문 시 포인트를 사용할 경우 사용되는 변수
1450 $remain_use_point = $use_point;
1451
1452 for($i=0;$i<count($list_cart);$i++) {
1453
1454 #주문상품이 현재 접속한 shop의 밴더셀러 등록한 제품인지 확인
1455 #밴더셀러 등록한 제품이 맞으면 무통장입금 신청 시 밴더셀러의 계좌가 발송된다.
1456 #(단 밴더셀러의 계좌가 등록되어 있어야 한다.)
1457 if($_SESSION[private_shop] || $_SESSION[agency_id]){
1458 $shop_id = $_SESSION[agency_id] ? $_SESSION[agency_id] : $_SESSION[private_shop];
1459 $shopInfo = $this->getShopInfo($shop_id);
1460 $goodsInfo = $this->objSF->getGoodsInfo($list_cart[$i]['gs_idx']);
1461 if($goodsInfo[shop_idx] != $shopInfo[shop_idx]){
1462 $this->isBanderAccountSend = false;
1463 }
1464 }
1465
1466 $list_cart[$i] = $this->escapes($list_cart[$i]);
1467
1468 # 주문정보
1469 $cart_total_price += $list_cart[$i]['sale_price'];
1470 $this->setOrderNo();
1471 $addF = '';
1472
1473 if($_SESSION['lang']=='kr') {
1474 # 묶음배송이나 묶음 무료배송등이 존재할때는 배송비 총합을 해당 장바구니 주문의 첫번째 주문에 몰아서 넣는다
1475 if($this->isGroupShipping==true) {
1476 if($i==0) {
1477 $list_cart[$i]['sale_price'] += $shipp_tot; // 장바구니 결제시 첫번째 제품에 전체 배송비를 더해준다
1478 $cart_total_price += $shipp_tot;
1479 $shipp = $shipp_tot;
1480 } else {
1481 $shipp = '0';
1482 }
1483 } else { # 묶음 배송등의 조건이 없을때는 각 제품별로 배송비 계산
1484 $shipp = $this->getAllShippPrice($list_cart[$i]['goods_idx'],$list_cart[$i]['sale_price'], $isAdditionAddr);
1485 $cart_total_price += $shipp;
1486 $list_cart[$i]['sale_price'] += $shipp;
1487 }
1488 } else {
1489 if($i==0) {
1490 $list_cart[$i]['sale_price'] += $shipp_tot; // 장바구니 결제시 첫번째 제품에 전체 배송비를 더해준다
1491 $cart_total_price += $shipp_tot;
1492 $shipp = $shipp_tot;
1493 } else {
1494 $shipp = '0';
1495 }
1496 }
1497
1498 # 수량
1499 $qty = $list_cart[$i]['quantity'];
1500 /*$ea_sp = explode('|',$list_cart[$i]['opts_ea']);
1501 for ($j=0; $j < count($ea_sp); $j++) {
1502 $qty += $ea_sp[$j];
1503 }*/
1504 if(!isSellerSession()) { // 샘플 구매 아닌경우만 셀러 아이디 입력
1505 $addF = "seller_id='".$list_cart[$i]['seller_id']."',";
1506 }
1507 if($point_use_flag==true && $i==0) { // 장바구니 구매는 첫 제품에만 포인트 사용액을 넣어준다
1508 $addF2 = "pay_point=".$arrData[use_point].",";
1509 } else {
1510 $addF2 = '';
1511 }
1512 # 옵션 추가금액에 대한 공급가 계산 (샘플구매신 적용되지 않음)
1513 //if(!$_SESSION['seller']) {
1514 $optFactoryPrice = $this->calcOptFactoryPrice($list_cart[$i]['goods_idx'],$list_cart[$i]['opts_dp']);
1515 if($optFactoryPrice > 0 && is_numeric($optFactoryPrice)) {
1516 $addF .= "opts_price_factory=".$optFactoryPrice.",";
1517 }
1518 //}
1519 $q .= "insert into sf_order set
1520 stats='".$stats."',
1521 pay_gs_price='".$list_cart[$i]['sale_price']."',
1522 pay_shipp_price='".$shipp."',
1523 mb_type='".$_SESSION['mb_type']."',
1524 mb_seq=".$mb_seq.",
1525 $addF
1526 $addF2
1527 $addF_noChg
1528 pay_method='".$arrData['payment_type']."',
1529 goods_idx='".$list_cart[$i]['goods_idx']."',
1530 order_no='".$this->orderNo ."',
1531 order_no_group='".$order_no_group."',
1532 opts_values='".$list_cart[$i]['opts_values']."',
1533 opts_ea='".$list_cart[$i]['opts_ea']."',
1534 opts_dp='".$list_cart[$i]['opts_dp']."',
1535 quantity=".$qty.",
1536 account_name='".$arrData['buyer_ac_name']."',
1537 deliver_msg='".$arrData['deliver_msg']."',
1538 receiver_zipcode='".$addr['zipcode']."',
1539 receiver_name='".$addr['name_1']."',
1540 receiver_phone='".$addr['phone_1']."',
1541 receiver_addr='".$addr['addr_1'].' '.$addr['addr_2']."',
1542 order_host='".$_SERVER['HTTP_HOST']."',
1543 receiver_email='".$addr['email_1']."';";
1544
1545 if($arrData['cash_receipt_type'] && $arrData['cash_receipt_type'] != '0'){
1546
1547 //포인트 사용 여부 체크
1548 if($point_use_flag){
1549 //제품 가격보다 사용하는 포인트가 크면 제품가격을 0원처리한다.
1550 if($remain_use_point >= $list_cart[$i]['sale_price']){
1551 $sale_price = 0; //제품가격을 0원처리
1552 $remain_use_point -= $list_cart[$i]['sale_price']; //다음 제품에서 차감할 수 있는 포인트를 계산한다.
1553 }
1554 //사용포인트가 제품가격보다 낮으면 사용 포인트만큼 제품 가격에서 차감한다.
1555 else{
1556 $sale_price = $list_cart[$i]['sale_price'] - $remain_use_point; //포인트를 차감한 제품가격을 구한다.
1557 $remain_use_point = 0; //제품가격에서 모든 포인트를 차감 했기 때문에 잔여포인트를 0원 처리 한다.
1558 }
1559 }
1560 else{
1561 $sale_price = $list_cart[$i]['sale_price'];
1562 }
1563 $pub_type = $arrData['cash_receipt_type'] == '1' ? '1' : '2';
1564 $idnt_no = $arrData['cash_receipt_type'] == '1' ? $arrData['company_num'] : $arrData['individual_num'];
1565
1566 $q .= "INSERT INTO `sf_cash_receipt` SET
1567 `stat` = '1',
1568 `order_no` = '" . $this->orderNo . "',
1569 `idnt_no` = '" . $idnt_no . "',
1570 `pub_type` = '" . $pub_type . "',
1571 `req_flag` = '" . $arrData['cash_receipt_type'] . "';";
1572
1573 }
1574 array_push($order_nos, $this->orderNo);
1575 }
1576 # 0 원결제인지 체크 - 총 결제 금액 문제로 부득이 바로주문일시와 구분하여 체크함
1577 //if($point_use_flag == true && $cart_total_price-$use_point==0) {
1578 if($cart_total_price-$use_point==0) {
1579 $zero_payment_flag = true;
1580 }
1581 # 결제비번 체크 - 결제방식이 비인증인 경우만 체크해야 함.
1582 // if($isPayment==false) {
1583 // if($arrData[payment_type]=='cd' && isSession() && $zero_payment_flag == false) { // 0원결제일 경우 결제비번 체크하지 않음
1584 // $chk = $this->fetchOne("select mb_seq from sf_member where mb_payment_pwd=password('".$arrData[order_payment_pwd]."') and mb_email='".$_SESSION[mb_id]."' and mb_payment_pwd is not null and mb_payment_pwd<>''");
1585 // if(!$chk[mb_seq]) {
1586 // $order_result[result] = 'false';
1587 // $order_result[resultMsg] = '결제 비밀번호가 맞지 않습니다';
1588 // return $order_result;
1589 // }
1590 // }
1591 // }
1592 }
1593
1594 # 구매정보 쿼리실행
1595 if($this->multi_query($q)) {
1596 # 텐핑 cpa 구매 api 처리
1597 if($_SESSION['tenping_jid'] && $_SESSION['tenping_uid'] && $_SESSION['tenping_at'] && $_SESSION['private_shop']=='tenping') {
1598 $t_q = sprintf("insert into sf_order_etc set order_no='%s',data1='%s'",
1599 $order_no_group ? $order_no_group : $order_no,$_SESSION['tenping_jid'].'|'.$_SESSION['tenping_uid'].'|'.$_SESSION['tenping_at']);
1600 //die($t_q);
1601 $this->query($t_q);
1602 }
1603
1604 # 구매 user_agent 통계
1605 $this->query("insert into sf_order_user_agent set agent='".$_SERVER[HTTP_USER_AGENT]."',order_no='".$order_no."'");
1606 # 바로구매
1607 if($arrData['order_type']=='d') {
1608 # 무통장/알리페이/페이팔 바로주문 처리
1609 //if(($arrData['payment_type']=='ac' || $arrData['payment_type']=='al' || $arrData['payment_type']=='pp') && $zero_payment_flag==false) { // 무통장 바로구매
1610 // 무통장 바로구매
1611 // pnlink 결제도 저장 먼저
1612 // ac:무통장, al:알리페이, pp : paypal, pc:pnlink card, pr:pnlink 실시간, pv:pnlink 가상계좌
1613 if(
1614 (
1615 (MobileCheck() == true && in_array($arrData['payment_type'], array('pc', 'pr'))) !== false // 모바일의 pnlink는 저장먼저 해야함
1616 || in_array($arrData['payment_type'], array('ac', 'al', 'pp', 'pv')) !== false
1617 )
1618 && $zero_payment_flag==false
1619 ) {
1620 # 포인트사용 (무통장도 포인트는 선 사용된다);
1621 if($point_use_flag==true) { // 포인트사용러
1622 if(isSellerSession()) {
1623 $objTagby = new Tagby;
1624 $result_point = $objTagby->payPoint($_SESSION['mb_id'], $arrData[use_point]);
1625 if($result_point) {
1626 $arr_point = json_decode($result_point, true);
1627 if($arr_point['code'] != '1') {
1628 Log::write_pay($order_no, "포인트 사용 실패. (code: " . $arr_point['code'] . ", msg: " . $arr_point['msg']);
1629 }
1630 } else {
1631 Log::write_pay($order_no, "포인트 사용 실패. (api 호출 실패, ". $arrData[use_point] .")");
1632 }
1633 } else {
1634 $this->usePoint($_SESSION[mb_seq],$arrData['from_seller_id'],$arrData[use_point]); # 셀러가 포인트 사용 분기
1635 }
1636 }
1637 //if($arrData[payment_type]!='al') {
1638 if(in_array($arrData['payment_type'], array('al', 'pc', 'pr', 'pv')) === false) {
1639 $this->sendOrderSms($arrData['buyer_phone'],$_SESSION['last_order_no'],$arrData['gs_title_sms'],$arrData['sale_price']-$use_point,'2');
1640 }
1641 $order_result[result] = '1';
1642 # 카드 바로주문 처리
1643 //} else if($arrData[payment_type]=='cd' && $zero_payment_flag==false) {
1644 } else if(in_array($arrData['payment_type'], array('cd', 'pc', 'pr')) !== false && $zero_payment_flag==false) {
1645 // pnlink 카드, 실시간계좌이체는 바로 성공처리
1646 if(in_array($arrData['payment_type'], array('pc', 'pr')) !== false) {
1647 $isPayment = true;
1648 }
1649 # 이미 결제가 완료된 주문이면 바로 성공처리
1650 if($isPayment==true) {
1651 $order_result[result] = '1';
1652 } else {
1653 if($shop_info['shop_config_pg_com']=='2') { // 나이스페이 비이증
1654 $order_result = $this->payment_request_card_billing($arrData);
1655 } else {
1656 $order_result[result] = '1'; // 이니시스 인증(비인증) 결제는 우선 성공으로 간주
1657 }
1658 }
1659
1660 # 카드결제 성공
1661 if($order_result[result]=='1') {
1662 if($shop_info['shop_config_pg_com']=='2') { // 나이스페이 비인증인경우만 실제 결제가 완료된 상태로 넘어옴으로 실결제 후 처리
1663 # 포인트사용
1664 if($point_use_flag==true) { // 포인트사용
1665 if(isSellerSession()) {
1666 $objTagby = new Tagby;
1667 $result_point = $objTagby->payPoint($_SESSION['mb_id'], $arrData[use_point]);
1668 if($result_point) {
1669 $arr_point = json_decode($result_point, true);
1670 if($arr_point['code'] != '1') {
1671 Log::write_pay($order_no, "포인트 사용 실패. (code: " . $arr_point['code'] . ", msg: " . $arr_point['msg']);
1672 }
1673 } else {
1674 Log::write_pay($order_no, "포인트 사용 실패. (api 호출 실패, ". $arrData[use_point] .")");
1675 }
1676 } else {
1677 $this->usePoint($_SESSION[mb_seq],$arrData['from_seller_id'],$arrData[use_point]); # 셀러가 포인트 사용 분기
1678 }
1679 }
1680 $this->updateOrderStats('2',$order_no);
1681 $this->addOrderAGAC($order_no);
1682 $this->addPoint($order_no);
1683 $this->sendOrderSms($arrData[buyer_phone],$_SESSION[last_order_no],$arrData[gs_title_sms],$arrData[sale_price]-$use_point,'1');
1684 }
1685 # 카드결제 실패
1686 } else {
1687 if($order_result['resultMsg']=='unknownErr') {
1688 $order_result['resultMsg'] = "결제가 실패했습니다. 일시적인 오류일 수 있으니 결제하기를 다시 눌러봐주세요";
1689 }
1690 Log::write_pay($order_no,"결제실패후 주문삭제1 $q");
1691 if(!$this->query("delete from sf_order where order_no='".$order_no."'")) {
1692 Log::write_pay($order_no,"결제 실패후 주문삭제 실패 | delete from sf_order where order_no='".$order_no."'");
1693 }
1694 }
1695
1696 # 0원 바로주문 처리
1697 } else if($zero_payment_flag==true) {
1698 # 포인트사용
1699 if($point_use_flag==true) { // 포인트사용
1700 if(isSellerSession()) {
1701 $objTagby = new Tagby;
1702 $result_point = $objTagby->payPoint($_SESSION['mb_id'], $arrData[use_point]);
1703 if($result_point) {
1704 $arr_point = json_decode($result_point, true);
1705 if($arr_point['code'] != '1') {
1706 Log::write_pay($order_no, "포인트 사용 실패. (code: " . $arr_point['code'] . ", msg: " . $arr_point['msg']);
1707 }
1708 } else {
1709 Log::write_pay($order_no, "포인트 사용 실패. (api 호출 실패, ". $arrData[use_point] .")");
1710 }
1711 } else {
1712 $this->usePoint($_SESSION[mb_seq],$arrData['from_seller_id'],$arrData[use_point]); # 셀러가 포인트 사용 분기
1713 }
1714 }
1715 $order_result[result] = '1';
1716 $this->updateOrderStats('2',$order_no);
1717 $this->addOrderAGAC($order_no);
1718 $this->addPoint($order_no);
1719 $this->sendOrderSms($arrData[buyer_phone],$_SESSION[last_order_no],$arrData[gs_title_sms],$arrData[sale_price]-$use_point,'1');
1720 # 전자지갑 바로주문 처리
1721 } else if($arrData[payment_type] == 'cc' && $zero_payment_flag == false) {
1722 $tmp['price'] = $arrData['amount'];
1723 $tmp['referer_code'] = $arrData['wallet_referer_code'];
1724 $tmp['symbol'] = $arrData['my_balance_list'];
1725 $result = $this->curl_wallet_payment($tmp);
1726 if($result['code'] == '1') {
1727 if($point_use_flag==true) { // 포인트사용
1728 if(isSellerSession()) {
1729 $objTagby = new Tagby;
1730 $result_point = $objTagby->payPoint($_SESSION['mb_id'], $arrData[use_point]);
1731 if($result_point) {
1732 $arr_point = json_decode($result_point, true);
1733 if($arr_point['code'] != '1') {
1734 Log::write_pay($order_no, "포인트 사용 실패. (code: " . $arr_point['code'] . ", msg: " . $arr_point['msg']);
1735 }
1736 } else {
1737 Log::write_pay($order_no, "포인트 사용 실패. (api 호출 실패, ". $arrData[use_point] .")");
1738 }
1739 } else {
1740 $this->usePoint($_SESSION[mb_seq],$arrData['from_seller_id'],$arrData[use_point]); # 셀러가 포인트 사용 분기
1741 }
1742 }
1743 $order_result[result] = '1';
1744 $this->updateOrderStats('2',$order_no);
1745 $this->addOrderAGAC($order_no);
1746 $this->addPoint($order_no);
1747 $this->sendOrderSms($arrData[buyer_phone],$_SESSION[last_order_no],$arrData[gs_title_sms],$arrData[sale_price]-$use_point,'1');
1748 } else if($result['code'] === '2') {
1749 $order_result[result] = 'false';
1750 $order_result[resultMsg] = '잔액이 부족합니다.';
1751 } else if($result['code'] === '5' && $result['msg'] === '007') {
1752 $order_result[result] = 'false';
1753 $order_result[resultMsg] = '수수료가 부족합니다. ETH 수수료를 충전해주세요.';
1754 Log::write('orderErr', "바로주문 전자지갑결제 오류 발생 " . $result['code'] . " - " . $result['msg']);
1755 } else {
1756 $order_result[result] = 'false';
1757 $order_result[resultMsg] = '주문 중 일시적인 오류가 발생하였습니다.';
1758 Log::write('orderErr', "바로주문 전자지갑결제 오류 발생 " . $result['code'] . " - " . $result['msg']);
1759 }
1760 # 바로주문 예외발생
1761 } else {
1762 sendSmsDev("바로주문 오류 발생 - $order_no");
1763 $order_result[result] = 'false';
1764 $order_result[resultMsg] = '주문중 일시적인 오류가 발생하였습니다';
1765 Log::write('orderErr',"바로주문 예외 발생 $q");
1766 }
1767 # 장바구니 구매
1768 } else if($arrData[order_type]=='c') {
1769 # 장바구니 무통장/알리페이/페이팔 구매
1770 //if(($arrData[payment_type]=='ac' || $arrData[payment_type]=='al' || $arrData[payment_type]=='pp') && $zero_payment_flag==false) { // 무통장
1771 //if(in_array($arrData['payment_type'], array('ac', 'al', 'pp', 'pv')) && $zero_payment_flag==false) { // 무통장 바로구매
1772 if(
1773 (
1774 (MobileCheck() == true && in_array($arrData['payment_type'], array('pc', 'pr'))) !== false // 모바일의 pnlink는 저장먼저 해야함
1775 || in_array($arrData['payment_type'], array('ac', 'al', 'pp', 'pv')) !== false
1776 )
1777 && $zero_payment_flag==false
1778 ) {
1779 // pp : paypay, pc:pnlink card, pr:pnlink 실시간, pv:pnlink 가상계좌
1780 if(in_array($arrData['payment_type'], array('al', 'pc', 'pr', 'pv')) === false) {
1781 $this->sendOrderSms($arrData[buyer_phone],$order_no_group,$arrData[gs_title_sms],$cart_total_price-$use_point,'2');
1782 }
1783
1784 $order_result[result] = '1';
1785 if($point_use_flag==true) { // 포인트사용
1786 if(isSellerSession()) {
1787 $objTagby = new Tagby;
1788 $result_point = $objTagby->payPoint($_SESSION['mb_id'], $arrData[use_point]);
1789 if($result_point) {
1790 $arr_point = json_decode($result_point, true);
1791 if($arr_point['code'] != '1') {
1792 Log::write_pay($order_no, "포인트 사용 실패. (code: " . $arr_point['code'] . ", msg: " . $arr_point['msg']);
1793 }
1794 } else {
1795 Log::write_pay($order_no, "포인트 사용 실패. (api 호출 실패, ". $arrData[use_point] .")");
1796 }
1797 } else {
1798 $this->usePoint($_SESSION[mb_seq],$arrData['from_seller_id'],$arrData[use_point]); # 셀러가 포인트 사용 분기
1799 }
1800 }
1801 # 카드 장바구니 구매
1802 //} else if($arrData[payment_type]=='cd' && $zero_payment_flag==false) {
1803 } else if(in_array($arrData['payment_type'], array('cd', 'pc', 'pr')) !== false && $zero_payment_flag==false) {
1804 //$order_result = $this->payment_request_card($arrData);
1805 // pnlink 카드, 실시간계좌이체는 바로 성공처리
1806 if(in_array($arrData['payment_type'], array('pc', 'pr')) !== false) {
1807 $isPayment = true;
1808 }
1809 # 이미 결제가 완료된 주문이면 바로 성공처리
1810 if($isPayment==true) {
1811 $order_result[result] = '1';
1812 } else {
1813 $order_result = $this->payment_request_card_billing($arrData); // 나이스 페이로 변경 // 171220
1814 }
1815
1816 if($order_result[result]=='1') {
1817 for($i=0;$i<count($order_nos);$i++) {
1818 $this->updateOrderStats('2',$order_nos[$i]);
1819 $this->addOrderAGAC($order_nos[$i]);
1820 $this->addPoint($order_nos[$i]);
1821 }
1822 if($point_use_flag==true) { // 포인트사용
1823 if(isSellerSession()) {
1824 $objTagby = new Tagby;
1825 $result_point = $objTagby->payPoint($_SESSION['mb_id'], $arrData[use_point]);
1826 if($result_point) {
1827 $arr_point = json_decode($result_point, true);
1828 if($arr_point['code'] != '1') {
1829 Log::write_pay($order_no, "포인트 사용 실패. (code: " . $arr_point['code'] . ", msg: " . $arr_point['msg']);
1830 }
1831 } else {
1832 Log::write_pay($order_no, "포인트 사용 실패. (api 호출 실패, ". $arrData[use_point] .")");
1833 }
1834 } else {
1835 $this->usePoint($_SESSION[mb_seq],$arrData['from_seller_id'],$arrData[use_point]); # 셀러가 포인트 사용 분기
1836 }
1837 }
1838 $this->sendOrderSms($arrData[buyer_phone],$order_no_group,$arrData[gs_title_sms],$cart_total_price-$use_point,'1');
1839 } else {
1840 if($order_result['resultMsg']=='unknownErr') {
1841 $order_result['resultMsg'] = "결제가 실패했습니다. 일시적인 오류일 수 있으니 결제하기를 다시 눌러봐주세요";
1842 }
1843 Log::write_pay($order_no,"결제실패후 주문삭제2 $q");
1844 # 실패시 주문 삭제
1845 for($i=0;$i<count($order_nos);$i++) {
1846 if(!$this->query("delete from sf_order where order_no='".$order_nos[$i]."'")) {
1847 Log::write_pay($order_no,"결제 실패후 주문삭제 실패 | delete from sf_order where order_no='".$order_no."'");
1848 }
1849 }
1850 }
1851 # 장바구니 0원 구매
1852 } else if($zero_payment_flag==true) {
1853 if($point_use_flag==true) { // 포인트사용
1854 if(isSellerSession()) {
1855 $objTagby = new Tagby;
1856 $result_point = $objTagby->payPoint($_SESSION['mb_id'], $arrData[use_point]);
1857 if($result_point) {
1858 $arr_point = json_decode($result_point, true);
1859 if($arr_point['code'] != '1') {
1860 Log::write_pay($order_no, "포인트 사용 실패. (code: " . $arr_point['code'] . ", msg: " . $arr_point['msg']);
1861 }
1862 } else {
1863 Log::write_pay($order_no, "포인트 사용 실패. (api 호출 실패, ". $arrData[use_point] .")");
1864 }
1865 } else {
1866 $this->usePoint($_SESSION[mb_seq],$arrData['from_seller_id'],$arrData[use_point]); # 셀러가 포인트 사용 분기
1867 }
1868 }
1869 $order_result[result] = '1';
1870 for($i=0;$i<count($order_nos);$i++) {
1871 $this->updateOrderStats('2',$order_nos[$i]);
1872 $this->addOrderAGAC($order_nos[$i]);
1873 $this->addPoint($order_nos[$i]);
1874 }
1875 $this->sendOrderSms($arrData[buyer_phone],$order_no_group,$arrData[gs_title_sms],$cart_total_price-$use_point,'1');
1876 # 전자지갑 장바구니 처리
1877 } else if($arrData[payment_type] == 'cc' && $zero_payment_flag == false) {
1878 $tmp['price'] = $arrData['amount'];
1879 $tmp['referer_code'] = $arrData['wallet_referer_code'];
1880 $tmp['symbol'] = $arrData['my_balance_list'];
1881 $result = $this->curl_wallet_payment($tmp);
1882 if($result['code'] == '1') {
1883 if($point_use_flag==true) { // 포인트사용
1884 if(isSellerSession()) {
1885 $objTagby = new Tagby;
1886 $result_point = $objTagby->payPoint($_SESSION['mb_id'], $arrData[use_point]);
1887 if($result_point) {
1888 $arr_point = json_decode($result_point, true);
1889 if($arr_point['code'] != '1') {
1890 Log::write_pay($order_no, "포인트 사용 실패. (code: " . $arr_point['code'] . ", msg: " . $arr_point['msg']);
1891 }
1892 } else {
1893 Log::write_pay($order_no, "포인트 사용 실패. (api 호출 실패, ". $arrData[use_point] .")");
1894 }
1895 } else {
1896 $this->usePoint($_SESSION[mb_seq],$arrData['from_seller_id'],$arrData[use_point]); # 셀러가 포인트 사용 분기
1897 }
1898 }
1899 $order_result[result] = '1';
1900 for($i=0;$i<count($order_nos);$i++) {
1901 $this->updateOrderStats('2',$order_nos[$i]);
1902 $this->addOrderAGAC($order_nos[$i]);
1903 $this->addPoint($order_nos[$i]);
1904 }
1905 $this->sendOrderSms($arrData[buyer_phone],$order_no_group,$arrData[gs_title_sms],$cart_total_price-$use_point,'1');
1906 } else if($result['code'] == '2') {
1907 $order_result[result] = 'false';
1908 $order_result[resultMsg] = '잔액이 부족합니다.';
1909 } else if($result['code'] === '5' && $result['msg'] === '007') {
1910 $order_result[result] = 'false';
1911 $order_result[resultMsg] = '수수료가 부족합니다. ETH 수수료를 충전해주세요.';
1912 Log::write('orderErr', "바로주문 전자지갑결제 오류 발생 " . $result['code'] . " - " . $result['msg']);
1913 } else {
1914 $order_result[result] = 'false';
1915 $order_result[resultMsg] = '주문 중 일시적인 오류가 발생하였습니다.';
1916 Log::write('orderErr', "장바구니 전자지갑결제 오류 발생 " . $result['code'] . " - " . $result['msg']);
1917 }
1918 }
1919 # 장바구니 구매 예외 발생
1920 } else {
1921 sendSmsDev("장바구니 주문 오류 발생 - $order_no");
1922 $order_result[result] = 'false';
1923 $order_result[resultMsg] = '주문중 일시적인 오류가 발생하였습니다';
1924 Log::write('orderErr',"장바구니 예외 발생 $q");
1925 }
1926 } else {
1927 Log::write('SQLErr','Order Insert False - '.$q);
1928 $order_result[result] = 'false';
1929 }
1930 return $order_result;
1931 }
1932 function accountHolderInfo(){
1933
1934 global $shop_info;
1935 $isVenderSeller = $this->isKasType($_SESSION[private_shop]);
1936 $isAgencyVenderSeller = $this->isAgencyAccountInfo($_SESSION[private_shop]);
1937
1938 //if($isAgencyVenderSeller[status] == true)
1939 if($isAgencyVenderSeller[status] == true && $this->isBanderAccountSend == true)
1940 {
1941 $account_info = $isAgencyVenderSeller[bank_name].' '.$isAgencyVenderSeller[account_number].' '.$isAgencyVenderSeller[account_holder];
1942 }
1943 //else if($_SESSION['seller'] == '' && $_SESSION['shop_idx'] == '' && $isVenderSeller && $private_shop_info[footer_account] != ''){
1944 else if($_SESSION['seller'] == '' && $_SESSION['shop_idx'] == '' && $isVenderSeller && $private_shop_info[footer_account] != '' && $this->isBanderAccountSend == true){
1945 $account_info = $private_shop_info[footer_account];
1946 }
1947 else {
1948 $account_info = $shop_info[footer_account];
1949 }
1950
1951 return $account_info;
1952
1953 }
1954 // function sendOrderSms($to_phone,$order_no,$goods,$price,$payment,$to_email='') {
1955 // global $shop_info;
1956
1957 // $account_info = $this->accountHolderInfo();
1958
1959 // $q = "select count(a.idx) as cnt,sum(a.pay_gs_price)-sum(a.pay_point) as pay_price,b.seller_name,b.seller_id,c.gs_name,a.receiver_phone from sf_order a
1960 // left join sf_member b on a.seller_id=b.seller_id
1961 // left join sf_goods c on a.goods_idx=c.gs_idx where a.order_no='".$order_no."'";
1962 // $order_data = $this->fetch1($q);
1963 // $market_name = $order_data['seller_name'] ? $order_data['seller_name'] : $order_data['seller_id'];
1964
1965
1966 // if($_SESSION['lang']=='kr') {
1967 // if(!trim($market_name)) $market_name = "태그바이";
1968
1969 // $send_url = 'http://cpsms.skysms.co.kr/cpsms/cp_mms_send.php';
1970 // $stats = $payment=='1' ? "주문 완료" : "주문 접수";
1971 // $sms_msg = "[".$market_name." - ".$stats."]\n";
1972 // $sms_msg .= "● 주문상품 : ".str_replace('|', "\n",$goods)."\n";
1973 // $sms_msg .= "● 주문번호 : ".$order_no."\n\n";
1974 // if($payment=='1') {
1975 // $sms_msg .= "고객님, 주문하신 상품 결제가\n";
1976 // $sms_msg .= "완료 되었습니다.주문하신 상품은 \n";
1977 // $sms_msg .= "2~5일 이내 발송되며, 배송이\n";
1978 // $sms_msg .= "지연되는 경우 별도로 안내 드리겠습니다.\n";
1979 // $sms_msg .= "감사합니다\n";
1980 // } else {
1981 // $sms_msg .= "고객님, 주문하신 상품이 접수 되었습니다.";
1982 // $sms_msg .= $account_info;
1983 // $sms_msg .= number_format($price)." 입금 시";
1984 // $sms_msg .= "주문이 완료됩니다. 감사합니다.";
1985 // }
1986 // $vars = array(
1987 // 'cpuserid' => 'argethero',
1988 // 'passwd' => '!Sky_hun80@',
1989 // 'destination' => preg_replace("/[^0-9]/","",$to_phone),
1990 // 'callback' => $_ENV['sms_sender_no'],
1991 // 'body' => iconv('utf-8','euc-kr',$sms_msg)
1992 // );
1993 // $res = soket_req($send_url,$vars);
1994 // if($res['status']=='ok') {
1995 // if($_SERVER[HTTP_HOST]!='dev.socialmarket.kr') {
1996 // $sms_msg = $goods;
1997 // $sms_msg .= $payment=='1' ? " 카드주문" : " 무통장 주문";
1998 // $sms_msg .="이 들어왔습니다.(".$price."원)";
1999 // sendSms($_ENV['sms_sender_no'],$_ENV['sms_manager_no'],$sms_msg);
2000 // }
2001 // }
2002 // } else {
2003 // # 추후 해외 주문에 대해 메일링 되도록
2004 // }
2005 // }
2006
2007 function sendOrderSms($to_phone,$order_no,$goods,$price,$payment,$to_email='') {
2008 global $shop_info;
2009 $objSql = new Mysql;
2010
2011 $order_type = substr($order_no,0,1);
2012 if($order_type=='g') {
2013 $cond = "a.order_no_group='".$order_no."'";
2014 } else {
2015 $cond = "a.order_no='".$order_no."'";
2016 }
2017
2018 $account_info = $this->accountHolderInfo();
2019
2020 $q = "select (a.pay_gs_price-a.pay_point) as pay_price,b.seller_name,b.seller_id,c.gs_name,a.receiver_phone,a.quantity,a.receiver_name,a.opts_dp
2021 from sf_order a
2022 left join sf_member b on a.seller_id=b.seller_id
2023 left join sf_goods c on a.goods_idx=c.gs_idx where $cond group by a.idx";
2024 $order_data = $this->fetchs($q);
2025
2026 $shop_name = $order_data[0]['seller_name'] ? $order_data[0]['seller_name'] : $order_data[0]['seller_id'];
2027 # 샘플구매시는 shop 정보를 못가져오기에 사이트 정보로 셋팅
2028 if(!$shop_name) {
2029 $shop_name = $shop_info['shop_name'];
2030 }
2031 $name = $order_data[0]['receiver_name'];
2032
2033 if(count($order_data)==1) {
2034 $goods_name = $order_data[0]['gs_name'];
2035 $goods_option = $order_data[0]['opts_dp'];
2036 $goods_quantity = '총수량 '.$order_data[0]['quantity'];
2037 // $price = $order_data[0]['pay_price'];
2038
2039 } else {
2040 $goods_name = $order_data[0]['gs_name'].' 외 '.(count($order_data)-1).'건';
2041 for ($i=0; $i < count($order_data); $i++) {
2042 $goods_option .= $order_data[$i]['opts_dp'];
2043 $goods_quantity += $order_data[$i]['quantity'];
2044 // $price += $order_data[$i]['pay_price'];
2045 }
2046 $goods_quantity = '총수량 '.$goods_quantity;
2047 }
2048
2049 if($_SESSION['lang']=='kr') {
2050 if(!trim($shop_name)) $shop_name = "태그바이";
2051 if($payment=='1') {
2052 $tmp_code = 'SJT_038297';
2053 $sms_msg = "[$shop_name - 주문 접수]
2054● 주문상품 : ".$objSql->escape($goods_name)." / $goods_option / $goods_quantity
2055● 주문번호 : $order_no
2056
2057$name 고객님, 주문하신 상품 결제가 완료 되었습니다.주문하신 상품은
2058공휴일 제외 2~5일 이내 발송되며, 배송이 지연되는 경우 별도로 안내 드리겠습니다.
2059감사합니다.";
2060 } else {
2061 $tmp_code = 'SJT_038295';
2062 $sms_msg = "[$shop_name - 주문 접수]
2063● 주문상품 : ".$objSql->escape($goods_name)." / $goods_option / $goods_quantity
2064● 주문번호 : $order_no
2065
2066$name 고객님, 주문하신 상품이 접수 되었습니다.
2067$account_info ".number_format($price)."원 입금 시 주문이 완료됩니다. 감사합니다.";
2068 }
2069
2070 # 임대몰은 문자로
2071 if($shop_info['shop_type']=='2') {
2072 $this->sendAlimTok($to_phone,$sms_msg,$tmp_code,'3');
2073 } else {
2074 $this->sendAlimTok($to_phone,$sms_msg,$tmp_code);
2075 ## 상품판매 알림
2076 if($order_data[0]['seller_id'] && $payment=='1') {
2077 $tres = $this->fetchOne("select seller_phone from sf_member where seller_id='".$order_data[0]['seller_id']."'");
2078 if($tres['seller_phone']) {
2079 $deliver_com_link = $_SERVER['HTTP_HOST'];
2080 $tmp_code = 'SJT_038301';
2081 $sms_msg = "[주문 알림]
2082".$shop_name."님 상품판매 축하드립니다!
2083
2084● 주문자이름 : $name
2085● 주문상품 : $goods_name / $goods_option / $goods_quantity
2086● 주문번호 : $order_no
2087● 결제금액 : ".number_format($price)."
2088
2089결제완료 후 공휴일 제외 2~5일 이내 배송될 예정입니다.
2090감사합니다.
2091
2092판매내역 조회하기 - $deliver_com_link";
2093 $this->sendAlimTok($tres['seller_phone'],$sms_msg,$tmp_code);
2094 }
2095 }
2096 }
2097 } else {
2098 # 추후 해외 주문에 대해 메일링 되도록
2099 }
2100 if($_SERVER[HTTP_HOST]!='dev.socialmarket.kr') {
2101 $sms_msg = $goods;
2102 $sms_msg .= $payment=='1' ? " 카드주문" : " 무통장 주문";
2103 $sms_msg .="이 들어왔습니다.(".$price."원)";
2104 sendSms($_ENV['sms_sender_no'],$_ENV['sms_manager_no'],$sms_msg);
2105 }
2106 }
2107
2108 function sendAlimTok($send_number, $message,$tmp_code,$msg_type = '6') {
2109 $objSql = new Mysql();
2110 $objSql->con_alimtok();
2111// mysqli_select_db($objSql->oSql,"tagby_msg_live");
2112// $sender_key = "0ce413dd436ba9b6485ebb8190bb9a419912cdc6";
2113 $sender_key = "bf94e1dd5740da51ba028d96d4abc373f6410aac";
2114 $callback_number = "07075002220";
2115
2116 $sql = "insert into msg_queue set
2117 msg_type=$msg_type,
2118 send_type=1,
2119 k_next_type = 5,
2120 dstaddr='".$send_number."',
2121 callback='".$callback_number."',
2122 text='".$message."',
2123 request_time=now(),
2124 sender_key='".$sender_key."',
2125 k_template_code='".$tmp_code."'";
2126 if(!$objSql->query($sql)) {
2127 Log::write('smsErr','문자전송 실패 - '.$sql);
2128 }
2129
2130 }
2131 function getNotice($admin='') {
2132 $admin=='1' ? $cond = "1=1" : $cond="notice_view='1'";
2133 $chk = $this->fetch1("select * from sf_notice where $cond and notice_start<='".date('Y-m-d')."' and notice_end>='".date('Y-m-d')."'");
2134 if(trim($chk['notice_url'])) {
2135 if($chk['notice_url']==$_SERVER['HTTP_HOST']) {
2136 return $chk;
2137 } else {
2138 return false;
2139 }
2140 } else {
2141 return $chk;
2142 }
2143
2144 }
2145 function addOrderActive($arrData) {
2146 $order_result = array();
2147 if(!isSession() && $arrData[just_order]!='1') {
2148 $order_result[result] = 'false';
2149 return $order_result;
2150 }
2151 # 배송정보
2152 if(isSession() && $arrData[just_order]!='1') {
2153 $this->addDeliverInfo($arrData);
2154 $addr = $this->getDeliveryInfo();
2155 } else {
2156 $addr[name_1] = $arrData[buyer_name];
2157 $addr[phone_1] = $arrData[buyer_phone];
2158 $addr[addr_1] = $arrData[buyer_addr];
2159 $addr[addr_2] = $arrData[buyer_addr2];
2160 }
2161
2162
2163 $order_nos = array();
2164 $mb_seq = $arrData[just_order] ? "0" : $_SESSION['mb_seq'];
2165 if($arrData[order_type]=='d') { // 바로주문
2166 # 판매가능한 제품인지
2167 $chk = $this->fetchOne("select gs_remain,gs_startdate,gs_enddate,gs_discount from sf_goods where gs_idx=".$arrData['gs_idx']." limit 1");
2168 // if(date('Y-m-d') < $chk[gs_startdate] || date('Y-m-d') > $chk[gs_enddate]) {
2169 // Log::write('orderFalse','판매 불가능 제품 구매시도');
2170 // $order_result[result] = 'false';
2171 // return $order_result;
2172 // }
2173 # 주문정보
2174 $this->setOrderNo();
2175 $order_no = $arrData[order_no] ? $arrData[order_no] : $this->orderNo;
2176 $shipp = $this->getShippPrice($arrData[gs_idx],$arrData[sale_price]);
2177 $_SESSION[last_order_no] = $order_no;
2178 $arrData['sale_price'] += $shipp;
2179
2180 # 수량
2181 $qty = 0;
2182 $ea_sp = explode('|',$arrData['opts_qt']);
2183 for ($i=0; $i < count($ea_sp); $i++) {
2184 $qty += $ea_sp[$i];
2185 }
2186
2187 $q = "insert into sf_order set
2188 stats='2',
2189 pay_gs_price='".$arrData['sale_price']."',
2190 pay_shipp_price='".$shipp."',
2191 mb_type='".$_SESSION['mb_type']."',
2192 mb_seq=".$mb_seq.",
2193 seller_id='".$arrData['from_seller_id']."',
2194 pay_method='".$arrData['payment_type']."',
2195 goods_idx='".$arrData['gs_idx']."',
2196 order_no='".$order_no ."',
2197 opts_values='".$arrData['opts_values']."',
2198 opts_ea='".$arrData['opts_qt']."',
2199 opts_dp='".$arrData['opts_dp']."',
2200 quantity=".$qty.",
2201 account_name='".$arrData['buyer_ac_name']."',
2202 deliver_msg='".$arrData['deliver_msg']."',
2203 receiver_name='".$addr['name_1']."',
2204 receiver_phone='".$addr['phone_1']."',
2205 receiver_addr='".$addr['addr_1'].' '.$addr['addr_2']."',
2206 receiver_email='".$arrData['buyer_email']."'";
2207 } else {
2208 $cart_total_price = 0;
2209 $list_cart = $this->getCartList($_SESSION[mb_seq]);
2210 $order_no_group = $this->setGroupOrderNo();
2211 for($i=0;$i<count($list_cart);$i++) {
2212 # 주문정보
2213 $cart_total_price += $list_cart[$i]['sale_price'];
2214 $this->setOrderNo();
2215 $shipp = $list_cart[$i][shipp_price];
2216 $_SESSION[last_order_no] = $this->orderNo;
2217 $list_cart[$i]['sale_price'] += $shipp;
2218 $cart_total_price += $shipp;
2219
2220 # 수량
2221 $qty = 0;
2222 $ea_sp = explode('|',$list_cart[$i]['opts_ea']);
2223 for ($j=0; $j < count($ea_sp); $j++) {
2224 $qty += $ea_sp[$j];
2225 }
2226
2227 $q .= "insert into sf_order set
2228 stats='2',
2229 pay_gs_price='".$list_cart[$i]['sale_price']."',
2230 pay_shipp_price='".$shipp."',
2231 mb_type='".$_SESSION['mb_type']."',
2232 mb_seq=".$mb_seq.",
2233 seller_id='".$list_cart[$i]['seller_id']."',
2234 pay_method='".$arrData['payment_type']."',
2235 goods_idx='".$list_cart[$i]['goods_idx']."',
2236 order_no='".$this->orderNo ."',
2237 order_no_group='".$order_no_group."',
2238 opts_values='".$list_cart[$i]['opts_values']."',
2239 opts_ea='".$list_cart[$i]['opts_ea']."',
2240 opts_dp='".$list_cart[$i]['opts_dp']."',
2241 quantity=".$qty.",
2242 account_name='".$arrData['buyer_ac_name']."',
2243 deliver_msg='".$list_cart[$i]['deliver_msg']."',
2244 receiver_name='".$addr['name_1']."',
2245 receiver_phone='".$addr['phone_1']."',
2246 receiver_addr='".$addr['addr_1'].' '.$addr['addr_2']."',
2247 receiver_email='".$addr['email_1']."';";
2248 array_push($order_nos, $this->orderNo);
2249 }
2250 }
2251 if($this->multi_query($q)) {
2252 # 재고 삭감
2253 if(!$this->query("update sf_goods set gs_remain = gs_remain - ".$arrData['opts_qt']." where gs_idx=".$arrData['gs_idx']."")) {
2254 //Log::write('SQLErr','Remain minus false2 - '."update sf_goods set gs_remain = gs_remain - ".$arrData['opts_qt']." where gs_idx=".$arrData['gs_idx']."");
2255 }
2256 # 문자
2257 if($arrData[order_type]=='d') { // 바로구매
2258
2259 $order_result[result] = '1';
2260 return $order_result;
2261
2262 } else if($arrData[order_type]=='c') { // 장바구니구매
2263 if(count($list_cart) > 1) {
2264 $sms_title = $list_cart[0][gs_name].'외 '.(count($list_cart)-1).'건';
2265 } else {
2266 $sms_title = "[소셜마켓]\n주문번호 ".$_SESSION[last_order_no];
2267 }
2268 $order_result[result] = '1';
2269 return $order_result;
2270 }
2271 return true;
2272 } else {
2273 Log::write('SQLErr','Order Insert False - '.$q);
2274 $order_result[result] = 'false';
2275 return $order_result;
2276 }
2277 }
2278
2279 function addOrderAG($order_no) {
2280 if($_SESSION['is_agency'] && $_SESSION['agency_id']) {
2281 $order_data = $this->fetchOne("select seller_id,pay_gs_price,pay_shipp_price,goods_idx from sf_order where order_no='".$order_no."'");
2282 if($order_data[seller_id]) {
2283 $chk = $this->fetchOne("select idx from sf_order_recom where order_no='".$order_no."'");
2284 if(!$chk[idx]) {
2285 $q = "insert into sf_order_recom set seller_id='".$order_data[seller_id]."',
2286 recom_id='".$_SESSION['agency_id']."',
2287 pay_gs_price=".($order_data[pay_gs_price]-$order_data[pay_shipp_price]).",
2288 goods_idx=".$order_data[goods_idx].",
2289 order_no='".$order_no."'";
2290 if(!$this->query($q)) {
2291 Log::write('Err',"addOrderAG 실패 - ".$q);
2292 }
2293 }
2294 }
2295 }
2296 }
2297
2298 // order_no가 아닌 order idx 값으로 에이전시 주문 넣어줌 그리고 현재 에이전시 세션 체크 안함 - 관리자 Admin 클래스의 addOrderAG와 동일
2299 function addOrderAGADM($oidx) {
2300 $order_data = $this->fetchOne("select a.seller_recom,seller_recom2,b.order_no,b.seller_id,b.pay_gs_price,b.pay_shipp_price,b.goods_idx from sf_member a left join sf_order b on a.seller_id=b.seller_id where b.idx=$oidx");
2301 $recom = $order_data['seller_recom2'] ? $order_data['seller_recom2'] : $order_data['seller_recom'];
2302 if(trim($recom)) {
2303 $chk = $this->fetchOne("select idx from sf_order_recom where order_no='".$order_data['order_no']."'");
2304 if(!$chk[idx]) {
2305 $q = "insert into sf_order_recom set seller_id='".$order_data['seller_id']."',
2306 recom_id='".$recom."',
2307 pay_gs_price=".($order_data['pay_gs_price']-$order_data['pay_shipp_price']).",
2308 goods_idx=".$order_data['goods_idx'].",
2309 order_no='".$order_data['order_no']."'";
2310 if(!$this->query($q)) {
2311 Log::write('Err',"addOrderAG 실패 - ".$q);
2312 }
2313 }
2314 return false;
2315 }
2316 }
2317
2318 function addOrderAGAC($order_no) {
2319 $order_data = $this->fetchOne("select mb_seq,seller_id,pay_gs_price,pay_shipp_price,goods_idx from sf_order where order_no='".$order_no."'");
2320 if($order_data['mb_seq']) { // 회원 구매인 경우 에이전시 체크하여 에이전시 주문 테이블에 넣어줘야 함
2321 if($order_data['seller_id']) {
2322 $cond = "seller_id='".$order_data['seller_id']."'";
2323 } else {
2324 $cond = "mb_seq=".$order_data['mb_seq'];
2325 }
2326 $chk = $this->fetchOne("select seller_recom,seller_recom2 from sf_member where $cond");
2327 $recom = $chk['seller_recom2'] ? $chk['seller_recom2'] : $chk['seller_recom'];
2328 if($recom) {
2329 $chk2 = $this->fetchOne("select idx from sf_order_recom where order_no='".$order_no."'");
2330 if(!$chk2[idx]) {
2331 $q = "insert into sf_order_recom set seller_id='".$order_data[seller_id]."',
2332 recom_id='".$recom."',
2333 pay_gs_price=".($order_data[pay_gs_price]-$order_data[pay_shipp_price]).",
2334 goods_idx=".$order_data[goods_idx].",
2335 order_no='".$order_no."'";
2336 if(!$this->query($q)) {
2337 Log::write('Err',"addOrderAG 실패 - ".$q);
2338 }
2339 return false;
2340 }
2341 }
2342 }
2343 }
2344 # tpay resful api
2345 function payment_request_card($arrData) {
2346 $arr_result = array();
2347 $vars = array();
2348 $card_info = $this->getCreditInfo();
2349 # 해외카드 (언어가 en으로 되어 있을때ㄷ로 간주) 예외처리 - 카드번호와 유효기간만 있으면 처리해줌
2350 if($_SESSION['lang']=='en') {
2351 $arrData['card_quota'] = "0"; // 해외카드인경우 할부개월을 지정해주지 않으면 이상하게 에러가 남
2352 $vars['api_key'] = $_ENV['payment_api_secret2'];
2353 $vars['mid'] = $_ENV['payment_api_mid2'];
2354 if($arrData['repayment'] && isSession() && $card_info['c_no'] && $card_info['yymm']) { // 저장카드로 결재일때
2355 $arrData['card_number'] = $card_info['c_no'];
2356 $expire = substr($card_info['yymm'], 2,2).substr($card_info['yymm'], 0,2);
2357 } else { //첫결재일때
2358 $expire = substr($arrData['expiry'], 2,2).substr($arrData['expiry'], 0,2);
2359 }
2360 } else {
2361 if($arrData['repayment'] && isSession() && $card_info['c_no'] && $card_info['yymm']) { // 저장카드로 결재일때
2362 $vars['api_key'] = $_ENV['payment_api_secret'];
2363 $vars['mid'] = $_ENV['payment_api_mid'];
2364 $arrData['card_number'] = $card_info['c_no'];
2365 $expire = substr($card_info['yymm'], 2,2).substr($card_info['yymm'], 0,2);
2366 } else { //첫결재일때
2367 $vars['api_key'] = $_ENV['payment_api_secret2'];
2368 $vars['mid'] = $_ENV['payment_api_mid2'];
2369 $vars['buyer_auth_num'] = $arrData['card_birth'];
2370 $vars['card_pwd'] = $arrData['card_pwd'];
2371 $expire = substr($arrData['expiry'], 2,2).substr($arrData['expiry'], 0,2);
2372 }
2373 }
2374
2375 $order_no = $arrData['order_no'] ? $arrData['order_no'] : $this->orderNo;
2376 $req_url = "https://webtx.tpay.co.kr/api/v1/payments";
2377 $vars['goods_nm'] = $arrData['name'];
2378 $vars['amt'] = $arrData['amount'];
2379 $vars['moid'] = $order_no;
2380 $vars['buyer_nm'] = $arrData['buyer_name'];
2381 $vars['buyer_email'] = $arrData['buyer_email'];
2382 $vars['buyer_tel'] = $arrData['buyer_tel'];
2383 $vars['buyer_addr'] = $arrData['buyer_addr'];
2384 $vars['card_quota'] = $arrData['card_quota'];
2385 $vars['card_num'] = $arrData['card_number'];
2386 $vars['card_exp'] = $expire; //유효기간(년+월) (ex:YYMM)
2387
2388 $ch = curl_init();
2389 curl_setopt($ch, CURLOPT_URL, $req_url);
2390 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
2391 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
2392 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
2393 curl_setopt ($ch, CURLOPT_POST, 1);
2394 curl_setopt ($ch, CURLOPT_POSTFIELDS, http_build_query($vars));
2395 $response = curl_exec($ch);
2396 $errmsg = curl_error($ch);
2397 $cInfo = curl_getinfo($ch);
2398 curl_close($ch);
2399 $arr_res = json_decode($response);
2400 if($arr_res->result_cd=="3001") {
2401 # 결제 성공시 카드정보 저장
2402 $this->setCreditInfo($arrData['card_number'],$arrData['expiry']);
2403 $arr_result[result] = '1';
2404 return $arr_result;
2405 } else {
2406 Log::write_pay($order_no,"api 결제시도 실패 | code : ".$arr_res->result_cd." | message : ".$arr_res->result_msg);
2407 sendSmsDev("api 결제시도 실패 | code : ".$arr_res->result_cd." | message : ".$arr_res->result_msg);
2408 if($arr_res->result_msg) {
2409 $arr_result[result] = 'false';
2410 $arr_result[resultMsg] = $arr_res->result_msg;
2411 return $arr_result;
2412 } else {
2413 $arr_result[result] = 'false';
2414 $arr_result[resultMsg] = 'unknownErr';
2415 return $arr_result;
2416 }
2417 }
2418 return false;
2419 }
2420
2421
2422
2423
2424 # tpay resful api - 빌링키결제 (나이스페이전용))
2425 function payment_request_card_billing($arrData) {
2426 $arr_result = array();
2427 $vars = array();
2428 $card_info = $this->getCreditInfo();
2429 //Log::write('debug',$arrData['repayment'].'-'.$card_info['billkey']);
2430 if($arrData['repayment'] && isSession() && $card_info['c_no'] && $card_info['yymm'] && $card_info['billkey']) { // 저장카드로 결재일때
2431 $billkey = $card_info['billkey'];
2432 } else if(!$arrData['repayment'] && $arrData['card_number'] && $arrData['expiry'] && $arrData['card_birth'] && $arrData['card_pwd']) { // 첫결제일때 billkey 얻기
2433 $billkey = $this->request_billkey($arrData);
2434 if($billkey['result']==true && $billkey['billkey']) {
2435 $billkey = $billkey['billkey'];
2436 $this->setCreditInfo($arrData['card_number'],$arrData['expiry'],$billkey); // 빌링키 승인시 카드정보 저장
2437 } else {
2438 $arr_result['result'] = 'false';
2439 $arr_result['resultMsg'] = $billkey['result_msg'];
2440 return $arr_result;
2441 }
2442 }
2443
2444 /***************************************
2445 * 2. NicepayLite 클래스의 인스턴스 생성 *
2446 ***************************************/
2447 $nicepay = new NicepayLite;
2448
2449 // 로그 경로를 설정하여 주십시요.
2450 $nicepay->m_NicepayHome = $_SERVER['DOCUMENT_ROOT']."/log_nicepay";
2451
2452 $nicepay->m_Amt = $arrData['amount'];
2453 $nicepay->m_Moid = $arrData['order_no'];
2454 $nicepay->m_MID = $_ENV['payment_mid'];
2455 $nicepay->m_MallIP = $MallIP;
2456 $nicepay->m_EncryptedData = $EncryptedData;
2457 $nicepay->m_PayMethod = 'BILL';
2458 $nicepay->m_BillKey = $billkey;
2459 $nicepay->m_BuyerName = iconv('UTF-8','EUC-KR',$arrData['buyer_name']);
2460 $nicepay->m_GoodsName = iconv('UTF-8','EUC-KR',$arrData['name']);
2461 $nicepay->m_CardQuota = $arrData['card_quota'];
2462 $nicepay->m_ssl = "true";
2463 $nicepay->m_ActionType = "PYO";
2464 // 상점키를 설정한다.
2465 $nicepay->m_LicenseKey = $_ENV['payment_key'];
2466
2467
2468 $nicepay->m_NetCancelAmt = $arrData['amount']; //결제 금액에 맞게 수정
2469 $nicepay->m_NetCancelPW = "0623"; // 취소 패스워드 설정
2470
2471 $nicepay->m_debug = "DEBUG";
2472
2473 // PG에 접속하여 승인 처리를 진행.
2474 $nicepay->startAction();
2475
2476 if($nicepay->m_ResultData["ResultCode"]=='3001') {
2477 $arr_result[result] = '1';
2478 return $arr_result;
2479 } else {
2480 $arr_result[result] = 'false';
2481 $arr_result[resultMsg] = $arr_res->result_msg;
2482 if(!trim($arr_result[resultMsg])) {
2483 $arr_result[resultMsg] = '주문이 실패하였습니다. 관리자에게 문의해 주세요';
2484 }
2485 Log::write_pay($arrData[order_no],"api 결제시도 실패 | code : ".$nicepay->m_ResultData["ResultCode"]." | message : ".iconv('EUC-KR','UTF-8',$nicepay->m_ResultData["ResultMsg"]));
2486 sendSmsDev("api 결제시도 실패 | code : ".$nicepay->m_ResultData["ResultCode"]." | message : ".$nicepay->m_ResultData["ResultMsg"]);
2487 return $arr_result;
2488 }
2489 return false;
2490 }
2491
2492 # nicepay get billkey
2493 function request_billkey($arrData) {
2494 $result = array();
2495 /***************************************
2496 * 2. NicepayLite 클래스의 인스턴스 생성 *
2497 ***************************************/
2498 $nicepay = new NicepayLite;
2499 // 로그 경로를 설정하여 주십시요.
2500 $nicepay->m_NicepayHome = $_SERVER['DOCUMENT_ROOT']."/log_nicepay";
2501
2502 $nicepay->m_CardNo = $arrData['card_number'];
2503 $nicepay->m_ExpYear = substr($arrData['expiry'], 2,2);
2504 $nicepay->m_ExpMonth = substr($arrData['expiry'], 0,2);
2505 $nicepay->m_IDNo = $arrData['card_birth'];
2506 $nicepay->m_CardPw = $arrData['card_pwd'];
2507 $nicepay->GoodsCl = '1'; //실물
2508
2509
2510 $nicepay->m_MID = $_ENV['payment_mid'];
2511 $nicepay->m_MallIP = $MallIP;
2512 $nicepay->m_PayMethod = 'BILLKEY';
2513 $nicepay->m_ssl = "true";
2514 $nicepay->m_ActionType = "PYO";
2515 $nicepay->m_LicenseKey = $_ENV['payment_key'];
2516
2517 // PG에 접속하여 승인 처리를 진행.
2518 $nicepay->startAction();
2519
2520 if($nicepay->m_ResultData["ResultCode"]=='F100') {
2521 $result['result'] = true;
2522 $result['billkey'] = $nicepay->m_ResultData["BID"];
2523 } else {
2524 $result['result'] = false;
2525 $result['result_msg'] = $nicepay->m_ResultData["ResultMsg"];
2526 Log::write_pay($arrData['order_no'],"빌링키 요청 실패 | code : ".$nicepay->m_ResultData["ResultCode"]." | message : ".iconv('EUC-KR','UTF8',$nicepay->m_ResultData["ResultMsg"]));
2527 }
2528 return $result;
2529 /*echo '결과코드 : '.$nicepay->m_ResultData["ResultCode"]."<Br>";
2530 echo '결과메세지 : '.$nicepay->m_ResultData["ResultMsg"]."<br>";
2531 echo '빌키 : '.$nicepay->m_ResultData["BID"]."<br>";
2532 echo '카드 종류: '.$nicepay->m_ResultData["CardName"]."<br>";
2533 echo '거래 시간 : '.$nicepay->m_ResultData["AuthDate"]."<br>";
2534 echo '신용(0)/체크(1) : '.$nicepay->m_ResultData["CardCl"]."<br>";*/
2535 }
2536
2537 /** 장바구니 주문 입력 **/
2538 function addOrderCart($arrData) {
2539 $addr = $this->getDeliveryInfo();
2540 $listCart = $this->getCartList($arrData['mb_seq']);
2541 $this->objSF = new SF;
2542 $this->setOrderNo();
2543 for($i=0;$i<count($listCart);$i++) {
2544 $gInfo = $this->objSF->getGoodsInfo($listCart[$i][goods_idx]);
2545 $tsp = explode('|',$listCart[$i][opts]);
2546 $tsp2=explode("[**]",$gInfo[gs_opts]);
2547 $tShipp = 2500;
2548 if($listCart[$i][gs_deliver_free] == '1' && ($listCart[$i][tot_price] >= $listCart[$i][gs_deliver_free_price])) {
2549 $tShipp = 0;
2550 }
2551 $sumShipp+=$tShipp;
2552 $sumPrice+=$listCart[$i][tot_price];
2553
2554 //addDeliverInfo
2555 if(trim($arrData['name_'.$arrData['deliver']])) {
2556 $deliver_name = trim($arrData['name_'.$arrData['deliver']]);
2557 $this->addDeliverInfo('name_'.$arrData['deliver'],$deliver_name);
2558 } else {
2559 $deliver_name = trim($addr["name_".$arrData['deliver']]);
2560 }
2561
2562 if(trim($arrData['phone_'.$arrData['deliver']])) {
2563 $deliver_phone = trim($arrData['phone_'.$arrData['deliver']]);
2564 $this->addDeliverInfo('phone_'.$arrData['deliver'],$deliver_phone);
2565 } else {
2566 $deliver_phone = trim($addr["phone_".$arrData['deliver']]);
2567 }
2568
2569 if(trim($arrData['addr_'.$arrData['deliver']])) {
2570 $deliver_addr = trim($arrData['addr_'.$arrData['deliver']]);
2571 $this->addDeliverInfo('addr_'.$arrData['deliver'],$deliver_addr);
2572 } else {
2573 $deliver_addr = trim($addr["addr_".$arrData['deliver']]);
2574 }
2575
2576
2577 $q = "insert into sf_order set
2578 stats='1',
2579 mb_type='".$_SESSION['mb_type']."',
2580 mb_seq=".$arrData['mb_seq'].",
2581 pay_method='".$arrData['pay_method']."',
2582 goods_idx='".$listCart[$i]['goods_idx']."',
2583 order_no='".$this->orderNo."',
2584 quantity=".$listCart[$i]['quantity'].",
2585 opts='".$listCart[$i]['opts']."',
2586 account_name='".$arrData['ac_name']."',
2587 deliver_msg='".$arrData['deliver_msg']."',
2588 receiver_name='".$addr['name_'.$arrData['deliver']]."',
2589 receiver_phone='".$addr['phone_'.$arrData['deliver']]."',
2590 receiver_addr='".$addr['addr_'.$arrData['deliver']]."'";
2591 if($this->query($q)) {
2592 # 재고 삭감
2593 if(!$this->query("update sf_goods set gs_remain = gs_remain - ".$listCart[$i]['quantity']." where gs_idx=".$listCart[$i]['gs_idx']."")) {
2594 //Log::write('SQLErr','Remain minus false1 - '."update sf_goods set gs_remain = gs_remain - ".$arrData['opts_qt']." where gs_idx=".$arrData['gs_idx']."");
2595 }
2596 //return true;
2597 } else {
2598 Log::write('SQLErr','Order Insert False - '.$q);
2599 //return false;
2600 }
2601 }
2602 return true;
2603 }
2604 function setOrderNo() {
2605 $rand = explode(" ",microtime());
2606 $rand = explode(".",$rand[0]);
2607 $rand = substr($rand[1],-4);
2608 $str = $rand.date("ymd");
2609 $rand = "";
2610 for ($i = 0; $i < 4; $i++) {
2611 $rand .= mt_rand(1, 9);
2612 }
2613 $str .= $rand;
2614 $this->orderNo = $str;
2615 return $str;
2616 }
2617 function setGroupOrderNo() {
2618 $rand = explode(" ",microtime());
2619 $rand = explode(".",$rand[0]);
2620 $rand = substr($rand[1],-4);
2621 $str = $rand.date("ymd");
2622 $rand = "";
2623 for ($i = 0; $i < 4; $i++) {
2624 $rand .= mt_rand(1, 9);
2625 }
2626 $str .= $rand;
2627 $str = 'g'.$str;
2628 return $str;
2629 }
2630
2631 function getOrderInfo($type='1',$order_no = "") {
2632 $order_no = $order_no ? $order_no : $this->orderNo;
2633 if($order_no) {
2634 if($type=='1') {
2635 $res = $this->fetch1("select a.*,b.gs_is_cn,b.gs_name,b.gs_price,b.gs_image1,b.gs_deliver_free,gs_deliver_free_price as tot_price from sf_order a left join sf_goods b on a.goods_idx=b.gs_idx where a.order_no='".$order_no."' limit 1");
2636 } else if($type=='3') { // 장바구니 주문 목록 불러오기
2637 $res = $this->fetchs("select a.*,b.gs_is_cn,b.gs_name,b.gs_price,b.gs_image1,b.gs_deliver_free,gs_deliver_free_price as tot_price from sf_order a left join sf_goods b on a.goods_idx=b.gs_idx where a.order_no_group='".$order_no."'");
2638 } else {
2639 $res = $this->fetch1("select a.*,b.gs_is_cn,b.gs_name,b.gs_price,b.gs_image1,b.gs_deliver_free,gs_deliver_free_price as tot_price from sf_order a left join sf_goods b on a.goods_idx=b.gs_idx where a.idx=".$order_no." limit 1");
2640 }
2641 if($res['idx'] || $res[0]['idx']) {
2642 return $res;
2643 }
2644 }
2645 }
2646
2647 function setBlillKey($billKey,$mb_seq) {
2648 if($mb_seq) {
2649 $this->query("update sf_member set mb_billingkey='".$billKey."' where mb_seq=".$mb_seq);
2650 }
2651 }
2652
2653 function getBlillKey($mb_seq) {
2654 if($mb_seq) {
2655 $res = $this->fetch1("select mb_billingkey from sf_member where mb_seq=".$mb_seq);
2656 if(trim($res[mb_billingkey])) {
2657 return $res[mb_billingkey];
2658 } else {
2659 return "";
2660 }
2661 }
2662 }
2663
2664 // function getGoddsPrice($gid,$s_id='') {
2665 // $this->objSM = new SM;
2666
2667 // if($s_id) {
2668 // return $this->objSM->getSalePrice($gid,$s_id);
2669 // } else {
2670 // if(!$gid) {
2671 // return 0;
2672 // }
2673 // $res = $this->fetchOne("select gs_price,gs_price_factory from sf_goods where gs_idx=".$gid." limit 1");
2674
2675 // if($_SESSION['seller']) {
2676 // return $res['gs_price_factory'];
2677 // } else {
2678 // return $res['gs_price'];
2679 // }
2680 // }
2681 // }
2682 function getGoodsPrices($gid) {
2683 global $shop_info;
2684
2685 $this->objSF = new SF;
2686
2687 $opt_prices = array();
2688 $gid = $_SESSION[from_seller_gs_idx] ? $_SESSION[from_seller_gs_idx] : $gid;
2689 $res = $this->fetchOne("select gs_price,gs_price_factory,gs_price_margin,gs_price_origin,gs_opts_price,gs_opts_price_factory,gs_deliver_free,gs_deliver_free_price,gs_price_least,gs_price-gs_price_margin-gs_price_factory as d_margin from sf_goods where gs_idx=".$gid." limit 1");
2690 $gs_price_factory_origin = $res[gs_price_factory];
2691
2692
2693 # 수수료 우선순위 1 몰에대한 수수료가 존재할겨웅 해당 수수료만큼 공급가에 + (해당 수수료는 공급가에 대한 수수료)
2694 if($shop_info['shop_fee'] > 0) {
2695 $mall_fee = round(($res['gs_price_factory']+$res['gs_price_margin'])*$shop_info['shop_fee']);
2696 $res['gs_price_factory'] += $mall_fee;
2697 $res['d_margin'] = $res['gs_price']-$res['gs_price_factory']-$res['gs_price_margin'];
2698 }
2699
2700 # Ageny에 속한 셀러일경우 에이전시 마진을 공급가에 더해준다
2701 if($_SESSION['is_agency'] && $_SESSION['agency_id'] && $this->isFactoryBuy()) {
2702 $res['opt_agency_price'] = round($res['d_margin']*$this->getAgencyFee($_SESSION['agency_id']));
2703 $res['gs_price_factory'] += $res['opt_agency_price'];
2704 }
2705
2706 # 해당 상품을 본인/상위셀러가 등록 했는지
2707 $isMyGoods = false;
2708
2709
2710 # 벤더셀러가 본인이 등록한 제품을 본인이나 하위(벤더셀러이자 에이전시인경우) 셀러가 샘플 구매시엔 소마 수수료 받지 않음
2711 if(($_SESSION[seller_id] || $_SESSION[agency_id]) && $this->isFactoryBuy()){
2712 $shop_id = $_SESSION[agency_id] ? $_SESSION[agency_id] : $_SESSION[seller_id];
2713 $shopInfo = $this->getShopInfo($shop_id);
2714 $goodsInfo = $this->objSF->getGoodsInfo($gid);
2715 if($goodsInfo[shop_idx] == $shopInfo[shop_idx]){
2716 $isMyGoods = true;
2717 }
2718 }
2719
2720 # 소마 수수료 공급가에 +
2721 if($res[gs_price_margin]>0 && $isMyGoods == false){
2722 $res[gs_price_factory] += $res[gs_price_margin];
2723 }
2724
2725 # 마진율
2726 if($_SESSION['seller']) { // 내 판매가가 있는지
2727 $myprice = $this->getSalePrice($gid,$_SESSION['seller_id']);
2728 }
2729 if($res['gs_price'] > $res['gs_price_factory'] || $myprice > $res['gs_price_factory']) {
2730 if($myprice > 0) {
2731 $res['seller_margin'] = $myprice-$res['gs_price_factory'];
2732 $sale_per = round($res['seller_margin']/$myprice*100);
2733 } else {
2734 $res['seller_margin'] = $res['gs_price']-$res['gs_price_factory'];
2735 $sale_per = round($res['seller_margin']/$res['gs_price']*100);
2736 }
2737
2738 }
2739 $res['sale_per'] = $sale_per > 0 ? $sale_per : "0";
2740 # 옵션가
2741 $tsp = explode("[**]",$res['gs_opts_price']);
2742 $tsp_fp = explode("[**]",$res['gs_opts_price_factory']);
2743 for($i=0;$i<count($tsp);$i++) {
2744 $tsp2 = explode("|",$tsp[$i]);
2745 $tsp3 = explode(",",$tsp2[1]);
2746 $tsp_fp2 = explode("|",$tsp_fp[$i]);
2747 $tsp_fp3 = explode(",",$tsp_fp2[1]);
2748 for($j=0;$j<count($tsp3);$j++) {
2749 if($_SESSION['seller'] && $this->isFactoryBuy() && $_ENV['auth_factory_price']=='1') { // 셀러는 옵션 추가금액도 공급가로 지급
2750 $opt_prices[$i][$j] = $tsp_fp3[$j];
2751 } else {
2752 $opt_prices[$i][$j] = $tsp3[$j];
2753 }
2754 }
2755 }
2756 $res['opt_prices'] = $opt_prices;
2757 # 구매가 설정
2758 if($_SESSION[private_shop] && !$_SESSION[seller]) { // 개인상점에 접속한 일반회원
2759 $res[now_gs_price] = $this->getSalePrice($gid,$_SESSION[private_shop]);
2760 if($res[now_gs_price] <= 0) {
2761 $res[now_gs_price] = $res[gs_price];
2762 }
2763 } else if($_SESSION['seller'] && !$this->isFactoryBuy()) { // 샘플구매 권한이 없는 셀러
2764 $res['now_gs_price'] = $res['gs_price'];
2765 } else if($_SESSION['seller'] && $this->isFactoryBuy() && $_ENV['auth_factory_price']=='1') { // 샘플구매 권한이 있는 셀러. 공급가 보는 권한이 있어야 구매가가 공급가로 보임
2766 $res['now_gs_price'] = $res['gs_price_factory'];
2767 } else { // 미리보기인 경우 또는 기타인 경우는 기본 가격으로
2768 $res['now_gs_price'] = $res['gs_price'];
2769 }
2770 # 할인율
2771 if($res['gs_price_origin'] > $res['now_gs_price']) {
2772 $res['sale'] = round(($res['gs_price_origin']-$res['now_gs_price'])/$res['gs_price_origin']*100);
2773 }
2774
2775 return $res;
2776 }
2777
2778 function getOptPrices($arrOpt,$arrEA,$arrPrices) {
2779 $res = array();
2780 $res[totalPrice] = 0;
2781 $res[optPrice] = 0;
2782 $arr1 = explode('[**]',$arrOpt);
2783 $arr2 = explode('|',$arrEA);
2784 for($i = 0 ; $i<count($arr1);$i++) {
2785 $arr1_2 = explode('|',$arr1[$i]);
2786 $opt_price = 0;
2787 for($j = 0 ; $j<count($arr1_2);$j++) {
2788 $opt_price += $arrPrices[opt_prices][$j][$arr1_2[$j]];
2789 }
2790 $res[totalPrice] += ($arrPrices[now_gs_price]+$opt_price)*$arr2[$i];
2791 $res[optPrice] += $opt_price*$arrEA[$i];
2792 }
2793 return $res;
2794 }
2795
2796 function getGoodsOptArr($opt_txt,$opt_prices,$opt_prices_factory) {
2797 $arrOpts = array();
2798 $arr_opts = explode("[**]",$opt_txt);
2799 $arr_opts_prices = explode("[**]",$opt_prices);
2800 $arr_opts_prices_factory = explode("[**]",$opt_prices_factory);
2801 $c1 = count($arr_opts);
2802 for($i=0;$i<$c1;$i++) {
2803 $tsp_opts = explode("|",$arr_opts[$i]);
2804 $tsp_prices = explode("|",$arr_opts_prices[$i]);
2805 $tsp_prices_factory = explode("|",$arr_opts_prices_factory[$i]);
2806 $tsp_opts_values = explode(",",$tsp_opts[1]);
2807 $tsp_prices_values = explode(",",$tsp_prices[1]);
2808 $tsp_prices_factory_values = explode(",",$tsp_prices_factory[1]);
2809 $c2 = count($tsp_opts_values);
2810 $arrOpts[$i]['optNm'] = $arr_opts[0];
2811 for($j=0;$j<$c2;$j++) {
2812 $arrOpts[$i]['optValue'][$j] = stripslashes($tsp_opts_values[$j]);
2813 $arrOpts[$i]['optPrice'][$j] = stripslashes($tsp_prices_values[$j]);
2814 $arrOpts[$i]['optPriceFactory'][$j] = stripslashes($tsp_prices_factory_values[$j]);
2815 }
2816 }
2817 }
2818
2819 function setGoodsOptArr() {
2820
2821 }
2822
2823 function makeOptDP($opts,$optIdxs) {
2824 $tsp = explode("[**]",$opts);
2825 $dpStr = "";
2826 for($i=0;$i<count($tsp);$i++) {
2827 $tsp2 = explode("|",$tsp[$i]);
2828 $tsp3 = explode(",",$tsp2[1]);
2829 $dpStr .= $tsp2[1]." : ".$tsp3[$optIdxs[$i]];
2830 }
2831 return $dpStr;
2832 }
2833
2834 function updateOrderStats($st,$oid) {
2835 $payTime = date("Y-m-d G:i:s");
2836 $q = sprintf("update sf_order set stats='".$st."',paymentTime='%s' where order_no='%s'",$payTime,$oid);
2837 if($this->query($q)) {
2838 return true;
2839 } else {
2840 Log::write_pay($oid,"결제상태 업데이트 실패 $q");
2841 return false;
2842 }
2843 }
2844
2845 function updateStats($st) {
2846 $payTime = date("Y-m-d G:i:s");
2847 if(!$this->query("update sf_order set stats='$st',paymentTime='$payTime' where order_no='".$this->orderNo."' limit 1")) {
2848 Log::write('SQLErr','Order Stats Update False - '."update sf_order set stats='$st' where order_no='".$this->orderNo."' limit 1");
2849 return false;
2850 }
2851 return true;
2852 }
2853
2854 function getOrderList($mb_seq) {
2855 $q = "select a.*,b.gs_nation,b.gs_name,b.gs_price,b.gs_image1,b.gs_deliver_free,gs_deliver_free_price from sf_order a left join sf_goods b on a.goods_idx=b.gs_idx where mb_seq=".$mb_seq." order by a.idx desc";
2856 $res=$this->fetchs($q);
2857 return $res;
2858 }
2859
2860 function getOrderFromNoMember($arrData) {
2861 if($arrData['input_order_search_email']) {
2862 $q = "select a.*,b.gs_name,b.gs_price,b.gs_image1,b.gs_deliver_free,gs_deliver_free_price from sf_order
2863 a left join socialmarket.sf_goods b on a.goods_idx=b.gs_idx
2864 where (TRIM(receiver_email)='".trim($arrData['input_order_search_email'])."' and REPLACE(REPLACE(receiver_phone,' ',''),'-','')='".preg_replace("/[^0-9]*/s", "", $arrData['input_order_search_phone'])."')
2865 order by a.idx desc;";
2866 } else {
2867 $q = "select a.*,b.gs_name,b.gs_price,b.gs_image1,b.gs_deliver_free,gs_deliver_free_price from sf_order
2868 a left join socialmarket.sf_goods b on a.goods_idx=b.gs_idx
2869 where ((order_no='".trim($arrData[input_order_search_no])."' or order_no_group='".trim($arrData['input_order_search_no'])."') and REPLACE(REPLACE(receiver_phone,' ',''),'-','')='".preg_replace("/[^0-9]*/s", "", $arrData['input_order_search_phone2'])."')
2870 order by a.idx desc;";
2871 }
2872 $res=$this->fetchs($q);
2873 return $res;
2874 }
2875
2876 function getSaleList($mb_seq,$s_y = '',$s_m = '') {
2877 $cond = "";
2878 if($s_y) {
2879 $cond .= " and SUBSTRING_INDEX(a.orderTime,'-',1)='$s_y' ";
2880 }
2881 if($s_m) {
2882 $cond .= " and SUBSTRING_INDEX(SUBSTRING_INDEX(a.orderTime, '-', -2), '-', 1)='$s_m' ";
2883 }
2884 $q = "select a.*,b.gs_nation,b.gs_name,b.gs_price,b.gs_image1,b.gs_deliver_free,gs_deliver_free_price,a.pay_gs_price-a.pay_shipp_price as tot_price from sf_order a left join sf_goods b on a.goods_idx=b.gs_idx where a.seller_id='".$_SESSION[seller_id]."' $cond order by a.idx desc";
2885 $res=$this->fetchs($q);
2886 return $res;
2887 }
2888 function removeMyItem($gs_idx,$seller_id) {
2889 $chk = $this->getGoodsInfo($gs_idx,'2');
2890 if($chk[gs_idx]) {
2891 if($this->query("delete from sm_mysale where pr_idx=$chk[gs_idx] and shop_id='".$seller_id."'")) {
2892 return true;
2893 }
2894 }
2895 return false;
2896 }
2897
2898 function setSelfPrice($gs_idx,$price,$seller_id='') {
2899 $seller_id = $seller_id ? $seller_id : $_SESSION[seller_id];
2900 $arr_prices = $this->getGoodsPrices($gs_idx);
2901 $least = $arr_prices[gs_price_least] > 0 ? $arr_prices[gs_price_least] : $arr_prices[gs_price_factory];
2902 if($least <= $price) {
2903 if(!$this->isMySale($gs_idx)) {
2904 $this->addSaleLink($gs_idx);
2905 }
2906 $res = $this->query(sprintf("update sm_mysale set price=%d where pr_idx=%d and shop_id='%s'"
2907 ,$this->escape($price)
2908 ,$this->escape($gs_idx)
2909 ,$this->escape($seller_id)));
2910 if($res) {
2911 return true;
2912 }
2913 }
2914 return false;
2915 }
2916
2917 function isMySale($gs_idx,$seller_id='') {
2918 $seller_id = $seller_id ? $seller_id : $_SESSION[seller_id];
2919 $chk = $this->fetchOne("select idx from sm_mysale where pr_idx=$gs_idx and shop_id='".$seller_id."'");
2920 if($chk[idx]) {
2921 return $chk[idx];
2922 } else {
2923 return false;
2924 }
2925 }
2926
2927 function getSaleListAG($ag_id,$s_y = '',$s_m = '') {
2928 $cond = "";
2929 if($s_y) {
2930 $cond .= " and SUBSTRING_INDEX(c.orderTime,'-',1)='$s_y' ";
2931 }
2932 if($s_m) {
2933 $cond .= " and SUBSTRING_INDEX(SUBSTRING_INDEX(c.orderTime, '-', -2), '-', 1)='$s_m' ";
2934 }
2935 $q = "select a.*,c.*,b.* from sf_order_recom a
2936 left join sf_goods b on a.goods_idx=b.gs_idx
2937 left join sf_order c on a.order_no=c.order_no
2938 where a.recom_id='".$ag_id."' $cond group by a.idx order by a.idx desc";
2939 $res=$this->fetchs($q);
2940 return $res;
2941 }
2942
2943 ### @ Add Sale Link
2944 function addSaleLink($pid,$seller_id='') {
2945 $seller_id = $seller_id ? $seller_id : $_SESSION[seller_id];
2946 if($this->chkIsSellerGoods($pid)==true) {
2947 $seq = $this->getNextSeq();
2948 $q = sprintf("insert into sm_mysale set pr_idx=%d,seq=%d,shop_id='%s'"
2949 ,$this->escape($pid)
2950 ,$this->escape($seq)
2951 ,$this->escape($seller_id));
2952
2953 if($this->query($q)) {
2954 return $seq;
2955 //return true;
2956 } else {
2957 return false;
2958 }
2959 } else {
2960 return false;
2961 }
2962 }
2963
2964 ### @ 판매가능 셀러 지정 상품인지
2965 function chkIsSellerGoods($pid) {
2966 $seller_id = "";
2967 if($_SESSION[seller_id]) $seller_id = $_SESSION[seller_id];
2968 else if($_SESSION[private_shop]) $seller_id = $_SESSION[private_shop];
2969
2970 $chk = $this->fetchOne("select gs_is_sellers from sf_goods where gs_idx=".$this->escape($pid));
2971
2972 if(trim($chk[gs_is_sellers])) {
2973 $ex = explode(',',$chk[gs_is_sellers]);
2974 for($i=0;$i<count($ex);$i++) {
2975 if(trim($ex[$i])==$seller_id) {
2976 return true;
2977 break;
2978 }
2979 }
2980 return false;
2981 } else {
2982 return true;
2983 }
2984 }
2985
2986 function getNextSeq($seller_id = '') {
2987 $seller_id = $seller_id ? $seller_id : $_SESSION[seller_id];
2988 $q = sprintf("select seq from sm_mysale where shop_id='%s' order by seq desc",$seller_id);
2989 $res = $this->fetchOne($q);
2990 if($res['seq']) {
2991 return $res['seq']+1;
2992 } else {
2993 return 1;
2994 }
2995 }
2996
2997
2998 /**
2999 @ 판매링크얻기
3000 **/
3001 function getSaleLink($pid) {
3002 $res = $this->fetchOne(sprintf("select seq from sm_mysale where pr_idx=%d and shop_id='%s'"
3003 ,$this->escape($pid)
3004 ,$this->escape($_SESSION[seller_id])));
3005 if(!$res['seq']) {
3006 return "";
3007 } else {
3008 return $_ENV['site_url'].'/'.$_SESSION[seller_id].'/'.$res['seq'];
3009 }
3010 }
3011
3012 /**
3013 @ 판매가격 불러오기
3014 **/
3015 function getSalePrice($gs_idx,$seller_id="") {
3016 $seller_id = $seller_id ? $seller_id : $_SESSION[seller_id];
3017 $res = $this->fetchOne(sprintf("select price from sm_mysale where pr_idx=%d and shop_id='%s'"
3018 ,$this->escape($gs_idx)
3019 ,$this->escape($seller_id)));
3020 if(!$res['price']) {
3021 return "0";
3022 } else {
3023 // die($res['price']);
3024 return $res['price'];
3025 }
3026 return false;
3027 }
3028
3029 ### @ 태그바이 통합 회원 체크
3030 function chkUnionAccount($user_email,$pwd) {
3031 if(!$user_email || !$pwd) {
3032 return false;
3033 }
3034 switch($_SERVER['HTTP_HOST']) {
3035 case 'dev.socialmarket.kr' :
3036 $req_url = 'http://sob.tagby.kr/api/';
3037 break;
3038 case 'www.socialmarket.kr' :
3039 $req_url = 'https://www.tagby.kr/api/';
3040 break;
3041 default :
3042 $req_url = 'https://www.tagby.kr/api/';
3043 break;
3044 }
3045
3046 $postData = array('api_key'=>'*6F5F067D8252500A437E8AC7AE85471788A7CAD2'
3047 ,'req_cd'=>'add_user'
3048 ,'user_pwd' => $pwd
3049 ,'user_email' => $user_email);
3050
3051
3052
3053 $curlObj = curl_init();
3054 curl_setopt($curlObj, CURLOPT_URL, $req_url);
3055 curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);
3056 curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0);
3057 curl_setopt($curlObj, CURLOPT_HEADER, 0);
3058 curl_setopt($curlObj, CURLOPT_POST, 1);
3059 curl_setopt($curlObj, CURLOPT_POSTFIELDS, $postData);
3060 $response = curl_exec($curlObj);
3061 if(trim($response)!='success') {
3062 return false;
3063 } else {
3064 return true;
3065 }
3066 }
3067
3068 function getCartList($mb_seq) {
3069 if(!is_numeric($mb_seq)) {
3070 $this->objSF = new SF;
3071 $uData = $this->objSF->getUserInfo($mb_seq,"");
3072 if($uData[mb_seq]) $mb_seq = $uData[mb_seq];
3073 }
3074 if(!$mb_seq) return false;
3075 # 판매기간 지났거나 재고가 없 장바구니 리스트는 삭제
3076 /*$q = "select a.idx,b.gs_startdate,b.gs_enddate,b.gs_remain from sf_cart a left join sf_goods b on a.goods_idx=b.gs_idx where a.mb_type='".$_SESSION[mb_type]."' and mb_seq=".$mb_seq." order by a.idx desc";
3077 $res=$this->fetchs($q);
3078 for($i = 0;$i < count($res);$i++) {
3079 if($res[$i][gs_startdate]>date("Y-m-d") || $res[$i][gs_enddate]<date("Y-m-d") || $res[$i][gs_remain] <= 0) {
3080 $this->query("delete from sf_cart where idx=".$res[$i][idx]);
3081 }
3082 }*/
3083
3084 if($_SESSION['seller']) {
3085 $q = "select a.*,b.gs_stats,b.gs_remain,b.gs_brand,b.gs_name,b.gs_price,b.gs_image1,b.gs_deliver_free,gs_deliver_free_price from sf_cart a left join sf_goods b on a.goods_idx=b.gs_idx where mb_seq=".$mb_seq." order by a.idx desc";
3086 } else {
3087 $q = "select a.*,b.gs_stats,b.gs_remain,b.gs_brand,b.gs_name,b.gs_price,b.gs_image1,b.gs_deliver_free,gs_deliver_free_price from sf_cart a left join sf_goods b on a.goods_idx=b.gs_idx where mb_seq=".$mb_seq." order by a.idx desc";
3088 }
3089
3090
3091 $res=$this->fetchs($q);
3092 return $res;
3093 }
3094
3095 function getOrderPossibleCartList($mb_seq){
3096 if(!is_numeric($mb_seq)) {
3097 $this->objSF = new SF;
3098 $uData = $this->objSF->getUserInfo($mb_seq,"");
3099 if($uData[mb_seq]) $mb_seq = $uData[mb_seq];
3100 }
3101 if(!$mb_seq) return false;
3102
3103 $q = "select a.*,b.gs_weight,b.gs_is_cn,b.gs_idx,b.gs_remain,b.gs_brand,b.gs_name,b.gs_price,b.gs_image1,b.gs_deliver_free,gs_deliver_free_price from sf_cart a left join sf_goods b on a.goods_idx=b.gs_idx where a.mb_type='".$_SESSION[mb_type]."' and mb_seq=".$mb_seq." and b.gs_remain > 0 and b.gs_stats = '1' order by a.idx desc";
3104
3105 $res=$this->fetchs($q);
3106 return $res;
3107 }
3108
3109 function getCartProduct($cart_id) {
3110 $q = "select a.*,b.gs_idx,b.gs_brand,b.gs_name,b.gs_price,b.gs_image1,b.gs_deliver_free,b.gs_deliver_free_price,(b.gs_price*a.quantity) as tot_price from sf_cart a left join sf_goods b on a.goods_idx=b.gs_idx where a.idx=".$cart_id." group by a.idx limit 1";
3111 $res=$this->fetchOne($q);
3112 return $res;
3113 }
3114
3115 function getStatsStr($index) {
3116 global $trans;
3117 return $trans['orderst'.$index];
3118 // switch($index) {
3119 // case "1" : return "결제[입금확인]중"; break;
3120 // case "2" : return "결제완료[상품준비]"; break;
3121 // case "3" : return "배송중"; break;
3122 // case "4" : return "배송완료"; break;
3123 // case "5" : return "환불중"; break;
3124 // case "6" : return "환불완료"; break;
3125 // }
3126 }
3127 function getCntNewer($chkDate) {
3128 $chk = $this->fetchOne("select count(gs_idx) as tcnt from sf_goods where gs_stats='1' and gs_startdate <= '".date('Y-m-d')."' and gs_enddate >= '".date('Y-m-d')."' and gs_remain > 0 and left(gs_regDate,10)>'".$chkDate."'");
3129 return $chk[tcnt] > 0 ? $chk[tcnt] : "0";
3130 }
3131
3132 function isPayed($order_no,$mb_seq) {
3133 if(!$mb_seq || !$order_no) {
3134 return false;
3135 }
3136 $rs = $this->fetch1("select idx from sf_order where order_no='".$order_no."' and (stats='2' or stats='3' or stats='4') and mb_seq=".$mb_seq);
3137 return $rs['idx'] ? true : false;
3138 }
3139
3140 function isPointed($order_no,$mb_seq) {
3141 if(!$mb_seq || !$order_no) {
3142 return false;
3143 }
3144 $rs = $this->fetch1("select idx from sf_user_point_stack where order_no='".$order_no."' and mb_seq=".$mb_seq);
3145 return $rs['idx'] ? true : false;
3146 }
3147
3148 function getSellerPoint($seller_id) {
3149 $rs = $this->fetch1("select seller_point from sf_member where seller_id='".$seller_id."'");
3150 return $rs[seller_point] > 0 ? $rs[seller_point] : "0";
3151 }
3152
3153 function isSellerOrder($seller_id,$order_no) {
3154 if(!$seller_id || !$order_no) {
3155 return false;
3156 }
3157 $rs = $this->fetchOne("select idx from sf_order where seller_id='".$seller_id."' and order_no='".$order_no."'");
3158 return $rs[idx] ? true : false;
3159 }
3160
3161 function calcPoint($order_no,$seller_id,$goods_idx=0,$ea=0) {
3162 $per = $this->getSellerPoint($seller_id);
3163 if($goods_idx>0 && $ea>0) {
3164 $gs_info = $this->getGoodsInfo($goods_idx);
3165
3166 } else {
3167 $margin = $this->getSellerPayFromOrder($order_no,$seller_id);
3168 if($margin > 0 && $per > 0 && is_numeric($margin) && is_numeric($per)) {
3169 return round($margin*$per/100);
3170 }
3171 }
3172
3173 return 0;
3174 }
3175 function calcOptFactoryPrice($gs_idx,$optTxt) {
3176 $gs_info = $this->fetch1('select gs_opts,gs_opts_price_factory from sf_goods where gs_idx='.$gs_idx);
3177 $arrOptInfos = array();
3178 $arrOptFactory = array();
3179 $arrOrderOptNm = array();
3180 $arrOrderOptEa = array();
3181 $addOptFactoryPrice = 0;
3182 $goodsOptTxt = $gs_info['gs_opts'];
3183 $factoryPrices = $gs_info['gs_opts_price_factory'];
3184 $ex1 = explode('[**]',$goodsOptTxt);
3185 $ex_p = explode('[**]',$factoryPrices);
3186 $ex_o = explode('<br>',$optTxt);
3187 $ct = count($ex1);
3188 for($i=0; $i<$ct;$i++) {
3189 $ex2 = explode('|',$ex1[$i]);
3190 $ex3 = explode(',',$ex2[1]);
3191 $ex_p2 = explode('|',$ex_p[$i]);
3192 $ex_p3 = explode(',',$ex_p2[1]);
3193 $ct2 = count($ex3);
3194 for($j=0;$j<$ct2;$j++) {
3195 $arrOptInfos[$i][$j] = $ex3[$j];
3196 $arrOptFactory[$i][$j] = $ex_p3[$j];
3197 }
3198 }
3199 for($i=0; $i<count($ex_o);$i++) {
3200 $ex_o2 = explode('선택'.($i+1).'-',$ex_o[$i]);
3201 $ex_o3 = explode('/',$ex_o2[1]);
3202 //debug($ex_o3);
3203 for($j=0;$j<count($ex_o3);$j++) {
3204 $ex_o4 = explode(':',$ex_o3[$j]);
3205 if($j==0) {
3206 $ex_tmp = explode(':',$ex_o3[count($ex_o3)-1]);
3207 $tmpEa = $ex_tmp[1];
3208 // echo "수량 - $tmpEa <br>";
3209 }
3210 $arrOrderOptNm[$i][$j] = $ex_o4[1];
3211 for($k=0;$k<count($arrOptInfos[$j]);$k++) {
3212 if($arrOptInfos[$j][$k]==$arrOrderOptNm[$i][$j]) {
3213 if($arrOptFactory[$j][$k]>0) {
3214 $addOptFactoryPrice += $arrOptFactory[$j][$k]*$tmpEa;
3215 // echo $arrOptInfos[$j][$k]." - 옵션공급가".($arrOptFactory[$j][$k]*$tmpEa)."<Br>";
3216 }
3217 }
3218 }
3219 }
3220 }
3221 return $addOptFactoryPrice>0? $addOptFactoryPrice : 0;
3222 }
3223
3224 ## 포인트 관련 ##
3225 //function addPoint($mb_seq,$order_no,$seller_id,$point) {
3226 function addPoint($order_no) {
3227 $order_info = $this->getOrderInfo('1',$order_no);
3228 $mb_seq = $order_info[mb_seq];
3229 $seller_id = $order_info[seller_id];
3230 # 검증
3231 if(!$mb_seq || !$order_no || !$seller_id) {
3232 return false;
3233 }
3234 if($this->isPayed($order_no,$mb_seq)==true && $this->isPointed($order_no,$mb_seq)==false && $this->getSellerPoint($seller_id) > 0) {
3235 $addPoint = $this->calcPoint($order_no,$seller_id);
3236 // Log::write('debug',"2 $addPoint");
3237 if($addPoint > 0) {
3238 // Log::write('debug','cond ok');
3239 $chk = $this->fetch1("select idx from sf_user_point where mb_seq=$mb_seq and seller_id='".$seller_id."'");
3240 if(!$chk[idx]) {
3241 $m_q = "insert into sf_user_point set mb_seq=$mb_seq,seller_id='".$seller_id."',point=$addPoint;";
3242 } else {
3243 $m_q = "update sf_user_point set point=point+$addPoint where mb_seq=$mb_seq and seller_id='".$seller_id."';";
3244 }
3245 $m_q .= "insert into sf_user_point_stack set mb_seq=$mb_seq,order_no='".$order_no."',point=$addPoint;";
3246 if(!$this->multi_query($m_q)) {
3247 Log::write('pointErr',$m_q);
3248 return false;
3249 }
3250 }
3251 } else {
3252 return false;
3253 }
3254 }
3255
3256 # 수정해야함 복사만 해놓음
3257 function addPointBox($order_no) {
3258 $order_info = $this->getOrderInfo('1',$order_no);
3259 $mb_seq = $order_info['mb_seq'];
3260 $seller_id = $order_info['seller_id'];
3261 # 검증
3262 if(!$mb_seq || !$order_no || !$seller_id) {
3263 return false;
3264 }
3265 if($this->isPayed($order_no,$mb_seq)==true && $this->isPointed($order_no,$mb_seq)==false && $this->getSellerPoint($seller_id) > 0) {
3266 $addPoint = $this->calcPoint($order_no,$seller_id);
3267 // Log::write('debug',"2 $addPoint");
3268 if($addPoint > 0) {
3269 // Log::write('debug','cond ok');
3270 $chk = $this->fetch1("select idx from sf_user_point where mb_seq=$mb_seq and seller_id='".$seller_id."'");
3271 if(!$chk[idx]) {
3272 $m_q = "insert into sf_user_point set mb_seq=$mb_seq,seller_id='".$seller_id."',point=$addPoint;";
3273 } else {
3274 $m_q = "update sf_user_point set point=point+$addPoint where mb_seq=$mb_seq and seller_id='".$seller_id."';";
3275 }
3276 $m_q .= "insert into sf_user_point_stack set mb_seq=$mb_seq,order_no='".$order_no."',point=$addPoint;";
3277 if(!$this->multi_query($m_q)) {
3278 Log::write('pointErr',$m_q);
3279 return false;
3280 }
3281 }
3282 } else {
3283 return false;
3284 }
3285 }
3286
3287 # 적립포인트 삭제
3288 function removePoint($order_no) {
3289 $chk = $this->fetch1("select idx,point,mb_seq from sf_user_point_stack where order_no='".$order_no."'");
3290 $chk2 = $this->fetch1("select seller_id from sf_order where order_no='".$order_no."' limit 1");
3291 $chk['seller_id'] = $chk2['seller_id'];
3292 if($chk['idx'] && $chk['seller_id']) { // 포인트 적립은 개인상점(셀러아이디가 있는) 에서만 일어나므로 셀러아이디 있을시만 삭제한다
3293 $remain = $this->fetch1("select point,seller_id from sf_user_point where mb_seq=".$chk[mb_seq]." and seller_id='".$chk['seller_id']."'");
3294 if($remain['point'] >= $chk['point']) {
3295 $m_q = "update sf_user_point set point=point-".$chk['point']." where mb_seq=".$chk[mb_seq]." and seller_id='".$chk['seller_id']."';";
3296 $m_q .= "delete from sf_user_point_stack where order_no='".$order_no."';";
3297 if(!$this->multi_query($m_q)) {
3298 Log::write('pointErr',$m_q);
3299 return false;
3300 }
3301 return true;
3302 } else {
3303 Log::write('BadPointUse',"취소되어야할 적립포인트가 사용됨 - $order_no");
3304 return false;
3305 }
3306 }
3307 }
3308 # 사용 포인트 환불
3309 function refundPoint($order_no) {
3310 $chk = $this->getOrderInfo('1',$order_no);
3311 if($chk['idx'] && $chk['mb_seq'] && $chk['pay_point'] > 0 && !$chk['refund_point_flag']) {
3312 $cond = "";
3313 if($chk['seller_id']) {
3314 $cond = " and seller_id='".$chk['seller_id']."'";
3315 }
3316 $m_q = "update sf_order set refund_point_flag='1' where idx=".$chk['idx'].";";
3317 $m_q .= "update sf_user_point set point=point+".$chk['pay_point']." where mb_seq=".$chk['mb_seq']." $cond;";
3318 if(!$this->multi_query($m_q)) {
3319 Log::write('pointRefundErr',$m_q);
3320 return false;
3321 }
3322 }
3323 }
3324
3325 function signupPoint($mb_seq,$mb_type) {
3326 if(!$mb_seq || !$mb_type) {
3327 return false;
3328 }
3329 $point = 500;
3330 $chk = $this->fetchOne("select idx from sf_user_point where mb_seq=".$mb_seq." and mb_type='".$mb_type."'");
3331 if(!$chk[idx]) {
3332 if(!$this->query("insert into sf_user_point set mb_seq=".$mb_seq.",mb_type='".$mb_type."'")) {
3333 Log::write('pointErr',"insert into sf_user_point set mb_seq=".$mb_seq.",mb_type='".$mb_type."'");
3334 return false;
3335 }
3336 if(!$this->query("update sf_user_point set point=point+".$point." where mb_seq=".$mb_seq." and mb_type='".$mb_type."'")) {
3337 Log::write('pointErr',"update sf_user_point set point=point+".$point." where mb_seq=".$mb_seq." and mb_type='".$mb_type."'");
3338 return false;
3339 }
3340 $this->query("insert into sf_user_point_stack set mb_seq=".$mb_seq.",mb_type='".$mb_type."',pt_type='signup',point=".$point);
3341 }
3342 return false;
3343 }
3344
3345 function usePoint($mb_seq,$seller_id,$point) {
3346 $user_point = $this->getPoint($mb_seq,$seller_id);
3347 if($point <= $user_point) {
3348 $chk = $this->getUserInfo($mb_seq,'');
3349 if($chk[seller]=='y') {
3350 $q = "update sf_user_point set sf_user_point.point = sf_user_point.point - $point where mb_seq=".$mb_seq;
3351 } else {
3352 $q = "update sf_user_point set sf_user_point.point = sf_user_point.point - $point where mb_seq=".$mb_seq." and seller_id='".$seller_id."'";
3353 }
3354 if(!$this->query($q)) {
3355 Log::write("ptErr","포인트사용 실패 - $mb_seq - $seller_id - $q");
3356 return false;
3357 }
3358 }
3359 return true;
3360 }
3361
3362 function getPointFromGoods($goods_idx,$seller_id) {
3363 $point = 0;
3364 $margin = $this->getSellerMargin($goods_idx,$seller_id);
3365 if($margin > 0) {
3366 $seller_point_per = $this->getSellerPoint($seller_id);
3367 if($seller_point_per > 0) {
3368 $point = round($margin*$seller_point_per/100);
3369 }
3370 }
3371 return $point;
3372 }
3373 function getPoint($mb_seq,$seller_id) {
3374 if(!$mb_seq) {
3375 return "0";
3376 }
3377 $uData = $this->getUserInfo($mb_seq,"");
3378 $cond = "";
3379 if($uData[seller]!='y') { // 셀러가 아니면 개인상점 적립포인트조회
3380 if(!$mb_seq || !$seller_id) {
3381 return "0";
3382 }
3383 $cond = "and seller_id='".$seller_id."'";
3384 } else {
3385 $cond = "and seller_id=''"; // 셀러면 개인상점 적립포인트를 조회하면 안됨
3386 }
3387 $tot = $this->fetch1("select point from sf_user_point where mb_seq=".$mb_seq." $cond limit 1");
3388 // echo "select point from sf_user_point where mb_seq=".$mb_seq." $cond limit 1";
3389 if(!$tot[point]) { return "0"; }
3390 return $tot[point];
3391 }
3392
3393 function getUserInfo($mb_id,$mb_type) {
3394 if(!$mb_id) {
3395 return "";
3396 }
3397 if(is_numeric($mb_id)) {
3398 if(strlen($mb_id) > 5) {
3399 $uData = $this->fetch1(sprintf("select mb_seq,mb_email,mb_type,mb_nick,seller from sf_member where mb_email='%s'",$this->escape($mb_id)));
3400 } else {
3401 $uData = $this->fetch1(sprintf("select mb_seq,mb_email,mb_type,mb_nick,seller from sf_member where mb_seq=%d",$this->escape($mb_id)));
3402 }
3403 } else {
3404 $uData = $this->fetch1(sprintf("select mb_seq,mb_email,mb_type,mb_nick,seller from sf_member where mb_email='%s'",$this->escape($mb_id)));
3405 }
3406 if(!$uData[mb_type]) $uData[mb_type] = 'st';
3407 if(!$uData[mb_seq]) return false;
3408 return $uData;
3409 }
3410
3411 # 아이돌챔프 어플내에서 소마 샾 호출시 자동 회원가입
3412 function getICUser($user_info) { // user_info : json param
3413 unset($_SESSION['mb_seq']);
3414 unset($_SESSION['mb_id']);
3415 unset($_SESSION['mb_nick']);
3416 unset($_SESSION['mb_type']);
3417 unset($_SESSION['seller']);
3418 unset($_SESSION['seller_id']);
3419 unset($_SESSION['seller_request']);
3420 unset($_SESSION['close_banner']);
3421 unset($_SESSION['is_shop']);
3422 unset($_SESSION['shop_idx']);
3423 unset($_SESSION['shop_auth']);
3424
3425 if($user_info->value->user_id && $user_info->value->session_id) {
3426 $chk = $this->getUserInfo($user_info->value->user_id,'ic');
3427 }
3428 if(!$chk['mb_seq']) {
3429 $q = sprintf("insert into sf_member set
3430 mb_email='%s',mb_pwd=password('%s'),mb_type='ic'",
3431 $user_info->value->user_id,md5($user_info->value->user_id),$_SERVER['REMOTE_ADDR']);
3432 if($this->query($q)) {
3433 $lres = $this->fetchOne("select LAST_INSERT_ID() as lid;");
3434 $lid = $lres['lid'];
3435 if($lid) {
3436 $_SESSION['mb_seq'] = $lid;
3437 }
3438 $_SESSION['mb_id'] = $user_info->value->user_id;
3439 $_SESSION['mb_type'] = 'ic';
3440 }
3441 } else {
3442 $_SESSION['mb_id'] = $user_info->value->user_id;
3443 $_SESSION['mb_seq'] = $chk['mb_seq'];
3444 $_SESSION['mb_type'] = 'ic';
3445 }
3446 move('/idolchamp');
3447 return false;
3448 }
3449
3450 function getPointType($mb_seq,$mb_type,$type) {
3451 if(!$mb_seq || !$mb_type) {
3452 return "0";
3453 }
3454 $or = "";
3455 if(is_array($type)) {
3456 for($i=0;$i<count($type);$i++) {
3457 $i==0 ? $or .= "pt_type='".$type[$i]."'" : $or .= " or pt_type='".$type[$i]."'";
3458 }
3459 } else if(!is_array($type) && $type!='') {
3460 $or = "pt_type='".$type."'";
3461 }
3462 $tot = $this->fetchOne("select sum(point) as tot from sf_user_point_stack where mb_seq=".$mb_seq." and mb_type='".$mb_type."' and sf_user_point_stack.use='n' and ($or) limit 1");
3463 return $tot[tot];
3464 }
3465
3466 function getPtName($pt_type) {
3467 switch($pt_type) {
3468 case "signup" :
3469 $pt_type = "첫구매";
3470 break;
3471 case "link" :
3472 $pt_type = "친구";
3473 break;
3474 }
3475 return $pt_type;
3476 }
3477 function getSecondCates() {
3478 return array('1'=>'디자이너브랜드','2'=>'동대문제품','3'=>'소셜마켓파격특가','4'=>'핸드메이드악세사리','5'=>'소셜마켓뷰티','6'=>'키즈존');
3479 }
3480 function getDesignerBrand() {
3481 $res=array();
3482 $res[0][brand] = "RYUL + WAI:";
3483 $res[0][brandCD] = "RYULWAI";
3484 $res[0][img] = "1.png";
3485 $res[1][brand] = "MOSCA_";
3486 $res[1][brandCD] = "MOSCA";
3487 $res[1][img] = "2.png";
3488 //$res[2][brand] = "RYULWAI";
3489 //$res[2][img] = "demo-10.jpg";
3490 $res[2][brand] = "BENJAMINE CADETTE";
3491 $res[2][brandCD] = "BENJAMINECADETTE";
3492 $res[2][img] = "3.png";
3493 $res[3][brand] = "BLANK";
3494 $res[3][brandCD] = "BLANK";
3495 $res[3][img] = "4.png";
3496 $res[4][brand] = "BetweenAandB";
3497 $res[4][brandCD] = "BetweenAandB";
3498 $res[4][img] = "5.png";
3499 $res[5][brand] = "SONO IO";
3500 $res[5][brandCD] = "SONOIO";
3501 $res[5][img] = "6.png";
3502 $res[6][brand] = "2Placebo";
3503 $res[6][brandCD] = "2Placebo";
3504 $res[6][img] = "9.png";
3505 $res[7][brand] = "AOEMQ";
3506 $res[7][brandCD] = "AOEMQ";
3507 $res[7][img] = "7.png";
3508 $res[8][brand] = "WHY-RI ROVER";
3509 $res[8][brandCD] = "WHYRIROVER";
3510 $res[8][img] = "8.png";
3511 return $res;
3512 }
3513
3514 function isKasType($seller_id) {
3515 $sellerChkQuery = sprintf("select * from sf_member where seller_id = '%s'",$seller_id);
3516 $sellerChk = $this->fetch1($sellerChkQuery);
3517 $venderChkQuery = sprintf("select * from sf_shop where shop_id = '%s'",$seller_id);
3518 $venderChk = $this->fetch1($venderChkQuery);
3519
3520 if($sellerChk[mb_seq] && $venderChk[shop_idx])
3521 return true;
3522
3523 return false;
3524 }
3525
3526 function isAgencyAccountInfo($shop_id) {
3527
3528 $seller_id = $shop_id;
3529
3530 $result = array();
3531 $result[status] = false;
3532 $result[bank_name] = "";
3533 $result[account_holder] = "";
3534 $result[account_number] = "";
3535
3536 //셀러정보
3537 $agencyCheckQry = sprintf("select * from sf_member where seller_id = '%s'",$seller_id);
3538 $agencyCheck = $this->fetch1($agencyCheckQry);
3539
3540 //에이전시 셀러인 경우
3541 if($agencyCheck[seller_recom]){
3542 $tsp = explode('|',$_ENV['agency']);
3543 for ($i=0; $i < count($tsp); $i++) {
3544 //seller_recom과 agency가 일치
3545 if($tsp[$i]==$agencyCheck[seller_recom]) {
3546 $seller_id = $agencyCheck[seller_recom];
3547 }
3548 }
3549 }
3550
3551
3552 //밴더셀러 체크
3553 if(trim($seller_id)) {
3554 $isVenderSellerQry = sprintf("select a.mb_seq from sf_member a left join sf_shop b on a.seller_id=b.shop_id where a.seller_id<>'' and b.shop_id<>'' and a.seller_id='%s' limit 1",$seller_id);
3555 $isVenderSeller = $this->fetch1($isVenderSellerQry);
3556 }
3557
3558 if($isVenderSeller[mb_seq])
3559 {
3560 $accountInfoQry = sprintf("select * from sf_seller_config where mb_seq = '%d'" , $isVenderSeller[mb_seq]);
3561 $accountInfo = $this->fetch1($accountInfoQry);
3562 $accountInfoArr = explode('|',$accountInfo[footer_account]);
3563 if($accountInfoArr[0] && $accountInfoArr[1] && $accountInfoArr[2]){
3564 $result[status] = true;
3565 $result[bank_name] = $accountInfoArr[0];
3566 $result[account_number] = $accountInfoArr[1];
3567 $result[account_holder] = $accountInfoArr[2];
3568 }
3569 }
3570
3571
3572 return $result;
3573 }
3574
3575 function addCashReceipt($arrData){
3576 $arr_result = array();
3577 $vars = array();
3578
3579 $req_url = "https://webtx.tpay.co.kr/api/v1/cash_rcpt_req";
3580 $vars['api_key'] = $_ENV['payment_api_secret'];
3581 $vars['mid'] = $_ENV['payment_api_mid'];
3582 $vars['co_no'] = $arrData['co_no']; //사업자번호
3583 $vars['goods_nm'] = $arrData['goods_nm']; //상품명
3584 $vars['goods_amt'] = $arrData['goods_amt']; //결재금액
3585 $vars['goods_vat'] = $arrData['goods_vat']; //부가세
3586 $vars['supply_amt'] = $arrData['supply_amt']; //공급가액
3587 $vars['sys_amt'] = '0'; //봉사료
3588 $vars['ord_nm'] = $arrData['ord_nm']; //고객이름
3589 $vars['ord_email'] = $arrData['ord_email']; //고객 email
3590 $vars['ord_tel'] = $arrData['ord_tel']; //고객 연락처
3591 $vars['pub_type'] = $arrData['pub_type']; //발행구분코드(2.주민등록번호, 3.사업자번호, 4.휴대폰번호);
3592 $vars['idnt_no'] = $arrData['idnt_no']; //발행대상번호
3593 $vars['req_flag'] = $arrData['req_flag']; //발행용도(1.소득공제, 2.지출증빙)
3594
3595 $ch = curl_init();
3596 curl_setopt($ch, CURLOPT_URL, $req_url);
3597 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
3598 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
3599 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
3600 curl_setopt ($ch, CURLOPT_POST, 1);
3601 curl_setopt ($ch, CURLOPT_POSTFIELDS, http_build_query($vars));
3602 $response = curl_exec($ch);
3603 $errmsg = curl_error($ch);
3604 $cInfo = curl_getinfo($ch);
3605 curl_close($ch);
3606 $arr_res = json_decode($response);
3607
3608 if($arr_res->result_cd=="000") {
3609 $q = "update sf_cash_receipt set issue_date=now(), status=2, cashNo='".$arr_res->cashNo."', cashTid='".$arr_res->cashTid."' where order_no = '".$arrData['order_no']."'";
3610 $this->query($q);
3611 }
3612 }
3613
3614 #장바구니 삭제(만료,재고,비노출 등)
3615 #기획변경으로 삭제 로직 주석처리
3616 function chkOrderCart($mb_seq){
3617
3618 $response = array();
3619 $seller_list = array();
3620 $sold_out_count = 0;
3621
3622 //$q = "select a.*,b.* from sf_cart a, sf_goods b where a.mb_seq = ".$mb_seq." and a.mb_type='st' and b.gs_idx = a.goods_idx"; // 왜 mb_type='st' 인것만 했지..?
3623 $q = "select a.*,b.* from sf_cart a, sf_goods b where a.mb_seq = ".$mb_seq." and b.gs_idx = a.goods_idx";
3624 $res=$this->fetchs($q);
3625 $cart_total_count = count($res);
3626
3627 for($i = 0;$i < count($res);$i++) {
3628 //각 상품의 seller_id를 count한다.
3629 $seller_id = $res[$i][seller_id];
3630 if($seller_id){
3631 if($seller_list[$seller_id]) $seller_list[$seller_id] = $seller_list[$seller_id]+1;
3632 else $seller_list[$seller_id] = 1;
3633 }
3634 //제품의 수량을 체크한다.
3635 if($res[$i][gs_remain] == 0 || $res[$i][gs_stats] != 1) {
3636 $isOrderPossible= false;
3637 $sold_out_count++;
3638 }
3639 }
3640 if($cart_total_count == 0){
3641 $response['code'] = '0';
3642 }
3643 else if($cart_total_count == $sold_out_count){
3644 $response['code'] = '1';
3645 if(count($seller_list) > 0){
3646 krsort($seller_list); //value로 먼저 정렬
3647 arsort($seller_list); //count가 같은 seller_id가 있을 수 있으니 key로 한번 더 정렬
3648 $seller_list_keys = array_keys($seller_list);
3649 $response['seller_id'] = $seller_list_keys[0];
3650 }
3651 }
3652 else if($sold_out_count > 0){
3653 $response['code'] = '2';
3654 }
3655 else{
3656 $response['code'] = '3';
3657 }
3658 return json_encode($response);
3659
3660 }
3661
3662 function getCashReceiptStatusStr($status){
3663 if($status == '1') return "신청";
3664 else if($status == "2") return "발급";
3665 return "취소";
3666 }
3667
3668 #최종접속 sellerId가져오기
3669 function getLastSellerid(){
3670
3671 $qry = sprintf("select * from sf_member where mb_seq = '%s'",$_SESSION[mb_seq]);
3672 $memberInfo = $this->fetch1($qry);
3673 if($memberInfo[mb_last_sellerid] && $memberInfo[mb_last_sellerid] != ""){
3674 return $memberInfo[mb_last_sellerid];
3675 }
3676
3677 return "";
3678 }
3679
3680 function isPrivateContactUs(){
3681 if($_SESSION['seller_id'] && ($this->isAgency($_SESSION['seller_id']) || $this->isBelongAgency($_SESSION['seller_id']) || $this->isKasType($_SESSION['seller_id']))){
3682 if($_SESSION[is_shop_url] == "0"){
3683 return false;
3684 }
3685 }
3686 return true;
3687 }
3688
3689 # 외부 광고유입시 구매완료후 정보전송
3690 function sendCPAResult($order_no,$type='tenping') {
3691 $order_type = substr($order_no,0,1);
3692 if($type=='tenping') {
3693 # 주문정보 가져오기
3694 if($order_type=='g') {
3695 $order_data = $this->fetch1("select sum(a.pay_gs_price) as tot,sum(a.quantity) as qtot,b.data1,b.stats from sf_order a left join sf_order_etc b on a.order_no_group=b.order_no where a.order_no_group = '".$order_no."'");
3696 } else {
3697 $order_data = $this->fetch1("select a.pay_gs_price as tot,a.quantity as qtot,b.data1,b.stats from sf_order a left join sf_order_etc b on a.order_no=b.order_no where a.order_no = '".$order_no."'");
3698 }
3699 if($order_data['stats']=='2') { // 이미 전송된 주문이면
3700 return false;
3701 }
3702
3703 $vars['ordnum'] = $order_no;
3704 $tenping_ids = explode('|',$order_data['data1']);
3705 $req_url = "http://api.tenping.kr/Query";
3706 $vars['jid'] = $tenping_ids[0];
3707 $vars['uid'] = $tenping_ids[1];
3708 $vars['at'] = $tenping_ids[2];
3709 $vars['ordpri'] = $order_data['tot']; // 금액
3710 //$vars['itemnum'] = $_SESSION['tenping_at']; // 상품번호
3711 $vars['ordcnt'] = $order_data['qtot']; // 상품갯수
3712
3713 }
3714 $ch = curl_init();
3715 curl_setopt($ch, CURLOPT_URL, $req_url);
3716 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
3717 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
3718 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
3719 curl_setopt ($ch, CURLOPT_POST, 1);
3720 curl_setopt ($ch, CURLOPT_POSTFIELDS, http_build_query($vars));
3721 $response = curl_exec($ch);
3722 $errmsg = curl_error($ch);
3723 $cInfo = curl_getinfo($ch);
3724 curl_close($ch);
3725 $res = json_decode($response);
3726 if($res->ResultCode!='1') {
3727 Log::write('apiErr','Tenping API 에러 '.$vars['ordnum']);
3728 } else {
3729 $this->query("update sf_order_etc set stats='2' where order_no='".$vars['ordnum']."'");
3730 }
3731 return $res;
3732 }
3733
3734 function sendApiToTwinCircle($order_type,$arrOrderData) {
3735 $req_url = "http://14.35.204.81:8800/api/v1/public/default/inter/partner";
3736 $md5_key = "74B70B2CEA2331D543BA60897EFD3CB3";
3737 /* http://14.35.204.81:8800/api/v1/public/default/inter/partner (개발)
3738
http://www.global-emall.com/api/v1/public/default/inter/partner (운영) */
3739 $vars['ptnId'] = "tagbyc";
3740 $vars['svcId'] = "0100";
3741 $vars['transDt'] = date('YmdHis');
3742 // 中国,北京|中国,北京,北京市|区 |街道地址|邮政编码|320611198501245210
3743 $cny = getExchangeRate('cny');
3744 if($order_type=='d') {
3745 $tmp_ex = explode('|',$arrOrderData['receiver_addr']);
3746 $gs_info = $this->fetchOne("select b.ct_name_cn,a.gs_no,a.gs_name,a.gs_price from sf_goods a left join sf_category b on a.gs_cate=b.ct_idx where a.gs_idx=".$arrOrderData['goods_idx']);
3747 $price_cn = round($gs_info['gs_price']/$cny,2);
3748 $cityCD = $this->fetchOne("select code from sf_citycode_china where name_cn='".$tmp_ex[1]."'");
3749 $vars['transId'] = $arrOrderData['order_no'];
3750 $mb_seq = $arrOrderData['mb_seq'];
3751 $dt_vars['b_name'] = $arrOrderData['receiver_name'];
3752 $dt_vars['b_custID'] = trim((string)$tmp_ex[5]);
3753 $dt_vars['b_phone'] = $arrOrderData['receiver_phone'];
3754 $dt_vars['b_city1'] = $tmp_ex[0];
3755 $dt_vars['b_city2'] = $tmp_ex[1];
3756 $dt_vars['b_city2CD'] = $cityCD['code'];
3757 $dt_vars['b_city3'] = $tmp_ex[2];
3758 $dt_vars['b_addr'] = $tmp_ex[3];
3759 $dt_vars['b_zip'] = $tmp_ex[4];
3760 $dt_vars['items'] = array(
3761 "0"=>
3762 array(
3763 "sku" => $gs_info['gs_no'], // 제품번호
3764 "prodCls" => $gs_info['ct_name_cn'], // 상품분류명
3765 "prodNm" => $gs_info['gs_name'], // 상품명
3766 "upc" => $price_cn, // 단가(공급가)
3767 "qty" => $arrOrderData['quantity'] // 수량
3768 )
3769 );
3770
3771 } else if($order_type=='c') {
3772 $mb_seq = $arrOrderData[0]['mb_seq'];
3773 $vars['transId'] = $arrOrderData[0]['order_no_group'];
3774 $tmp_ex = explode('|',$arrOrderData[0]['receiver_addr']);
3775 $cityCD = $this->fetchOne("select code from sf_citycode_china where name_cn='".$tmp_ex[1]."'");
3776 $dt_vars['b_name'] = $arrOrderData[0]['receiver_name'];
3777 $dt_vars['b_custID'] = trim((string)$tmp_ex[5]);
3778 $dt_vars['b_phone'] = $arrOrderData[0]['receiver_phone'];
3779 $dt_vars['b_city1'] = $tmp_ex[0];
3780 $dt_vars['b_city2'] = $tmp_ex[1];
3781 $dt_vars['b_city2CD'] = $cityCD['code'];
3782 $dt_vars['b_city3'] = $tmp_ex[2];
3783 $dt_vars['b_addr'] = $tmp_ex[3];
3784 $dt_vars['b_zip'] = $tmp_ex[4];
3785 $arr_gs_info = array();
3786 $dt_vars['items'] = array();
3787 for ($i=0; $i < count($arrOrderData); $i++) {
3788 // echo ' - '.$arrOrderData[$i]['goods_idx']. ' - ';
3789 if(!$arrOrderData[$i]['goods_idx']) {
3790 Log::write($vars['transId'],'중국물류 API 장바구니 전송시 제품번호 누실');return false;
3791 }
3792 $gs_info = $this->fetchOne("select b.ct_name_cn,a.gs_no,a.gs_name,a.gs_price from sf_goods a left join sf_category b on a.gs_cate=b.ct_idx where a.gs_idx=".$arrOrderData[$i]['goods_idx']);
3793 $price_cn = round($gs_info['gs_price']/$cny,2);
3794
3795 if(!$gs_info['gs_no'] || !$gs_info['ct_name_cn'] || !$gs_info['gs_name'] || !$price_cn || !$arrOrderData[$i]['quantity']) {
3796 Log::write($vars['transId'],'중국물류 API 장바구니 전송시 제품정보 누실');return false;
3797 }
3798
3799 array_push($dt_vars['items'], array(
3800 "sku" => $gs_info['gs_no'], // 제품번호
3801 "prodCls" => $gs_info['ct_name_cn'], // 상품분류명
3802 "prodNm" => $gs_info['gs_name'], // 상품명
3803 "upc" => $price_cn, // 단가(공급가)
3804 "qty" => $arrOrderData[$i]['quantity'] // 수량
3805 ));
3806
3807
3808 }
3809 }
3810 $data = array(
3811 "orderNo" => $vars['transId'], // 주문번호
3812 "orderDt" => $vars['transDt'], // 주문일시
3813 "custId" => $mb_seq, // 주문자고객아이디
3814 "custNm" => $dt_vars['b_name'], // 주문자명
3815 "custIdNo" => $dt_vars['b_custID'], // 주문자신분증번호
3816 "custPhone" => $dt_vars['b_phone'], // 주문자핸드폰번호
3817 "recvNm" => $dt_vars['b_name'], // 수취인이름
3818 "recvPhone" => $dt_vars['b_phone'], // 수취인핸드폰번호
3819 "recvProv" => $dt_vars['b_city1'], // 수취인 - 성
3820 "recvCityCd" => $dt_vars['b_city2CD'], // 수취인 – 시코드
3821 "recvCity" => $dt_vars['b_city2'], // 수취인 - 시
3822 "recvArea" => $dt_vars['b_city3'], // 수취인 - 구
3823 "recvAddr" => $dt_vars['b_addr'], // 수취인상세주소
3824 "recvZip" => $dt_vars['b_zip'], // 수취인우편번호
3825 "discAmt" => 0, // 할인금액
3826 "orderItem" => $dt_vars['items']
3827 );
3828 $data_json = json_encode($data);
3829 $vars['sign'] = md5($data_json.$md5_key);
3830 $vars['data'] = $data_json;
3831
3832 $ch = curl_init();
3833 curl_setopt($ch, CURLOPT_URL, $req_url);
3834 curl_setopt($ch, CURLOPT_HTTPHEADER, array(
3835 "Accept: application/json",
3836 "Accept-Language: en_US"
3837 ));
3838 curl_setopt($ch, CURLOPT_SSLVERSION, 6);
3839 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
3840 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
3841 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
3842 curl_setopt ($ch, CURLOPT_POST, 1);
3843 curl_setopt ($ch, CURLOPT_POSTFIELDS, $vars);
3844 $response = curl_exec($ch);
3845 $errmsg = curl_error($ch);
3846 $cInfo = curl_getinfo($ch);
3847 curl_close($ch);
3848 print_r($errmsg);
3849 print_r($response);
3850 $res = json_decode($response);
3851 if($res->resCd!='00') {
3852 Log::write($vars['transId'],$res->resMsg);
3853 }
3854 }
3855
3856 # 특정 제품이 특정 개인상점에서 팔린 횟수 및 등록된 시기에 따라 제품 리스트에 hot, new, 급상승 등의 svg icon 뱃지를 달아주는..
3857 function getSvgIcons($gs_idx,$priavet_shop) {
3858
3859 }
3860 function justLogin($shop_id) {
3861 $_SESSION['union_agree'] = '1';
3862 $qry_member = "select mb_seq,mb_email,mb_nick,seller,seller_id,seller_recom,seller_recom2,seller_type from sf_member";
3863 $info_member = $this->fetchOne(sprintf("$qry_member where seller_id='%s' and seller='y'",$shop_id));
3864 # 셀러인 경우 해당 셀러 아이디로 밴더 관리자 정보 자동 로드
3865 if($info_member['mb_seq'] && $info_member['seller']=='y' && $info_member['seller_id']) {
3866 $info_adm = $this->fetchOne(sprintf("select shop_id,shop_name,shop_idx,shop_auth,shop_type from sf_shop where shop_id='%s' and shop_auth<9",$login_email,$clean_post['pwd']));
3867 # 3 회원정보 없는경우
3868 } else if(!$info_member['mb_seq']) {
3869 return false;
3870 }
3871 # 세션 설정
3872 unset($_SESSION['mb_seq']);
3873 unset($_SESSION['mb_id']);
3874 unset($_SESSION['mb_nick']);
3875 unset($_SESSION['mb_type']);
3876 unset($_SESSION['seller']);
3877 unset($_SESSION['seller_id']);
3878 unset($_SESSION['seller_request']);
3879 unset($_SESSION['close_banner']);
3880 unset($_SESSION['is_shop']);
3881 unset($_SESSION['shop_idx']);
3882 unset($_SESSION['shop_auth']);
3883 $_SESSION['mb_seq'] = $info_member['mb_seq'];
3884 $_SESSION['mb_id'] = $info_member['mb_email'];
3885 $_SESSION['mb_nick'] = $info_member['mb_nick'];
3886 $_SESSION['mb_type'] = "st";
3887 # 셀러일 경우 추가 세션 설정
3888 if(trim($info_member['seller'])=='y') {
3889 unset($_SESSION['private_shop']); //셀러로 로그인한 경우 기존 개인상점 세션 제거
3890 $_SESSION['seller'] = "1";
3891 $_SESSION['seller_type'] = $info_member['seller_type'];
3892 $_SESSION['seller_id'] = $info_member['seller_id'];
3893 $recom = $info_member['seller_recom2'] ? $info_member['seller_recom2'] : $info_member['seller_recom']; // 임대몰 에이전시가 우선순위 - 주의 로그인시는 에이전시 아이디로 체크하면 안됨
3894 # 에이전시 혹은 하위 샾인지 체크
3895 if($this->isAgency($_SESSION['seller_id'])) {
3896 $_SESSION['agency'] = '1';
3897 } else if(trim($recom)) {
3898 if($this->isAgency($recom)) {
3899 $_SESSION['is_agency'] = '1';
3900 $_SESSION['agency_id'] = $recom;
3901 }
3902 }
3903 // if(trim($info_member['seller_recom'])) {
3904 // $tsp = explode('|',$_ENV['agency']);
3905 // for ($i=0; $i < count($tsp); $i++) {
3906 // if($tsp[$i]==$_SESSION['seller_id']) {
3907 // $_SESSION['agency'] = '1';
3908 // }
3909 // if($tsp[$i]==$info_member['seller_recom']) {
3910 // $_SESSION['is_agency'] = '1';
3911 // $_SESSION['agency_id'] = $tsp[$i];
3912 // }
3913 // }
3914 // }
3915 } else {
3916 return false;
3917 }
3918 }
3919
3920 function curl_wallet_payment($arrData) {
3921 $curl = curl_init();
3922
3923 $url = 'http://api.socialmarket.kr/Wallet/' . 'payWallet';
3924 $post_param = array(
3925 'api_key' => '*6F5F067D8252500A437E8AC7AE85471788A7CAD2',
3926 'referer_code' => $arrData['referer_code'],
3927 'symbol' => $arrData['symbol'],
3928 'price' => $arrData['price']
3929 );
3930 $curl_opt[CURLOPT_POST] = true;
3931 $curl_opt[CURLOPT_POSTFIELDS] = http_build_query($post_param);
3932 $curl_opt[CURLOPT_URL] = $url;
3933 $curl_opt[CURLOPT_RETURNTRANSFER] = true;
3934 $curl_opt[CURLOPT_CONNECTTIMEOUT] = 60;
3935 $curl_opt[CURLOPT_TIMEOUT] = 60;
3936 $curl_opt[CURLOPT_REFERER] = 'http://'.$_SERVER['HTTP_HOST'];
3937
3938 curl_setopt_array($curl, $curl_opt);
3939 $output = curl_exec($curl);
3940 curl_close($curl);
3941
3942 return json_decode($output, true);
3943 }
3944 }
3945?>