/home/mjc1/public_html/html/millennium/Order_point_Process_nice.php


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
<?php include_once("./_common2.php"); ?>
<?
include("../../manage/category/Ordercommon.php");
include(
$_SERVER["DOCUMENT_ROOT"]."/lib/common2.lib.php");

function 
nice_file_log($sql,$res_array){
    
$fp fopen($_SERVER['DOCUMENT_ROOT']."/nice/log/paynow_res_".date("Ymd").".txt",'a');
    if(
$sql == "res_start"){
        
fwrite($fp,"\n\n\n");
    }
    
fwrite($fp,"========================".date("Y-m-d H:i:s")."======================== \n");
    
fwrite($fp,"$sql \n");
    foreach(
$res_array as $key => $val){
        
fwrite($fp,"{$key} = {$val} \n");
    }
    
fclose($fp);
}

function 
conv_euckr($str){
    
$str iconv("utf-8","euc-kr",$str);
    return 
$str
}

function 
conv_utf8($str){
    
$str iconv("euc-kr","utf-8",$str);
    return 
$str
}

function 
conv_array_utf8($info){
    
$newinfo null;
    foreach(
$info as $key => $val){
        if(
is_array($val)){
            
$ninfo null;
            foreach(
$val as $k => $v){
                
$ninfo[$k] = stripslashes(conv_utf8($v));
            }
            
$newinfo[$key] = $ninfo;
        } else {
            
$newinfo[$key] = stripslashes(conv_utf8($val));
        }
    }
    return 
$newinfo;
}

function 
conv_array_euckr($info){
    
$newinfo null;
    foreach(
$info as $key => $val){
        if(
is_array($val)){
            
$ninfo null;
            foreach(
$val as $k => $v){
                
$ninfo[$k] = stripslashes(conv_euckr($v));
            }
            
$newinfo[$key] = $ninfo;
        } else {
            
$newinfo[$key] = stripslashes(conv_euckr($val));
        }
    }
    return 
$newinfo;
}

/*
****************************************************************************************
* <인증 결과 파라미터>
****************************************************************************************
*/
$authResultCode $_POST['AuthResultCode'];        // 인증결과 : 0000(성공)
$authResultMsg $_POST['AuthResultMsg'];        // 인증결과 메시지
$nextAppURL $_POST['NextAppURL'];                // 승인 요청 URL
$txTid $_POST['TxTid'];                        // 거래 ID
$authToken $_POST['AuthToken'];                // 인증 TOKEN
$payMethod $_POST['PayMethod'];                // 결제수단
$mid $_POST['MID'];                            // 상점 아이디
$moid $_POST['Moid'];                            // 상점 주문번호
$amt $_POST['Amt'];                            // 결제 금액
$reqReserved $_POST['ReqReserved'];            // 상점 예약필드
$netCancelURL $_POST['NetCancelURL'];            // 망취소 요청 URL
$authSignature $_POST['Signature'];            // Nicepay에서 내려준 응답값의 무결성 검증 Data

nice_file_log("res_start"$_POST); // 파일로그

$merchantKey "tw1EOlWp+7E6ezOifjEbmBfFfEuzjEex/WeQRXuqMJArF696mq4byEi+bFaiWrWNhMoHNP+RXdOupN5AvnNJmg=="// 상점키

// 인증 응답 Signature = hex(sha256(AuthToken + MID + Amt + MerchantKey)
$authComparisonSignature bin2hex(hash('sha256'$authToken$mid$amt$merchantKeytrue)); 

/*
****************************************************************************************
* <승인 결과 파라미터 정의>
* 샘플페이지에서는 승인 결과 파라미터 중 일부만 예시되어 있으며, 
* 추가적으로 사용하실 파라미터는 연동메뉴얼을 참고하세요.
****************************************************************************************
*/

$response "";

$post $_POST;

// 인증 응답으로 받은 Signature 검증을 통해 무결성 검증을 진행하여야 합니다.
if($authResultCode === "0000" && $authSignature == $authComparisonSignature){
    
/*
    ****************************************************************************************
    * <해쉬암호화> (수정하지 마세요)
    * SHA-256 해쉬암호화는 거래 위변조를 막기위한 방법입니다. 
    ****************************************************************************************
    */    
    
$ediDate date("YmdHis");
    
$signData bin2hex(hash('sha256'$authToken $mid $amt $ediDate $merchantKeytrue));

    try{
        
$data = Array(
            
'TID' => $txTid,
            
'AuthToken' => $authToken,
            
'MID' => $mid,
            
'Amt' => $amt,
            
'EdiDate' => $ediDate,
            
'SignData' => $signData,
            
'CharSet' => 'utf-8'
        
);

        
$ch curl_init();
        
curl_setopt($chCURLOPT_URL$nextAppURL);
        
curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
        
curl_setopt($chCURLOPT_CONNECTTIMEOUT15);                    //connection timeout 15 
        
curl_setopt($chCURLOPT_SSL_VERIFYPEERfalse);
        
curl_setopt($chCURLOPT_POSTFIELDShttp_build_query($data));    //POST data
        
curl_setopt($chCURLOPT_POSTtrue);
        
$response curl_exec($ch);
        
$httpCode curl_getinfo($chCURLINFO_HTTP_CODE);
        
curl_close($ch);

        
$isSuccess $httpCode == 200;

        
$responseJson json_decode($response);

        foreach ( 
$responseJson as $key => $value ){
            if(
$key == "Amt" || $key == "CancelAmt"){
                
$payAmt $value;
            }
            if(
$key == "TID"){
                
$tid $value;
            }
            if(
$key == "Moid"){
                
$cancelmoid $value;
            }
            if(
$key == "BuyerName"){
                
$cancelbname conv_euckr($value);
            }
            if(
$key == "GoodsName"){
                
$cancelgname conv_euckr($value);
            }
            
// 승인 응답으로 받은 Signature 검증을 통해 무결성 검증을 진행하여야 합니다.
            
if($key == "Signature"){
                
$paySignature bin2hex(hash('sha256'$tid$mid$payAmt$merchantKeytrue));
                if(
$value != $paySignature){

                    
$ediDate2 date("YmdHis");
                    
$signData2 bin2hex(hash('sha256'$mid $amt $ediDate2 $merchantKeytrue));

                    
// 비정상 거래일 경우 거래취소를 진행한다.
                    
try{
                        
$data = Array(
                            
'TID' => $tid,
                            
'MID' => $mid,
                            
'Moid' => $moid,
                            
'CancelAmt' => $amt,
                            
'CancelMsg' => "비정상거래",
                            
'PartialCancelCode' => "0",
                            
'EdiDate' => $ediDate2,
                            
'SignData' => $signData2,
                            
'CharSet' => 'utf-8'
                        
);

                        
$ch curl_init();
                        
curl_setopt($chCURLOPT_URL"https://pg-api.nicepay.co.kr/webapi/cancel_process.jsp");
                        
curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
                        
curl_setopt($chCURLOPT_CONNECTTIMEOUT15); //connection timeout 15 
                        
curl_setopt($chCURLOPT_SSL_VERIFYPEERfalse);
                        
curl_setopt($chCURLOPT_POSTFIELDShttp_build_query($data));    //POST data
                        
curl_setopt($chCURLOPT_POSTtrue);
                        
$response curl_exec($ch);
                        
curl_close($ch);

                        
$respArr json_decode($response);

                        foreach ( 
$respArr as $key => $value ){
                            if(
$key == "CancelAmt"){
                                
$cancelAmt $value;
                            }
                            if(
$key == "TID"){
                                
$tid $value;
                            }
                            
// 취소 응답으로 받은 Signature 검증을 통해 무결성 검증을 진행하여야 합니다.
                            
if($key == "Signature"){
                                
$cancelSignature bin2hex(hash('sha256'$tid$mid$cancelAmt$merchantKeytrue));
                                if(
$value != $cancelSignature){
                                    echo 
"비정상거래 :: 결제취소에 실패했습니다.";
                                    exit;
                                }
                            }
                        }

                        
$respArr json_decode(json_encode($respArrJSON_UNESCAPED_UNICODE),true);

                        
$respArr conv_array_euckr($respArr);

                        
nice_file_log("nice_cancel_res"$respArr); // 파일로그

                        
echo "TX Rollback Response_code = " $respArr['ResultCode'] . "<br>";
                        echo 
"TX Rollback Response_msg = " $respArr['ResultMsg'] . "<br>";
                    
                        if( 
"2001" == $respArr['ResultCode'] || "2211" == $respArr['ResultCode'] ) { // 2001 : 취소 성공, 2211 : 환불 성공
                            
echo "자동취소가 정상적으로 완료 되었습니다.<br>";
                        } else {
                            echo 
"자동취소가 정상적으로 처리되지 않았습니다.<br>";
                        }

                        
$plusdate $respArr['CancelDate'].$respArr['CancelNum'];

                        
$json conv_array_utf8($respArr);
                        
$json str_replace("\\","\\\\",json_encode($json));

                        
$post_json conv_array_utf8($data);
                        
$post_json str_replace("\\","\\\\",json_encode($post_json));

                        
$sql "insert into nice_log set p_type = 'signature_fail', mid = '{$respArr[MID]}', moid = '{$respArr[Moid]}', amt = '{$respArr[CancelAmt]}', buyername = '{$cancelbname}', goodsname = '{$cancelgname}', authcode = '{$respArr[CancelNum]}', authdate = '{$plusdate}', paymethod = '{$respArr[PayMethod]}', signature = '{$respArr[Signature]}', tid = '{$respArr[TID]}', resultcode = '{$respArr[ResultCode]}', resultmsg = '{$respArr[ResultMsg]}', res_json = '$json', post_json = '$post_json'";
                        
mysql_query($sql);

                    }catch(
Exception $e){
                        
$e->getMessage();
                        echo 
"통신실패 :: 결제취소에 실패했습니다.";
                        exit;
                    }
                }
            }
        }

        
$nice_res json_decode(json_encode($responseJsonJSON_UNESCAPED_UNICODE),true);
        
$nice_res conv_array_euckr($nice_res);

        
/*
        결제수단    성공 ResultCode    설명
        신용카드    3001    결제 성공
        계좌이체    4000    실시간 이체 성공
        가상계좌    4100 / 4110    4100: 계좌 발급 / 4110: 입금 확인 완료
        */
        
if ($isSuccess && ($nice_res['ResultCode'] == "3001" || $nice_res['ResultCode'] == "4000" || $nice_res['ResultCode'] == "4100" || $nice_res['ResultCode'] == "4110")) { // 결제 성공시
            
nice_file_log("nice_res"$nice_res); // 파일로그

            
$json conv_array_utf8($nice_res);
            
$json str_replace("\\","\\\\",json_encode($json));

            
$post_json conv_array_utf8($post);
            
$post_json str_replace("\\","\\\\",json_encode($post_json));

            
// 로그 저장
            
$sql "insert into nice_log set
                    p_type = 'pay_res', mid = '
{$nice_res[MID]}', moid = '{$nice_res[Moid]}', amt = '{$nice_res[Amt]}', buyername = '{$nice_res[BuyerName]}', goodsname = '{$nice_res[GoodsName]}', authcode = '{$nice_res[AuthCode]}', authdate = '{$nice_res[AuthDate]}', paymethod = '{$nice_res[PayMethod]}', signature = '{$nice_res[Signature]}', tid = '{$nice_res[TID]}', resultcode = '{$nice_res[ResultCode]}', resultmsg = '{$nice_res[ResultMsg]}', res_json = '$json', post_json = '{$post_json}'";
            
mysql_query($sql);

            
$post['OrdPhone'] = $post['tel1'].$post['tel2'].$post['tel3'];
            
$post['OrdPhone2'] = $post['hp1'].$post['hp2'].$post['hp3'];
            
$post['DlvPost'] = $post['post1'].$post['post2'];
            
$reg_date date("Y-m-d H:i:s",time());

            if(
$nice_res['PayMethod']=='BANK'){ // 실시간 계좌이체일 경우
                
$iche_name $nice_res['BuyerName']; // 계좌주명
                
$reciept[0] = '소득공제'$reciept[1] = '지출증빙';
                
$iche_outbankname $nice_res['RcptAuthCode']."/".$nice_res['RcptTID']."/".$reciept[$nice_res['RcptType']]; // 현금영수증 정보

            
} else if($nice_res['PayMethod']=='VBANK'){ // 가상계좌 일경우
                
$iche_outacct $nice_res['VbankNum']; // 가상계좌발급번호
                
$iche_name $nice_res['BuyerName']; // 가상계좌 입금계좌주명
                // 가상계좌의 경우 현금영수증과 관련된 리턴값은 없음.
            
}

            if(
$nice_res['PayMethod'] == "CARD") {
                
$authty_txt "card";
            } else if(
$nice_res['PayMethod'] == "BANK") {
                
$authty_txt "iche";
            } else if(
$nice_res['PayMethod'] == "VBANK") {
                
$authty_txt "virtual";
            }

            
$point_txt iconv("utf-8","euc-kr","[포인트충전]");

            if(
$nice_res['PayMethod']=='VBANK'){ // 가상계좌 일경우
                
$insertOrder =  " insert into mBoard_order set
                    rOrdNo = '
{$nice_res['Moid']}', AuthTy = '{$authty_txt}', memberId = '{$post['UserId']}', OrdNm ='{$post['Mname']}',
                    OrdPhone = '
{$post['OrdPhone']}', OrdPhone2 = '{$post['OrdPhone2']}', UserEmail = '{$post['Memail']}', DlvAddr = '{$post['Madd']}', 
                    DlvPost = '
{$post['DlvPost']}', OrdComp = '{$post['Mcompany']}', ProductCode = 'point', rProdNm = '{$point_txt}',
                    rProdNm2 = '', rProdNm3 = '', rProdNm4 = '', rAmt = '
{$nice_res['Amt']}', 
                    rSuccYn = 'i', rCardNm = '
{$res_array['LGD_FINANCENAME']} {$res_array['LGD_CARDNUM']}', rApprNo = '{$res_array['LGD_TID']}', ICHE_OUTBANKNAME = '{$ICHE_OUTBANKNAME}',
                    ICHE_OUTACCTNO = '
{$ICHE_OUTACCTNO}', ICHE_OUTBANKMASTER = '{$ICHE_OUTBANKMASTER}', ICHE_AMOUNT = '{$ICHE_AMOUNT}', bank = '$bank',
                    Pcnt = '
{$res_array['LGD_ESCROWYN']}', reg_date = '$reg_date', InvoiceNum = '{$res_array['LGD_RESPMSG']}:{$res_array['LGD_OID']}/{$res_array['LGD_RESPCODE']}', Deliver = '', 
                    senditem = '
{$post['SendItem']}', salestopvalue = '', mod_date = '$reg_date'
                "
;
            } else {
                
$insertOrder =  " insert into mBoard_order set
                    rOrdNo = '
{$nice_res['Moid']}', AuthTy = '{$authty_txt}', memberId = '{$post['UserId']}', OrdNm ='{$post['Mname']}',
                    OrdPhone = '
{$post['OrdPhone']}', OrdPhone2 = '{$post['OrdPhone2']}', UserEmail = '{$post['Memail']}', DlvAddr = '{$post['Madd']}', 
                    DlvPost = '
{$post['DlvPost']}', OrdComp = '{$post['Mcompany']}', ProductCode = 'point', rProdNm = '{$point_txt}',
                    rProdNm2 = '', rProdNm3 = '', rProdNm4 = '', rAmt = '
{$nice_res['Amt']}', 
                    rSuccYn = 'y', rCardNm = '
{$nice_res['CardName']} {$nice_res['CardNo']}', rApprNo = '{$nice_res['TID']}', ICHE_OUTBANKNAME = '{$iche_outbankname}',
                    ICHE_OUTACCTNO = '
{$iche_outacct}', ICHE_OUTBANKMASTER = '{$iche_name}', ICHE_AMOUNT = '', bank = '',
                    Pcnt = 'N', reg_date = '
$reg_date', InvoiceNum = '{$nice_res['ResultMsg']}:{$nice_res['Moid']}/{$nice_res['ResultCode']}', Deliver = '', 
                    senditem = '
{$post['SendItem']}', salestopvalue = '', mod_date = '$reg_date'
                "
;

                
nice_file_log($insertOrder,""); // 파일로그

                //echo "<pre>"; print_r($insertOrder); echo "</pre>";
                
mysql_query($insertOrder);
                
//order_log("mBoard_order", $insertOrder);
            
}

            
$sql "select count(*) as cnt from mBoard_order where rApprNo = '{$nice_res['TID']}' ";
            
$res mysql_query($sql);
            
$info mysql_fetch_array($res);
            
            if(
$info['cnt']>0){ $isDBOK true; } else { $isDBOK false; }
            
            if( !
$isDBOK ) {
                
$ediDate2 date("YmdHis");
                
$signData2 bin2hex(hash('sha256'$nice_res['MID'] . $nice_res['Amt'] . $ediDate $merchantKeytrue));

                try{
                    
$data = Array(
                        
'TID' => $nice_res['TID'],
                        
'MID' => $nice_res['MID'],
                        
'Moid' => $nice_res['Moid'],
                        
'CancelAmt' => $nice_res['Amt'],
                        
'CancelMsg' => "상점 DB처리 실패로 인하여 Rollback 처리",
                        
'PartialCancelCode' => "0",
                        
'EdiDate' => $ediDate2,
                        
'SignData' => $signData2,
                        
'CharSet' => 'utf-8'
                    
);

                    
$ch curl_init();
                    
curl_setopt($chCURLOPT_URL"https://pg-api.nicepay.co.kr/webapi/cancel_process.jsp");
                    
curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
                    
curl_setopt($chCURLOPT_CONNECTTIMEOUT15); //connection timeout 15 
                    
curl_setopt($chCURLOPT_SSL_VERIFYPEERfalse);
                    
curl_setopt($chCURLOPT_POSTFIELDShttp_build_query($data));    //POST data
                    
curl_setopt($chCURLOPT_POSTtrue);
                    
$response curl_exec($ch);
                    
curl_close($ch);

                    
$respArr json_decode($response);

                    foreach ( 
$respArr as $key => $value ){
                        if(
$key == "CancelAmt"){
                            
$cancelAmt $value;
                        }
                        if(
$key == "TID"){
                            
$tid $value;
                        }
                        
// 취소 응답으로 받은 Signature 검증을 통해 무결성 검증을 진행하여야 합니다.
                        
if($key == "Signature"){
                            
$cancelSignature bin2hex(hash('sha256'$tid$mid$cancelAmt$merchantKeytrue));
                            if(
$value != $cancelSignature){
                                echo 
"비정상거래 :: 결제취소에 실패했습니다.";
                                exit;
                            }
                        }
                    }

                    
$respArr json_decode(json_encode($respArrJSON_UNESCAPED_UNICODE),true);
                    
$respArr conv_array_euckr($respArr);

                    
nice_file_log("nice_cancel_res"$respArr); // 파일로그

                    
echo "TX Rollback Response_code = " $respArr['ResultCode'] . "<br>";
                    echo 
"TX Rollback Response_msg = " $respArr['ResultMsg'] . "<br>";
                
                    if( 
"2001" == $respArr['ResultCode'] || "2211" == $respArr['ResultCode'] ) { // 2001 : 취소 성공, 2211 : 환불 성공
                        
echo "자동취소가 정상적으로 완료 되었습니다.<br>";
                    } else {
                        echo 
"자동취소가 정상적으로 처리되지 않았습니다.<br>";
                    }

                    
$plusdate $respArr['CancelDate'].$respArr['CancelNum'];

                    
$json conv_array_utf8($respArr);
                    
$json str_replace("\\","\\\\",json_encode($json));

                    
$post_json conv_array_utf8($data);
                    
$post_json str_replace("\\","\\\\",json_encode($post_json));

                    
$sql "insert into nice_log set p_type = 'signature_fail', mid = '{$respArr[MID]}', moid = '{$respArr[Moid]}', amt = '{$respArr[CancelAmt]}', buyername = '{$cancelbname}', goodsname = '{$cancelgname}', authcode = '{$respArr[CancelNum]}', authdate = '{$plusdate}', paymethod = '{$respArr[PayMethod]}', signature = '{$respArr[Signature]}', tid = '{$respArr[TID]}', resultcode = '{$respArr[ResultCode]}', resultmsg = '{$respArr[ResultMsg]}', res_json = '$json', post_json = '$post_json'";
                    
mysql_query($sql);

                }catch(
Exception $e){
                    
$e->getMessage();
                    echo 
"통신실패 :: 결제취소에 실패했습니다.";
                    exit;
                }
                    
                exit;
            }

            
// 포인트 자동충전
            
if($nice_res['PayMethod']=='VBANK'){ // 가상계좌 일경우
            
} else {
                include(
"../../manage/category/pointordercommon.php");

                
$idqry    "select * from customers where id = '{$post['UserId']}'";
                
$resultid  =   mysql_query($idqry);

                
$online_txt iconv("utf-8","euc-kr","온라인");
                        
                
//포인트 아이디가 있으면 충전
                
if( mysql_num_rows($resultid) > 0){
                    
$pupdateQry "INSERT INTO cash_fill (cust_id, rgst_dtm, addpoint, price, rgster_nm, delkey)
                                values ('
$UserId','$reg_date','$f_point','$f_price','$online_txt','0')";    //기존회원 포인트 충전
                    
mysql_query($pupdateQry);
            
                
//포인트 ID가 없을 경우 생성후 충전    
                
} else {
            
                    
$companyNum2 str_replace("-","",$companyNum);
                    
$newinsertQry "INSERT INTO customers ( id, custname, custnum, tel, hpno, frst_rgst_dtm, frst_rgster_nm)
                                    values ('
$Mid','$Mcompany','$companyNum2','$Mtel1','$Mhp','$reg_date','$online_txt')";    //회원등록
                    
mysql_query($newinsertQry);
                    

                    
$newpupdateQry "INSERT INTO cash_fill (cust_id, rgst_dtm, addpoint, price, rgster_nm, delkey)
                                    values ('
$UserId','$reg_date','$f_point','$f_price','$online_txt','0')";    //포인트충전
                    
                    
mysql_query($newpupdateQry);
                }
            }
        
        } else { 
// 결제실패

            
$nice_res json_decode(json_encode($responseJsonJSON_UNESCAPED_UNICODE),true);
            
$nice_res conv_array_euckr($nice_res);

            
$post['OrdPhone'] = $post['tel1'].$post['tel2'].$post['tel3'];
            
$post['OrdPhone2'] = $post['hp1'].$post['hp2'].$post['hp3'];
            
$post['DlvPost'] = $post['post1'].$post['post2'];
            
$reg_date date("Y-m-d H:i:s",time());

            if(
$nice_res['PayMethod']=='BANK'){ // 실시간 계좌이체일 경우
                
$iche_name $nice_res['BuyerName']; // 계좌주명
                
$reciept[0] = '소득공제'$reciept[1] = '지출증빙';
                
$iche_outbankname $nice_res['RcptAuthCode']."/".$nice_res['RcptTID']."/".$reciept[$nice_res['RcptType']]; // 현금영수증 정보

            
} else if($nice_res['PayMethod']=='VBANK'){ // 가상계좌 일경우
                
$iche_outacct $nice_res['VbankNum']; // 가상계좌발급번호
                
$iche_name $nice_res['BuyerName']; // 가상계좌 입금계좌주명
                // 가상계좌의 경우 현금영수증과 관련된 리턴값은 없음.
            
}

            if(
$nice_res['PayMethod'] == "CARD") {
                
$authty_txt "card";
            } else if(
$nice_res['PayMethod'] == "BANK") {
                
$authty_txt "iche";
            } else if(
$nice_res['PayMethod'] == "VBANK") {
                
$authty_txt "virtual";
            }

            
$insertOrder =  " insert into mBoard_order set
                    rOrdNo = '
{$nice_res['Moid']}', AuthTy = '{$authty_txt}', memberId = '{$post['UserId']}', OrdNm ='{$post['Mname']}',
                    OrdPhone = '
{$post['OrdPhone']}', OrdPhone2 = '{$post['OrdPhone2']}', UserEmail = '{$post['Memail']}', DlvAddr = '{$post['Madd']}', 
                    DlvPost = '
{$post['DlvPost']}', OrdComp = '{$post['Mcompany']}', ProductCode = '{$post['LGD_PRODUCTINFO']}', rProdNm = '{$post['LGD_PRODUCTINFO']}',
                    rProdNm2 = '', rProdNm3 = '', rProdNm4 = '', rAmt = '
{$nice_res['Amt']}', 
                    rSuccYn = 'y', rCardNm = '
{$nice_res['CardName']} {$nice_res['CardNo']}', rApprNo = '{$nice_res['TID']}', ICHE_OUTBANKNAME = '{$iche_outbankname}',
                    ICHE_OUTACCTNO = '
{$iche_outacct}', ICHE_OUTBANKMASTER = '{$iche_name}', ICHE_AMOUNT = '', bank = '',
                    Pcnt = 'N', reg_date = '
$reg_date', InvoiceNum = '{$nice_res['ResultMsg']}:{$nice_res['Moid']}/{$nice_res['ResultCode']}', Deliver = '', 
                    senditem = '
{$post['SendItem']}', salestopvalue = '', mod_date = '$reg_date'
                "
;

            
nice_file_log($insertOrder,""); // 파일로그

            //echo "<pre>"; print_r($insertOrder); echo "</pre>";
            //mysql_query($insertOrder);
            //order_log("mBoard_order", $insertOrder);

            //통신상의 문제 발생(최종결제요청 결과 실패 DB처리)
            
echo "최종결제요청 결과 실패 DB처리하시기 바랍니다.<br>";
        }
        
    }catch(
Exception $e){
        
$e->getMessage();
        
$data = Array(
            
'TID' => $txTid,
            
'AuthToken' => $authToken,
            
'MID' => $mid,
            
'Amt' => $amt,
            
'EdiDate' => $ediDate,
            
'SignData' => $signData,
            
'NetCancel' => '1',
            
'CharSet' => 'utf-8'
        
);
        
$response reqPost($data$netCancelURL); //예외 발생시 망취소 진행
        
$responseJson jsonRespDump($response); //response json dump example
    
}
    
} else if(
$authComparisonSignature == $authSignature) {
    
//인증 실패 하는 경우 결과코드, 메시지
    
$ResultCode $authResultCode;
    
$ResultMsg $authResultMsg;
    
_pr("결제 실패");
    
_pr($ResultMsg);
    
_pr($ResultCode);
    exit;

} else {
    
_pr('인증 응답 Signature : '$authSignature);
    
_pr('인증 생성 Signature : '$authComparisonSignature);
    exit;
}

// API CALL foreach 예시
function jsonRespDump($resp){
    global 
$mid$merchantKey;
    
$respArr json_decode($resp);

    foreach ( 
$respArr as $key => $value ){
        if(
$key == "Amt" || $key == "CancelAmt"){
            
$payAmt $value;
        }
        if(
$key == "TID"){
            
$tid $value;
        }
        
// 승인 응답으로 받은 Signature 검증을 통해 무결성 검증을 진행하여야 합니다.
        
if($key == "Signature"){
            
$paySignature bin2hex(hash('sha256'$tid$mid$payAmt$merchantKeytrue));
            if(
$value != $paySignature){
                
_pr("비정상 거래! 취소 요청이 필요합니다.");
                
_pr("승인 응답 Signature : ".$value);
                
_pr("승인 생성 Signature : ".$paySignature);
                exit;
            }
        }
    }

    return 
$respArr;
}

//Post api call
function reqPost(Array $data$url){
    
$ch curl_init();
    
curl_setopt($chCURLOPT_URL$url);
    
curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
    
curl_setopt($chCURLOPT_CONNECTTIMEOUT15);                    //connection timeout 15 
    
curl_setopt($chCURLOPT_SSL_VERIFYPEERfalse);
    
curl_setopt($chCURLOPT_POSTFIELDShttp_build_query($data));    //POST data
    
curl_setopt($chCURLOPT_POSTtrue);
    
$response curl_exec($ch);
    
curl_close($ch);     
    return 
$response;
}

?>

<html>
<head>
</head>
<body onload="nicepay_ing.submit();">
<!-- LOGGER(TM) SCRIPT FOR SETTING ENVIRONMENT V.27 :  / FILL THE VALUE TO SET. -->
<script type="text/javascript">var _TRK_LID="54486";var _L_TD="ssl.logger.co.kr";var _TRK_CDMN=".mjsoft.co";</script>
<script type="text/javascript">var _CDN_DOMAIN = location.protocol == "https:" ? "https://fs.bizspring.net" : "http://fs.bizspring.net";
(function(b,s){var f=b.getElementsByTagName(s)[0],j=b.createElement(s);j.async=true;j.src='//fs.bizspring.net/fs4/bstrk.1.js';f.parentNode.insertBefore(j,f);})(document,'script');</script>
<noscript><img alt="Logger Script" width="1" height="1" src="http://ssl.logger.co.kr/tracker.tsp?u=54486&amp;js=N" /></noscript>

<script type="text/javascript">
_TRK_PI = "ODR";
_TRK_OA = "<?php echo $nice_res['Amt'];?>";
_TRK_OE = "<?php echo $post['productname'].' '.$post['productcode'];?>";
_TRK_OP = "1";
</script>
<!-- END OF ENVIRONMENT SCRIPT -->
<form name="nicepay_ing" method="post" action="Order_result_nice.php">

<input type=hidden name="Moid" value="<?=$nice_res['Moid']?>">        <!-- 주문번호 -->
<input type=hidden name="MID" value="<?=$nice_res['MID']?>">        <!-- 상점아이디 -->
<input type=hidden name="ResultMsg" value="<?=$nice_res['ResultMsg']?>">        <!-- 응답메시지 -->
<input type=hidden name="AuthDate" value="<?=$nice_res['AuthDate']?>">        <!-- 승인날짜 -->

</form>
</body> 
</html>

<script type="text/javascript" charset="UTF-8" src="//t1.daumcdn.net/adfit/static/kp.js"></script>
<script type="text/javascript">
      kakaoPixel('9030595970490714314').pageView();
      kakaoPixel('9030595970490714314').purchase();
</script>