first commit 2

This commit is contained in:
hmw1001
2026-06-11 18:47:38 +09:00
parent c768729ce6
commit 6f534e33a6
11095 changed files with 1595758 additions and 0 deletions
+2
View File
@@ -0,0 +1,2 @@
<?php
include_once('../../common.php');
+1
View File
@@ -0,0 +1 @@
<script language="javascript" type="text/javascript" src="https://stgstdpay.inicis.com/stdjs/INIStdPay_close.js" charset="UTF-8"></script>
+132
View File
@@ -0,0 +1,132 @@
<?php
if (!defined("_GNUBOARD_")) exit; // 개별 페이지 접근 불가
if($od['od_pg'] != 'inicis') return;
include_once(G5_SHOP_PATH.'/settle_inicis.inc.php');
// 택배회사 코드, https://manual.inicis.com/iniweb/code.html 에서 조회
$exCode = array(
'대한통운' => 'korex',
'아주택배' => 'ajutb',
'KT로지스' => 'ktlogistics',
'롯데택배(구.현대)' => 'hyundai',
'CJ대한통운' => 'cjgls',
'한진택배' => 'hanjin',
'트라넷' => 'tranet',
'하나로택배' => 'Hanaro',
'사가와익스프레스' => 'Sagawa',
'SEDEX' => 'sedex',
'KGB택배' => 'kgbls',
'로젠택배' => 'kgb',
'KG옐로우캡택배' => 'yellow',
'삼성HTH' => 'hth',
'동부택배' => 'dongbu',
'우체국' => 'EPOST',
'우편등기' => 'registpost',
'경동택배' => 'kdexp',
'천일택배' => 'chunil',
'대신택배' => 'daesin',
'일양로지스' => 'ilyang',
'호남택배' => 'honam',
'편의점택배' => 'cvsnet',
'합동택배' => 'hdexp',
'기타택배' => '9999'
);
//step1. 요청을 위한 파라미터 설정
// 가맹점관리자 > 상점정보 > 계약정보 > 부가정보 > INIAPI key 생성조회
if (function_exists('get_inicis_iniapi_key')) {
$key = get_inicis_iniapi_key();
} else {
$key = ! $default['de_card_test'] ? $default['de_inicis_iniapi_key'] : "ItEQKi3rY7uvDS8l";
}
$dlv_exName = $escrow_corp;
$type = "Dlv"; //"Dlv" 고정
$mid = $default['de_inicis_mid'];
$clientIp = $_SERVER['SERVER_ADDR']; // 가맹점 요청 서버IP, 상점 임의 설정 가능 (상점측 서버 구분을 위함)
$timestamp = date("YmdHis");
$tid = $escrow_tno; //에스크로 결제 승인TID
$oid = $od['od_id'];
$price = $od['od_receipt_price'];
$report = "I"; //에스크로 등록형태 ["I":등록, "U":변경]
$invoice = $escrow_numb; //운송장번호
$registName = $member['mb_id'];
$exCode = isset($exCode[$dlv_exName]) ? $exCode[$dlv_exName] : ''; //택배사코드 참고(https://manual.inicis.com/code/#gls)
$exName = $dlv_exName;
$charge = "SH"; //배송비 지급형태 ("SH":판매자부담, "BH":구매자부담)
$invoiceDay = G5_TIME_YMDHIS; //배송등록 확인일자 (String 으로 timestamp 사용 가능)
$sendName = $od['od_name'];
$sendTel = $od['od_tel'];
$sendPost = $od['od_zip1'].$od['od_zip2'];
$sendAddr1 = $od['od_addr1'].' '.$od['od_addr2'];
$recvName = $od['od_b_name'];
$recvTel = $od['od_b_tel'];
$recvPost = $od['od_b_zip1'].$od['od_b_zip2'];
$recvAddr = $od['od_b_addr1'].($od['od_b_addr2'] ? ' ' : '').$od['od_b_addr2'];
if(!$exCode)
$exCode = '9999';
// hash => INIAPIKey + type + timestamp + clientIp + mid + oid + tid + price
$plainText = (string)$key.(string)$type.(string)$timestamp.(string)$clientIp.(string)$mid.(string)$oid.(string)$tid.(string)$price;
// hash 암호화
$hashData = hash("sha512", $plainText);
//step2. key=value 로 post 요청
$data = array(
'type' => $type,
'mid' => $mid,
'clientIp' => $clientIp,
'timestamp' => $timestamp,
'tid' => $tid,
'oid' => $oid,
'price' => $price,
'report' => $report,
'invoice' => $invoice,
'registName' => $registName,
'exCode' => $exCode,
'exName' => $exName,
'charge' => $charge,
'invoiceDay' => $invoiceDay,
'sendName' => $sendName,
'sendTel' => $sendTel,
'sendPost' => $sendPost,
'sendAddr1' => $sendAddr1,
'recvName' => $recvName,
'recvTel' => $recvTel,
'recvPost' => $recvPost,
'recvAddr' => $recvAddr,
'hashData'=> $hashData
);
// Request URL
$url = "https://iniapi.inicis.com/api/v1/escrow";
$ch = curl_init(); // curl 초기화
curl_setopt($ch, CURLOPT_URL, $url); // 전송 URL 지정하기
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 요청 결과를 문자열로 반환
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); // connection timeout 10초
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); // POST data
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // (※ 로컬 테스트에서만 사용) 원격 서버의 인증서가 유효한지 검사 안함
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded; charset=utf-8')); // 전송헤더 설정
curl_setopt($ch, CURLOPT_POST, 1); // post 전송
$response = curl_exec($ch);
curl_close($ch);
//step3. 요청 결과
$ini_result = json_decode($response, true);
/**********************
* 4. 배송 등록 결과 *
**********************/
$resultCode = $ini_result['resultCode']; // 결과코드 ("00"이면 지불 성공)
$resultMsg = $ini_result['resultMsg']; // 결과내용 (지불결과에 대한 설명)
$dlv_date = $ini_result['resultDate'];
$dlv_time = $ini_result['resultTime'];
+61
View File
@@ -0,0 +1,61 @@
<?php
if (!defined("_GNUBOARD_")) exit; // 개별 페이지 접근 불가
/*******************************************************************
* 7. DB연동 실패 시 강제취소 *
* *
* 지불 결과를 DB 등에 저장하거나 기타 작업을 수행하다가 실패하는 *
* 경우, 아래의 코드를 참조하여 이미 지불된 거래를 취소하는 코드를 *
* 작성합니다. *
*******************************************************************/
$cancelFlag = "true";
// $cancelFlag를 "true"로 변경하는 condition 판단은 개별적으로
// 수행하여 주십시오.
if($cancelFlag == "true")
{
if( isset($is_noti_pay) && $is_noti_pay ){
return;
}
include_once(G5_SHOP_PATH.'/settle_inicis.inc.php');
if( get_session('ss_order_id') && $tno ){
$ini_oid = preg_replace('/[^a-z0-9_\-]/i', '', get_session('ss_order_id'));
$tno = preg_replace('/[^a-z0-9_\-]/i', '', $tno);
$sql = "select oid from {$g5['g5_shop_inicis_log_table']} where oid = '$ini_oid' and P_TID = '$tno' ";
$exists_log = sql_fetch($sql);
if( $exists_log['oid'] ){
$sql = " update {$g5['g5_shop_inicis_log_table']}
set P_STATUS = 'cancel',
P_AUTH_DT = '".preg_replace('/[^0-9]/', '', G5_TIME_YMDHIS)."' where oid = '$ini_oid' and P_TID = '$tno' ";
} else {
$sql = " insert into {$g5['g5_shop_inicis_log_table']}
set oid = '$ini_oid',
P_TID = '$tno',
P_STATUS = 'cancel',
P_AUTH_DT = '".preg_replace('/[^0-9]/', '', G5_TIME_YMDHIS)."' ";
}
sql_query($sql, false);
}
$ini_paymethod = get_type_inicis_paymethod($od_settle_case);
if ($ini_paymethod){
$args = array(
'paymethod' => $ini_paymethod,
'tid' => $tno,
'msg' => 'DB FAIL' // 취소사유
);
$response = inicis_tid_cancel($args);
}
}
+235
View File
@@ -0,0 +1,235 @@
<?php
include_once('./_common.php');
include_once(G5_SHOP_PATH.'/settle_inicis.inc.php');
require_once(G5_SHOP_PATH.'/inicis/libs/HttpClient.php');
require_once(G5_SHOP_PATH.'/inicis/libs/json_lib.php');
require_once(G5_SHOP_PATH.'/inicis/libs/properties.php');
$inicis_pay_result = false;
$prop = new properties();
try {
//#############################
// 인증결과 파라미터 일괄 수신
//#############################
// $var = $_REQUEST["data"];
//#####################
// 인증이 성공일 경우만
//#####################
if (isset($_REQUEST['resultCode']) && strcmp('0000', $_REQUEST['resultCode']) == 0) {
//############################################
// 1.전문 필드 값 설정(***가맹점 개발수정***)
//############################################
$charset = 'UTF-8'; // 리턴형식[UTF-8,EUC-KR](가맹점 수정후 고정)
$format = 'JSON'; // 리턴형식[XML,JSON,NVP](가맹점 수정후 고정)
// 추가적 noti가 필요한 경우(필수아님, 공백일 경우 미발송, 승인은 성공시, 실패시 모두 Noti발송됨) 미사용
//String notiUrl = "";
$authToken = $_REQUEST['authToken']; // 취소 요청 tid에 따라서 유동적(가맹점 수정후 고정)
$authUrl = $_REQUEST['authUrl']; // 승인요청 API url(수신 받은 값으로 설정, 임의 세팅 금지)
$netCancel = $_REQUEST['netCancelUrl']; // 망취소 API url(수신 받은f값으로 설정, 임의 세팅 금지)
///$mKey = $util->makeHash(signKey, "sha256"); // 가맹점 확인을 위한 signKey를 해시값으로 변경 (SHA-256방식 사용)
$mKey = hash("sha256", $signKey);
//##########################################################################
// 승인요청 API url (authUrl) 리스트 는 properties 에 세팅하여 사용합니다.
// idc_name 으로 수신 받은 센터 네임을 properties 에서 include 하여 승인요청하시면 됩니다.
//##########################################################################
$idc_name = $_REQUEST["idc_name"];
$authUrl = $prop->getAuthUrl($idc_name);
if (strcmp($authUrl, $_REQUEST["authUrl"]) != 0) {
die("authUrl check Fail\n");
}
//#####################
// 2.signature 생성
//#####################
$signParam['authToken'] = $authToken; // 필수
$signParam['timestamp'] = $timestamp; // 필수
// signature 데이터 생성 (모듈에서 자동으로 signParam을 알파벳 순으로 정렬후 NVP 방식으로 나열해 hash)
$signature = $util->makeSignature($signParam);
//#####################
// 3.API 요청 전문 생성
//#####################
$authMap['mid'] = $mid; // 필수
$authMap['authToken'] = $authToken; // 필수
$authMap['signature'] = $signature; // 필수
$authMap['timestamp'] = $timestamp; // 필수
$authMap['charset'] = $charset; // default=UTF-8
$authMap['format'] = $format; // default=XML
//if(null != notiUrl && notiUrl.length() > 0){
// authMap.put("notiUrl" ,notiUrl);
//}
try {
$httpUtil = new HttpClient();
//#####################
// 4.API 통신 시작
//#####################
$authResultString = "";
if ($httpUtil->processHTTP($authUrl, $authMap)) {
$authResultString = $httpUtil->body;
} else {
echo "Http Connect Error\n";
echo $httpUtil->errormsg;
throw new Exception("Http Connect Error");
}
//############################################################
//5.API 통신결과 처리(***가맹점 개발수정***)
//############################################################
$resultMap = json_decode($authResultString, true);
$tid = $resultMap['tid'];
$oid = preg_replace('/[^A-Za-z0-9\-_]/', '', $resultMap['MOID']);
/************************* 결제보안 추가 2016-05-18 START ****************************/
$secureMap['mid'] = $mid; //mid
$secureMap['tstamp'] = $timestamp; //timestemp
$secureMap['MOID'] = $resultMap['MOID']; //MOID
$secureMap['TotPrice'] = $resultMap['TotPrice']; //TotPrice
// signature 데이터 생성
$secureSignature = $util->makeSignatureAuth($secureMap);
/************************* 결제보안 추가 2016-05-18 END ****************************/
$sql = " select * from {$g5['g5_shop_order_data_table']} where od_id = '$oid' ";
$row = sql_fetch($sql);
$data = isset($row['dt_data']) ? unserialize(base64_decode($row['dt_data'])) : array();
if(isset($data['pp_id']) && $data['pp_id']) {
$page_return_url = G5_SHOP_URL.'/personalpayform.php?pp_id='.$data['pp_id'];
} else {
$page_return_url = G5_SHOP_URL.'/orderform.php';
if(get_session('ss_direct'))
$page_return_url .= '?sw_direct=1';
}
if ((strcmp('0000', $resultMap['resultCode']) == 0) && (strcmp($secureSignature, $resultMap['authSignature']) == 0) ) { //결제보안 추가 2016-05-18
/* * ***************************************************************************
* 여기에 가맹점 내부 DB에 결제 결과를 반영하는 관련 프로그램 코드를 구현한다.
[중요!] 승인내용에 이상이 없음을 확인한 뒤 가맹점 DB에 해당건이 정상처리 되었음을 반영함
처리중 에러 발생시 망취소를 한다.
* **************************************************************************** */
//최종결제요청 결과 성공 DB처리
$tno = $resultMap['tid'];
$amount = $resultMap['TotPrice'];
$app_time = $resultMap['applDate'].$resultMap['applTime'];
$pay_method = $resultMap['payMethod'];
$pay_type = $PAY_METHOD[$pay_method];
$depositor = isset($resultMap['VACT_InputName']) ? $resultMap['VACT_InputName'] : '';
$commid = '';
$mobile_no = isset($resultMap['HPP_Num']) ? $resultMap['HPP_Num'] : '';
$app_no = isset($resultMap['applNum']) ? $resultMap['applNum'] : '';
$card_name = isset($resultMap['CARD_Code']) ? $CARD_CODE[$resultMap['CARD_Code']] : '';
switch($pay_type) {
case '계좌이체':
$bank_name = isset($BANK_CODE[$resultMap['ACCT_BankCode']]) ? $BANK_CODE[$resultMap['ACCT_BankCode']] : '';
if ($default['de_escrow_use'] == 1)
$escw_yn = 'Y';
break;
case '가상계좌':
$bankname = isset($BANK_CODE[$resultMap['VACT_BankCode']]) ? $BANK_CODE[$resultMap['VACT_BankCode']] : '';
$account = $resultMap['VACT_Num'].' '.$resultMap['VACT_Name'];
$app_no = $resultMap['VACT_Num'];
if ($default['de_escrow_use'] == 1)
$escw_yn = 'Y';
break;
default:
break;
}
$inicis_pay_result = true;
} else {
$s = '(오류코드:'.$resultMap['resultCode'].') '.$resultMap['resultMsg'];
alert($s, $page_return_url);
}
// 수신결과를 파싱후 resultCode가 "0000"이면 승인성공 이외 실패
// 가맹점에서 스스로 파싱후 내부 DB 처리 후 화면에 결과 표시
// payViewType을 popup으로 해서 결제를 하셨을 경우
// 내부처리후 스크립트를 이용해 opener의 화면 전환처리를 하세요
//throw new Exception("강제 Exception");
} catch (Exception $e) {
// $s = $e->getMessage() . ' (오류코드:' . $e->getCode() . ')';
//####################################
// 실패시 처리(***가맹점 개발수정***)
//####################################
//---- db 저장 실패시 등 예외처리----//
$s = $e->getMessage() . ' (오류코드:' . $e->getCode() . ')';
echo $s;
//#####################
// 망취소 API
//#####################
$netcancelResultString = ""; // 망취소 요청 API url(고정, 임의 세팅 금지)
$netCancel = $prop->getNetCancel($idc_name);
if (strcmp($netCancel, $_REQUEST["netCancelUrl"]) == 0) {
if ($httpUtil->processHTTP($netCancel, $authMap)) {
$netcancelResultString = $httpUtil->body;
} else {
echo "Http Connect Error\n";
echo $httpUtil->errormsg;
throw new Exception("Http Connect Error");
}
echo "<br/>## 망취소 API 결과 ##<br/>";
/*##XML output##*/
//$netcancelResultString = str_replace("<", "&lt;", $$netcancelResultString);
//$netcancelResultString = str_replace(">", "&gt;", $$netcancelResultString);
// 취소 결과 확인
echo "<p>". $netcancelResultString . "</p>";
}
}
} else {
//#############
// 인증 실패시
//#############
echo "<br/>";
echo "####인증실패####";
ob_start();
$debug_msg = ob_get_contents();
ob_clean();
echo "<pre>" . strip_tags($debug_msg) . "</pre>";
}
} catch (Exception $e) {
$s = $e->getMessage() . ' (오류코드:' . $e->getCode() . ')';
echo $s;
}
if( !$inicis_pay_result ){
die("<br><br>결제 에러가 일어났습니다. 에러 이유는 위와 같습니다.");
}
+81
View File
@@ -0,0 +1,81 @@
<?php
include_once('./_common.php');
include_once(G5_SHOP_PATH.'/settle_inicis.inc.php');
require_once(G5_SHOP_PATH.'/inicis/libs/HttpClient.php');
require_once(G5_SHOP_PATH.'/inicis/libs/json_lib.php');
@header("Progma:no-cache");
@header("Cache-Control:no-cache,must-revalidate");
$request_mid = isset($_POST['mid']) ? clean_xss_tags($_POST['mid']) : '';
if( ($request_mid != $default['de_inicis_mid']) ){
alert("요청된 mid 와 설정된 mid 가 틀립니다.");
}
$orderNumber = isset($_POST['orderNumber']) ? preg_replace("/[ #\&\+%@=\/\\\:;,\.'\"\^`~|\!\?\*$#<>()\[\]\{\}]/i", "", strip_tags($_POST['orderNumber'])) : 0;
$session_order_num = get_session('ss_order_inicis_id');
if( !$orderNumber ){
alert("주문번호가 없습니다.");
}
$sql = " select * from {$g5['g5_shop_order_data_table']} where od_id = '$orderNumber' ";
$row = sql_fetch($sql);
if( empty($row) ){
alert("임시 주문정보가 저장되지 않았습니다.");
}
$data = unserialize(base64_decode($row['dt_data']));
$params = array();
$var_datas = array();
foreach($data as $key=>$value) {
if(is_array($value)) {
foreach($value as $k=>$v) {
$_POST[$key][$k] = $params[$key][$k] = clean_xss_tags(strip_tags($v));
}
} else {
if(in_array($key, array('od_memo'))){
$_POST[$key] = $params[$key] = clean_xss_tags(strip_tags($value), 0, 0, 0, 0);
} else {
$_POST[$key] = $params[$key] = clean_xss_tags(strip_tags($value));
}
}
}
if(isset($data['pp_id']) && $data['pp_id']) { //개인결제
foreach($params as $key=>$value){
if( in_array($key, array('pp_name', 'pp_email', 'pp_hp', 'pp_settle_case')) ){
$var_datas[$key] = $value;
$$key = $value;
}
}
include_once(G5_SHOP_PATH.'/personalpayformupdate.php');
} else { //상점주문
foreach($params as $key=>$value){
if( in_array($key, array('od_price', 'od_name', 'od_tel', 'od_hp', 'od_email', 'od_memo', 'od_settle_case', 'max_temp_point', 'od_temp_point', 'od_bank_account', 'od_deposit_name', 'od_test', 'od_ip', 'od_zip', 'od_addr1', 'od_addr2', 'od_addr3', 'od_addr_jibeon', 'od_b_name', 'od_b_tel', 'od_b_hp', 'od_b_addr1', 'od_b_addr2', 'od_b_addr3', 'od_b_addr_jibeon', 'od_b_zip', 'od_send_cost', 'od_send_cost2', 'od_hope_date')) ){
$var_datas[$key] = $value;
$$key = $value;
}
}
$od_send_cost = (int) $_POST['od_send_cost'];
$od_send_cost2 = (int) $_POST['od_send_cost2'];
include_once(G5_SHOP_PATH.'/orderformupdate.php');
}
+99
View File
@@ -0,0 +1,99 @@
<?php
class CreateIdModule {
function makeTid($payMetod, $mid, $mobileType) {
date_default_timezone_set('Asia/Seoul');
$date = new DateTime();
$prefix = "";
if ($mobileType) {
$prefix = "StdMX_";
} else {
$prefix = "Stdpay";
}
/////////////
list($usec, $sec) = explode(" ", microtime());
$time = date("YmdHis", $sec) . intval(round($usec * 1000));
if (strlen($time) == 17) {
} elseif (strlen($time) == 16) {
$time = $time . "0";
} else {
$time = $time . "00";
}
/////////////
$tid = $prefix . $this->getPGID($payMetod) . $mid . $time . $this->makeRandNum();
return $tid;
}
function getPGID($payMethod) {
$pgid = "";
if ($payMethod == "Card") {
$pgid = "CARD";
} elseif ($payMethod == "Account") {
$pgid = "ACCT";
} elseif ($payMethod == "DirectBank") {
$pgid = "DBNK";
} elseif ($payMethod == "OCBPoint") {
$pgid = "OCBP";
} elseif ($payMethod == "VCard") {
$pgid = "ISP_";
} elseif ($payMethod == "HPP") {
$pgid = "HPP_";
} elseif ($payMethod == "Nemo") {
$pgid = "NEMO";
} elseif ($payMethod == "ArsBill") {
$pgid = "ARSB";
} elseif ($payMethod == "PhoneBill") {
$pgid = "PHNB";
} elseif ($payMethod == "Ars1588Bill") {
$pgid = "1588";
} elseif ($payMethod == "VBank") {
$pgid = "VBNK";
} elseif ($payMethod == "Culture") {
$pgid = "CULT";
} elseif ($payMethod == "CMS") {
$pgid = "CMS_";
} elseif ($payMethod == "AUTH") {
$pgid = "AUTH";
} elseif ($payMethod == "INIcard") {
$pgid = "INIC";
} elseif ($payMethod == "MDX") {
$pgid = "MDX_";
} elseif ($payMethod == "CASH") {
$pgid = "CASH";
} elseif (strlen($payMethod) > 4) {
$pgid = strtoupper($payMethod);
$pgid = substr($pgid, 0, 4);
} else {
$pgid = trim($pgid);
}
return $pgid;
}
//랜덤 숫자 생성
function makeRandNum() {
$strNum = "";
$randNum = rand(0, 300);
if ($randNum < 10) {
$strNum = $strNum . "00" . $randNum;
} elseif ($randNum < 100) {
$strNum = $strNum . "0" . $randNum;
} else {
$strNum = $randNum;
}
return $strNum;
}
}
+154
View File
@@ -0,0 +1,154 @@
<?php
define("CONNECT_TIMEOUT", 5);
define("READ_TIMEOUT", 15);
//$explode_data = explode('/', $P_REQ_URL);
//$host = $explode_data[2];
//$path = "/" . $explode_data[3] . "/" . $explode_data[4];
class HttpClient {
var $sock = 0;
var $ssl;
var $host;
var $port;
var $path;
var $status;
var $headers = "";
var $body = "";
var $reqeust;
var $errorcode;
var $errormsg;
function processHTTP($url, $param) {
$data = "";
foreach ($param as $key => $value) {
$key2 = urlencode($key);
$value2 = urlencode($value);
$data .= "&$key2=$value2";
}
$data = substr($data, 1); // remove leading "&"
$url_data = parse_url($url);
// host 가 .inicis.com 의 주소가 아니라면 false 반환
// [scheme] => https
// [host] => fcstdpay.inicis.com || stdpay.inicis.com || ksstdpay.inicis.com
// [path] => /api/payAuth
if (! is_inicis_url_return($url)) {
return false;
}
if ($url_data["scheme"] == "https") {
$this->ssl = "ssl://";
$this->port = 443;
}
$this->host = $url_data["host"];
/*
if (is_null($url_data["port"])) {
$this->port = "80";
} else {
$this->port = $url_data["port"];
}
*/
$this->path = $url_data["path"];
if (!$this->sock = @fsockopen($this->ssl . $this->host, $this->port, $errno, $errstr, CONNECT_TIMEOUT)) {
switch ($errno) {
case -3:
$this->errormsg = 'Socket creation failed (-3)';
case -4:
$this->errormsg = 'DNS lookup failure (-4)';
case -5:
$this->errormsg = 'Connection refused or timed out (-5)';
default:
$this->errormsg = 'Connection failed (' . $errno . ')';
$this->errormsg .= ' ' . $errstr;
}
return false;
}
$this->headers = "";
$this->body = "";
/* Write */
$request = "POST " . $this->path . " HTTP/1.0\r\n";
$request .= "Connection: close\r\n";
$request .= "Host: " . $this->host . "\r\n";
$request .= "Content-type: application/x-www-form-urlencoded\r\n";
$request .= "Content-length: " . strlen($data) . "\r\n";
$request .= "Accept: */*\r\n";
$request .= "\r\n";
$request .= $data . "\r\n";
$request .= "\r\n";
fwrite($this->sock, $request);
/* Read */
stream_set_blocking($this->sock, FALSE);
$atStart = true;
$IsHeader = true;
$timeout = false;
$start_time = time();
while (!feof($this->sock) && !$timeout) {
$line = fgets($this->sock, 4096);
$diff = time() - $start_time;
if ($diff >= READ_TIMEOUT) {
$timeout = true;
}
if ($IsHeader) {
if ($line == "") {
continue;
}
if (substr($line, 0, 2) == "\r\n") {
$IsHeader = false;
continue;
}
$this->headers .= $line;
if ($atStart) {
$atStart = false;
if (!preg_match('/HTTP\/(\\d\\.\\d)\\s*(\\d+)\\s*(.*)/', $line, $m)) {
$this->errormsg = "Status code line invalid: " . htmlentities($line) . $m[1] . $m[2] . $m[3];
fclose($this->sock);
return false;
}
$http_version = $m[1];
$this->status = $m[2];
$status_string = $m[3];
continue;
}
} else {
$this->body .= $line;
}
}
fclose($this->sock);
if ($timeout) {
$this->errorcode = READ_TIMEOUT_ERR;
$this->errormsg = "Socket Timeout(" . $diff . "SEC)";
return false;
}
return true;
// return false;
}
function getErrorCode() {
return $this->errorcode;
}
function getErrorMsg() {
return $this->errormsg;
}
function getBody() {
return $this->body;
}
}
+124
View File
@@ -0,0 +1,124 @@
<?php
class INIStdPayUtil {
function getTimestamp() {
// timezone 을 설정하지 않으면 getTimestapme() 실행시 오류가 발생한다.
// php.ini 에 timezone 설정이 되어 잇으면 아래 코드가 필요없다.
// php 5.3 이후로는 반드시 timezone 설정을 해야하기 때문에 아래 코드가 필요없을 수 있음. 나중에 확인 후 수정필요.
// 이니시스 플로우에서 timestamp 값이 중요하게 사용되는 것으로 보이기 때문에 정확한 timezone 설정후 timestamp 값이 필요하지 않을까 함.
/**********php5
date_default_timezone_set('Asia/Seoul');
$date = new DateTime();
*/
putenv('TZ=Asia/Seoul');
$milliseconds = round(microtime(true) * 1000);
$tempValue1 = round($milliseconds / 1000); //max integer 자릿수가 9이므로 뒤 3자리를 뺀다
$tempValue2 = round((float) microtime(false) * 1000); //뒤 3자리를 저장
switch (strlen($tempValue2)) {
case '3':
break;
case '2':
$tempValue2 = "0" . $tempValue2;
break;
case '1':
$tempValue2 = "00" . $tempValue2;
break;
default:
$tempValue2 = "000";
break;
}
return "" . $tempValue1 . $tempValue2;
}
/*
//*** 위변조 방지체크를 signature 생성 ***
mid, price, timestamp 3개의 키와 값을
key=value 형식으로 하여 '&'로 연결한 하여 SHA-256 Hash로 생성 된값
ex) mid=INIpayTest&price=819000&timestamp=2012-02-01 09:19:04.004
* key기준 알파벳 정렬
* timestamp는 반드시 signature생성에 사용한 timestamp 값을 timestamp input에 그데로 사용하여야함
*/
function makeSignature($signParam) {
ksort($signParam);
$string = "";
foreach ($signParam as $key => $value) {
$string .= "&$key=$value";
}
$string = substr($string, 1); // remove leading "&"
$sign = hash( "sha256", $string);
return $sign;
}
function makeHash($data, $alg) {
// $s = hash_hmac('sha256', $data, 'secret', true);
// return base64_encode($s);
///$ret = openssl_digest($data, $alg);
$ret = hash($alg, $data);
return $ret;
}
//
function makeSignatureAuth($parameters) {
if ($parameters == null || sizeof($parameters) == 0) {
throw new Exception("<p>Parameters can not be empty.</P>");
}
$stringToSign = ""; //반환용 text
$mid = $parameters["mid"]; //mid
$tstamp = $parameters["tstamp"]; //auth timestamp
$MOID = $parameters["MOID"]; //OID
$TotPrice = $parameters["TotPrice"]; //total price
$tstampKey = substr($parameters["tstamp"], strlen($parameters["tstamp"]) - 1); // timestamp 마지막 자리 1자리 숫자
switch (intval($tstampKey)){
case 1 :
$stringToSign = "MOID=" . $MOID . "&mid=" . $mid . "&tstamp=" . $tstamp ;
break;
case 2 :
$stringToSign = "MOID=" . $MOID . "&tstamp=" . $tstamp . "&mid=" . $mid ;
break;
case 3 :
$stringToSign = "mid=" . $mid . "&MOID=" . $MOID . "&tstamp=" . $tstamp ;
break;
case 4 :
$stringToSign = "mid=" . $mid . "&tstamp=" . $tstamp . "&MOID=" . $MOID ;
break;
case 5 :
$stringToSign = "tstamp=" . $tstamp . "&mid=" . $mid . "&MOID=" . $MOID ;
break;
case 6 :
$stringToSign = "tstamp=" . $tstamp . "&MOID=" . $MOID . "&mid=" . $mid ;
break;
case 7 :
$stringToSign = "TotPrice=" . $TotPrice . "&mid=" . $mid . "&tstamp=" . $tstamp ;
break;
case 8 :
$stringToSign = "TotPrice=" . $TotPrice . "&tstamp=" . $tstamp . "&mid=" . $mid ;
break;
case 9 :
$stringToSign = "TotPrice=" . $TotPrice . "&MOID=" . $MOID . "&tstamp=" . $tstamp ;
break;
case 0 :
$stringToSign = "TotPrice=" . $TotPrice . "&tstamp=" . $tstamp . "&MOID=" . $MOID ;
break;
}
$signature = hash("sha256", $stringToSign); // sha256 처리하여 hash 암호화
//$signature = $this->makeHash($stringToSign, "sha256"); // sha256 처리하여 hash 암호화
return $signature;
}
}
@@ -0,0 +1,14 @@
<?php
require_once('../libs/INIStdPayUtil.php');
$SignatureUtil = new INIStdPayUtil();
$input = "oid=" . $_REQUEST["oid"] . "&price=" . $_REQUEST["price"] . "&timestamp=" . $_REQUEST["timestamp"];
$output['signature'] = array(
///'signature' => $SignatureUtil->makeHash($input, "sha256")
'signature' => hash("sha256", $input)
);
echo json_encode($output);
+804
View File
@@ -0,0 +1,804 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* Converts to and from JSON format.
*
* JSON (JavaScript Object Notation) is a lightweight data-interchange
* format. It is easy for humans to read and write. It is easy for machines
* to parse and generate. It is based on a subset of the JavaScript
* Programming Language, Standard ECMA-262 3rd Edition - December 1999.
* This feature can also be found in Python. JSON is a text format that is
* completely language independent but uses conventions that are familiar
* to programmers of the C-family of languages, including C, C++, C#, Java,
* JavaScript, Perl, TCL, and many others. These properties make JSON an
* ideal data-interchange language.
*
* This package provides a simple encoder and decoder for JSON notation. It
* is intended for use with client-side Javascript applications that make
* use of HTTPRequest to perform server communication functions - data can
* be encoded into JSON notation for use in a client-side javascript, or
* decoded from incoming Javascript requests. JSON format is native to
* Javascript, and can be directly eval()'ed with no further parsing
* overhead
*
* All strings should be in ASCII or UTF-8 format!
*
* LICENSE: Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met: Redistributions of source code must retain the
* above copyright notice, this list of conditions and the following
* disclaimer. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
* NO EVENT SHALL CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
* @category
* @package Services_JSON
* @author Michal Migurski <mike-json@teczno.com>
* @author Matt Knapp <mdknapp[at]gmail[dot]com>
* @author Brett Stimmerman <brettstimmerman[at]gmail[dot]com>
* @copyright 2005 Michal Migurski
* @version CVS: $Id: JSON.php,v 1.31 2006/06/28 05:54:17 migurski Exp $
* @license http://www.opensource.org/licenses/bsd-license.php
* @link http://pear.php.net/pepr/pepr-proposal-show.php?id=198
*/
/**
* Marker constant for Services_JSON::decode(), used to flag stack state
*/
define('SERVICES_JSON_SLICE', 1);
/**
* Marker constant for Services_JSON::decode(), used to flag stack state
*/
define('SERVICES_JSON_IN_STR', 2);
/**
* Marker constant for Services_JSON::decode(), used to flag stack state
*/
define('SERVICES_JSON_IN_ARR', 3);
/**
* Marker constant for Services_JSON::decode(), used to flag stack state
*/
define('SERVICES_JSON_IN_OBJ', 4);
/**
* Marker constant for Services_JSON::decode(), used to flag stack state
*/
define('SERVICES_JSON_IN_CMT', 5);
/**
* Behavior switch for Services_JSON::decode()
*/
define('SERVICES_JSON_LOOSE_TYPE', 16);
/**
* Behavior switch for Services_JSON::decode()
*/
define('SERVICES_JSON_SUPPRESS_ERRORS', 32);
/**
* Converts to and from JSON format.
*
* Brief example of use:
*
* <code>
* // create a new instance of Services_JSON
* $json = new Services_JSON();
*
* // convert a complexe value to JSON notation, and send it to the browser
* $value = array('foo', 'bar', array(1, 2, 'baz'), array(3, array(4)));
* $output = $json->encode($value);
*
* print($output);
* // prints: ["foo","bar",[1,2,"baz"],[3,[4]]]
*
* // accept incoming POST data, assumed to be in JSON notation
* $input = file_get_contents('php://input', 1000000);
* $value = $json->decode($input);
* </code>
*/
class Services_JSON
{
/**
* constructs a new JSON instance
*
* @param int $use object behavior flags; combine with boolean-OR
*
* possible values:
* - SERVICES_JSON_LOOSE_TYPE: loose typing.
* "{...}" syntax creates associative arrays
* instead of objects in decode().
* - SERVICES_JSON_SUPPRESS_ERRORS: error suppression.
* Values which can't be encoded (e.g. resources)
* appear as NULL instead of throwing errors.
* By default, a deeply-nested resource will
* bubble up with an error, so all return values
* from encode() should be checked with isError()
*/
function Services_JSON($use = 0)
{
$this->use = $use;
}
/**
* convert a string from one UTF-16 char to one UTF-8 char
*
* Normally should be handled by mb_convert_encoding, but
* provides a slower PHP-only method for installations
* that lack the multibye string extension.
*
* @param string $utf16 UTF-16 character
* @return string UTF-8 character
* @access private
*/
function utf162utf8($utf16)
{
// oh please oh please oh please oh please oh please
if(function_exists('mb_convert_encoding')) {
return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16');
}
$bytes = (ord($utf16[0]) << 8) | ord($utf16[1]);
switch(true) {
case ((0x7F & $bytes) == $bytes):
// this case should never be reached, because we are in ASCII range
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0x7F & $bytes);
case (0x07FF & $bytes) == $bytes:
// return a 2-byte UTF-8 character
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0xC0 | (($bytes >> 6) & 0x1F))
. chr(0x80 | ($bytes & 0x3F));
case (0xFFFF & $bytes) == $bytes:
// return a 3-byte UTF-8 character
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0xE0 | (($bytes >> 12) & 0x0F))
. chr(0x80 | (($bytes >> 6) & 0x3F))
. chr(0x80 | ($bytes & 0x3F));
}
// ignoring UTF-32 for now, sorry
return '';
}
/**
* convert a string from one UTF-8 char to one UTF-16 char
*
* Normally should be handled by mb_convert_encoding, but
* provides a slower PHP-only method for installations
* that lack the multibye string extension.
*
* @param string $utf8 UTF-8 character
* @return string UTF-16 character
* @access private
*/
function utf82utf16($utf8)
{
// oh please oh please oh please oh please oh please
if(function_exists('mb_convert_encoding')) {
return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8');
}
switch(strlen($utf8)) {
case 1:
// this case should never be reached, because we are in ASCII range
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return $utf8;
case 2:
// return a UTF-16 character from a 2-byte UTF-8 char
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0x07 & (ord($utf8[0]) >> 2))
. chr((0xC0 & (ord($utf8[0]) << 6))
| (0x3F & ord($utf8[1])));
case 3:
// return a UTF-16 character from a 3-byte UTF-8 char
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr((0xF0 & (ord($utf8[0]) << 4))
| (0x0F & (ord($utf8[1]) >> 2)))
. chr((0xC0 & (ord($utf8[1]) << 6))
| (0x7F & ord($utf8[2])));
}
// ignoring UTF-32 for now, sorry
return '';
}
/**
* encodes an arbitrary variable into JSON format
*
* @param mixed $var any number, boolean, string, array, or object to be encoded.
* see argument 1 to Services_JSON() above for array-parsing behavior.
* if var is a strng, note that encode() always expects it
* to be in ASCII or UTF-8 format!
*
* @return mixed JSON string representation of input var or an error if a problem occurs
* @access public
*/
function encode($var)
{
switch (gettype($var)) {
case 'boolean':
return $var ? 'true' : 'false';
case 'NULL':
return 'null';
case 'integer':
return (int) $var;
case 'double':
case 'float':
return (float) $var;
case 'string':
// STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT
$ascii = '';
$strlen_var = strlen($var);
/*
* Iterate over every character in the string,
* escaping with a slash or encoding to UTF-8 where necessary
*/
for ($c = 0; $c < $strlen_var; ++$c) {
$ord_var_c = ord($var[$c]);
switch (true) {
case $ord_var_c == 0x08:
$ascii .= '\b';
break;
case $ord_var_c == 0x09:
$ascii .= '\t';
break;
case $ord_var_c == 0x0A:
$ascii .= '\n';
break;
case $ord_var_c == 0x0C:
$ascii .= '\f';
break;
case $ord_var_c == 0x0D:
$ascii .= '\r';
break;
case $ord_var_c == 0x22:
case $ord_var_c == 0x2F:
case $ord_var_c == 0x5C:
// double quote, slash, slosh
$ascii .= '\\'.$var[$c];
break;
case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
// characters U-00000000 - U-0000007F (same as ASCII)
$ascii .= $var[$c];
break;
case (($ord_var_c & 0xE0) == 0xC0):
// characters U-00000080 - U-000007FF, mask 110XXXXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c, ord($var[$c + 1]));
$c += 1;
$utf16 = $this->utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ord_var_c & 0xF0) == 0xE0):
// characters U-00000800 - U-0000FFFF, mask 1110XXXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($var[$c + 1]),
ord($var[$c + 2]));
$c += 2;
$utf16 = $this->utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ord_var_c & 0xF8) == 0xF0):
// characters U-00010000 - U-001FFFFF, mask 11110XXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($var[$c + 1]),
ord($var[$c + 2]),
ord($var[$c + 3]));
$c += 3;
$utf16 = $this->utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ord_var_c & 0xFC) == 0xF8):
// characters U-00200000 - U-03FFFFFF, mask 111110XX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($var[$c + 1]),
ord($var[$c + 2]),
ord($var[$c + 3]),
ord($var[$c + 4]));
$c += 4;
$utf16 = $this->utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ord_var_c & 0xFE) == 0xFC):
// characters U-04000000 - U-7FFFFFFF, mask 1111110X
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($var[$c + 1]),
ord($var[$c + 2]),
ord($var[$c + 3]),
ord($var[$c + 4]),
ord($var[$c + 5]));
$c += 5;
$utf16 = $this->utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
}
}
return '"'.$ascii.'"';
case 'array':
/*
* As per JSON spec if any array key is not an integer
* we must treat the the whole array as an object. We
* also try to catch a sparsely populated associative
* array with numeric keys here because some JS engines
* will create an array with empty indexes up to
* max_index which can cause memory issues and because
* the keys, which may be relevant, will be remapped
* otherwise.
*
* As per the ECMA and JSON specification an object may
* have any string as a property. Unfortunately due to
* a hole in the ECMA specification if the key is a
* ECMA reserved word or starts with a digit the
* parameter is only accessible using ECMAScript's
* bracket notation.
*/
// treat as a JSON object
if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) {
$properties = array_map(array($this, 'name_value'),
array_keys($var),
array_values($var));
foreach($properties as $property) {
if(Services_JSON::isError($property)) {
return $property;
}
}
return '{' . join(',', $properties) . '}';
}
// treat it like a regular array
$elements = array_map(array($this, 'encode'), $var);
foreach($elements as $element) {
if(Services_JSON::isError($element)) {
return $element;
}
}
return '[' . join(',', $elements) . ']';
case 'object':
$vars = get_object_vars($var);
$properties = array_map(array($this, 'name_value'),
array_keys($vars),
array_values($vars));
foreach($properties as $property) {
if(Services_JSON::isError($property)) {
return $property;
}
}
return '{' . join(',', $properties) . '}';
default:
return ($this->use & SERVICES_JSON_SUPPRESS_ERRORS)
? 'null'
: new Services_JSON_Error(gettype($var)." can not be encoded as JSON string");
}
}
/**
* array-walking function for use in generating JSON-formatted name-value pairs
*
* @param string $name name of key to use
* @param mixed $value reference to an array element to be encoded
*
* @return string JSON-formatted name-value pair, like '"name":value'
* @access private
*/
function name_value($name, $value)
{
$encoded_value = $this->encode($value);
if(Services_JSON::isError($encoded_value)) {
return $encoded_value;
}
return $this->encode(strval($name)) . ':' . $encoded_value;
}
/**
* reduce a string by removing leading and trailing comments and whitespace
*
* @param $str string string value to strip of comments and whitespace
*
* @return string string value stripped of comments and whitespace
* @access private
*/
function reduce_string($str)
{
$str = preg_replace(array(
// eliminate single line comments in '// ...' form
'#^\s*//(.+)$#m',
// eliminate multi-line comments in '/* ... */' form, at start of string
'#^\s*/\*(.+)\*/#Us',
// eliminate multi-line comments in '/* ... */' form, at end of string
'#/\*(.+)\*/\s*$#Us'
), '', $str);
// eliminate extraneous space
return trim($str);
}
/**
* decodes a JSON string into appropriate variable
*
* @param string $str JSON-formatted string
*
* @return mixed number, boolean, string, array, or object
* corresponding to given JSON input string.
* See argument 1 to Services_JSON() above for object-output behavior.
* Note that decode() always returns strings
* in ASCII or UTF-8 format!
* @access public
*/
function decode($str)
{
$str = $this->reduce_string($str);
switch (strtolower($str)) {
case 'true':
return true;
case 'false':
return false;
case 'null':
return null;
default:
$m = array();
if (is_numeric($str)) {
// Lookie-loo, it's a number
// This would work on its own, but I'm trying to be
// good about returning integers where appropriate:
// return (float)$str;
// Return float or int, as appropriate
return ((float)$str == (integer)$str)
? (integer)$str
: (float)$str;
} elseif (preg_match('/^("|\').*(\1)$/s', $str, $m) && $m[1] == $m[2]) {
// STRINGS RETURNED IN UTF-8 FORMAT
$delim = substr($str, 0, 1);
$chrs = substr($str, 1, -1);
$utf8 = '';
$strlen_chrs = strlen($chrs);
for ($c = 0; $c < $strlen_chrs; ++$c) {
$substr_chrs_c_2 = substr($chrs, $c, 2);
$ord_chrs_c = ord($chrs[$c]);
switch (true) {
case $substr_chrs_c_2 == '\b':
$utf8 .= chr(0x08);
++$c;
break;
case $substr_chrs_c_2 == '\t':
$utf8 .= chr(0x09);
++$c;
break;
case $substr_chrs_c_2 == '\n':
$utf8 .= chr(0x0A);
++$c;
break;
case $substr_chrs_c_2 == '\f':
$utf8 .= chr(0x0C);
++$c;
break;
case $substr_chrs_c_2 == '\r':
$utf8 .= chr(0x0D);
++$c;
break;
case $substr_chrs_c_2 == '\\"':
case $substr_chrs_c_2 == '\\\'':
case $substr_chrs_c_2 == '\\\\':
case $substr_chrs_c_2 == '\\/':
if (($delim == '"' && $substr_chrs_c_2 != '\\\'') ||
($delim == "'" && $substr_chrs_c_2 != '\\"')) {
$utf8 .= $chrs[++$c];
}
break;
case preg_match('/\\\u[0-9A-F]{4}/i', substr($chrs, $c, 6)):
// single, escaped unicode character
$utf16 = chr(hexdec(substr($chrs, ($c + 2), 2)))
. chr(hexdec(substr($chrs, ($c + 4), 2)));
$utf8 .= $this->utf162utf8($utf16);
$c += 5;
break;
case ($ord_chrs_c >= 0x20) && ($ord_chrs_c <= 0x7F):
$utf8 .= $chrs[$c];
break;
case ($ord_chrs_c & 0xE0) == 0xC0:
// characters U-00000080 - U-000007FF, mask 110XXXXX
//see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $c, 2);
++$c;
break;
case ($ord_chrs_c & 0xF0) == 0xE0:
// characters U-00000800 - U-0000FFFF, mask 1110XXXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $c, 3);
$c += 2;
break;
case ($ord_chrs_c & 0xF8) == 0xF0:
// characters U-00010000 - U-001FFFFF, mask 11110XXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $c, 4);
$c += 3;
break;
case ($ord_chrs_c & 0xFC) == 0xF8:
// characters U-00200000 - U-03FFFFFF, mask 111110XX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $c, 5);
$c += 4;
break;
case ($ord_chrs_c & 0xFE) == 0xFC:
// characters U-04000000 - U-7FFFFFFF, mask 1111110X
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $c, 6);
$c += 5;
break;
}
}
return $utf8;
} elseif (preg_match('/^\[.*\]$/s', $str) || preg_match('/^\{.*\}$/s', $str)) {
// array, or object notation
if ($str[0] == '[') {
$stk = array(SERVICES_JSON_IN_ARR);
$arr = array();
} else {
if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
$stk = array(SERVICES_JSON_IN_OBJ);
$obj = array();
} else {
$stk = array(SERVICES_JSON_IN_OBJ);
$obj = new stdClass();
}
}
array_push($stk, array('what' => SERVICES_JSON_SLICE,
'where' => 0,
'delim' => false));
$chrs = substr($str, 1, -1);
$chrs = $this->reduce_string($chrs);
if ($chrs == '') {
if (reset($stk) == SERVICES_JSON_IN_ARR) {
return $arr;
} else {
return $obj;
}
}
//print("\nparsing {$chrs}\n");
$strlen_chrs = strlen($chrs);
for ($c = 0; $c <= $strlen_chrs; ++$c) {
$top = end($stk);
$substr_chrs_c_2 = substr($chrs, $c, 2);
if (($c == $strlen_chrs) || (($chrs[$c] == ',') && ($top['what'] == SERVICES_JSON_SLICE))) {
// found a comma that is not inside a string, array, etc.,
// OR we've reached the end of the character list
$slice = substr($chrs, $top['where'], ($c - $top['where']));
array_push($stk, array('what' => SERVICES_JSON_SLICE, 'where' => ($c + 1), 'delim' => false));
//print("Found split at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
if (reset($stk) == SERVICES_JSON_IN_ARR) {
// we are in an array, so just push an element onto the stack
array_push($arr, $this->decode($slice));
} elseif (reset($stk) == SERVICES_JSON_IN_OBJ) {
// we are in an object, so figure
// out the property name and set an
// element in an associative array,
// for now
$parts = array();
if (preg_match('/^\s*(["\'].*[^\\\]["\'])\s*:\s*(\S.*),?$/Uis', $slice, $parts)) {
// "name":value pair
$key = $this->decode($parts[1]);
$val = $this->decode($parts[2]);
if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
$obj[$key] = $val;
} else {
$obj->$key = $val;
}
} elseif (preg_match('/^\s*(\w+)\s*:\s*(\S.*),?$/Uis', $slice, $parts)) {
// name:value pair, where name is unquoted
$key = $parts[1];
$val = $this->decode($parts[2]);
if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
$obj[$key] = $val;
} else {
$obj->$key = $val;
}
}
}
} elseif ((($chrs[$c] == '"') || ($chrs[$c] == "'")) && ($top['what'] != SERVICES_JSON_IN_STR)) {
// found a quote, and we are not inside a string
array_push($stk, array('what' => SERVICES_JSON_IN_STR, 'where' => $c, 'delim' => $chrs[$c]));
//print("Found start of string at {$c}\n");
} elseif (($chrs[$c] == $top['delim']) &&
($top['what'] == SERVICES_JSON_IN_STR) &&
((strlen(substr($chrs, 0, $c)) - strlen(rtrim(substr($chrs, 0, $c), '\\'))) % 2 != 1)) {
// found a quote, we're in a string, and it's not escaped
// we know that it's not escaped becase there is _not_ an
// odd number of backslashes at the end of the string so far
array_pop($stk);
//print("Found end of string at {$c}: ".substr($chrs, $top['where'], (1 + 1 + $c - $top['where']))."\n");
} elseif (($chrs[$c] == '[') &&
in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
// found a left-bracket, and we are in an array, object, or slice
array_push($stk, array('what' => SERVICES_JSON_IN_ARR, 'where' => $c, 'delim' => false));
//print("Found start of array at {$c}\n");
} elseif (($chrs[$c] == ']') && ($top['what'] == SERVICES_JSON_IN_ARR)) {
// found a right-bracket, and we're in an array
array_pop($stk);
//print("Found end of array at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
} elseif (($chrs[$c] == '{') &&
in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
// found a left-brace, and we are in an array, object, or slice
array_push($stk, array('what' => SERVICES_JSON_IN_OBJ, 'where' => $c, 'delim' => false));
//print("Found start of object at {$c}\n");
} elseif (($chrs[$c] == '}') && ($top['what'] == SERVICES_JSON_IN_OBJ)) {
// found a right-brace, and we're in an object
array_pop($stk);
//print("Found end of object at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
} elseif (($substr_chrs_c_2 == '/*') &&
in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
// found a comment start, and we are in an array, object, or slice
array_push($stk, array('what' => SERVICES_JSON_IN_CMT, 'where' => $c, 'delim' => false));
$c++;
//print("Found start of comment at {$c}\n");
} elseif (($substr_chrs_c_2 == '*/') && ($top['what'] == SERVICES_JSON_IN_CMT)) {
// found a comment end, and we're in one now
array_pop($stk);
$c++;
for ($i = $top['where']; $i <= $c; ++$i)
$chrs = substr_replace($chrs, ' ', $i, 1);
//print("Found end of comment at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
}
}
if (reset($stk) == SERVICES_JSON_IN_ARR) {
return $arr;
} elseif (reset($stk) == SERVICES_JSON_IN_OBJ) {
return $obj;
}
}
}
}
/**
* @todo Ultimately, this should just call PEAR::isError()
*/
function isError($data, $code = null)
{
if (class_exists('pear')) {
return PEAR::isError($data, $code);
} elseif (is_object($data) && (get_class($data) == 'services_json_error' ||
is_subclass_of($data, 'services_json_error'))) {
return true;
}
return false;
}
}
if (class_exists('PEAR_Error')) {
class Services_JSON_Error extends PEAR_Error
{
function Services_JSON_Error($message = 'unknown error', $code = null,
$mode = null, $options = null, $userinfo = null)
{
parent::PEAR_Error($message, $code, $mode, $options, $userinfo);
}
}
} else {
/**
* @todo Ultimately, this class shall be descended from PEAR_Error
*/
class Services_JSON_Error
{
function Services_JSON_Error($message = 'unknown error', $code = null,
$mode = null, $options = null, $userinfo = null)
{
}
}
}
+134
View File
@@ -0,0 +1,134 @@
<?php
if (!defined('_GNUBOARD_')) exit;
function get_inicis_iniapi_key() {
global $default;
// iniapi_key 는 전체취소, 부분취소, 현금영수증, 에스크로 배송등록에 사용됨
if ($default['de_card_test']) { // 테스트결제이면
if ($default['de_inicis_mid'] === 'iniescrow0') { // 에스크로 테스트용 mid
return 'yERbIlJ3NhTeObsA';
} else if ($default['de_inicis_mid'] === 'INIpayTest'){ // 일반 테스트용 mid
return 'ItEQKi3rY7uvDS8l';
}
}
return $default['de_inicis_iniapi_key'];
}
function get_inicis_iniapi_iv() {
global $default;
// iniapi_iv 는 현금영수증 발급에 사용됨
if ($default['de_card_test']) { // 테스트결제이면
if ($default['de_inicis_mid'] === 'iniescrow0') { // 에스크로 테스트용 mid
return 'tOGDXbfoajk2DQ==';
} else if ($default['de_inicis_mid'] === 'INIpayTest'){ // 일반 테스트용 mid
return 'HYb3yQ4f65QL89==';
}
}
return $default['de_inicis_iniapi_iv'];
}
// KG 이니시스 일반 주문 취소 함수
// $args 변수의 타입은 array, $is_part 변수는 부분취소 구분 변수
function inicis_tid_cancel($args, $is_part=false){
global $default;
// step1. 요청을 위한 파라미터 설정
// 가맹점관리자 > 상점정보 > 계약정보 > 부가정보 > INIAPI key 생성조회
$key = isset($args['key']) ? $args['key'] : get_inicis_iniapi_key();
$type = "Refund"; // 고정
$paymethod = isset($args['paymethod']) ? $args['paymethod'] : "Card";
$timestamp = isset($args['timestamp']) ? $args['timestamp'] : date("YmdHis");
$clientIp = isset($args['clientIp']) ? $args['clientIp'] : $_SERVER['SERVER_ADDR'];
$mid = isset($args['mid']) ? $args['mid'] : $default['de_inicis_mid'];
$tid = $args['tid'];
$msg = $args['msg'];
// 부분취소인 경우
if ($is_part){
$type = 'PartialRefund';
$price = $args['price'];
$confirmPrice = $args['confirmPrice'];
// INIAPIKey + type + paymethod + timestamp + clientIp + mid + tid + price + confirmPrice
$hashData = hash("sha512",(string)$key.(string)$type.(string)$paymethod.(string)$timestamp.(string)$clientIp.(string)$mid.(string)$tid.(string)$price.(string)$confirmPrice); // hash 암호화
//step2. key=value 로 post 요청
$data = array(
'type' => $type,
'paymethod' => $paymethod,
'timestamp' => $timestamp,
'clientIp' => $clientIp,
'mid' => $mid,
'tid' => $tid,
'price' => $price,
'confirmPrice' => $confirmPrice,
'msg' => $msg,
'hashData'=> $hashData
);
} else {
// 전체취소인 경우
// INIAPIKey + type + paymethod + timestamp + clientIp + mid + tid
$hashData = hash("sha512", (string)$key.(string)$type.(string)$paymethod.(string)$timestamp.(string)$clientIp.(string)$mid.(string)$tid); // hash 암호화
//step2. key=value 로 post 요청
$data = array(
'type' => $type,
'paymethod' => $paymethod,
'timestamp' => $timestamp,
'clientIp' => $clientIp,
'mid' => $mid,
'tid' => $tid,
'msg' => $msg,
'hashData'=> $hashData
);
}
$url = "https://iniapi.inicis.com/api/v1/refund";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded; charset=utf-8'));
curl_setopt($ch, CURLOPT_POST, 1);
$response = curl_exec($ch);
curl_close($ch);
//step3. 요청 결과
return $response;
}
function get_type_inicis_paymethod($od_settle_case){
$ini_paymethod = '';
switch ($od_settle_case) {
case '신용카드':
case '간편결제':
$ini_paymethod = 'Card';
break;
case '가상계좌':
$ini_paymethod = 'GVacct'; // 가상계좌 (입금전, 채번취소 시 사용)
break;
case '계좌이체':
$ini_paymethod = 'Acct';
break;
case '휴대폰':
$ini_paymethod = 'HPP';
break;
}
if (! $ini_paymethod) {
if (is_inicis_order_pay($od_settle_case)) {
$ini_paymethod = 'Card';
}
}
return $ini_paymethod;
}
+28
View File
@@ -0,0 +1,28 @@
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2015-11-05
* Time: 오후 2:59
*/
if (!function_exists('json_decode')) {
function json_decode($content, $assoc=false) {
require_once 'JSON.php';
if ($assoc) {
$json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
}
else {
$json = new Services_JSON;
}
return $json->decode($content);
}
}
if (!function_exists('json_encode')) {
function json_encode($content) {
require_once 'JSON.php';
$json = new Services_JSON;
return $json->encode($content);
}
}
+42
View File
@@ -0,0 +1,42 @@
<?php
class properties {
function getAuthUrl($idc_name) {
$url = "stdpay.inicis.com/api/payAuth";
switch ($idc_name) {
case 'fc':
$authUrl = "https://fc".$url;
break;
case 'ks':
$authUrl = "https://ks".$url;
break;
case 'stg':
$authUrl = "https://stg".$url;
break;
default:
break;
}
return $authUrl;
}
function getNetCancel($idc_name) {
$url = "stdpay.inicis.com/api/netCancel";
switch ($idc_name) {
case 'fc':
$netCancel = "https://fc".$url;
break;
case 'ks':
$netCancel = "https://ks".$url;
break;
case 'stg':
$netCancel = "https://stg".$url;
break;
default:
break;
}
return $netCancel;
}
}
?>
+411
View File
@@ -0,0 +1,411 @@
<?php
/*
* Transparent SHA-256 Implementation for PHP 4 and PHP 5
*
* Author: Perry McGee (pmcgee@nanolink.ca)
* Website: http://www.nanolink.ca/pub/sha256
*
* Copyright (C) 2006,2007,2008,2009 Nanolink Solutions
*
* Created: Feb 11, 2006
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* or see <http://www.gnu.org/licenses/>.
*
* Include:
*
* require_once("[path/]sha256.inc.php");
*
* Usage Options:
*
* 1) $shaStr = hash('sha256', $string_to_hash);
*
* 2) $shaStr = sha256($string_to_hash[, bool ignore_php5_hash = false]);
*
* 3) $obj = new nanoSha2([bool $upper_case_output = false]);
* $shaStr = $obj->hash($string_to_hash[, bool $ignore_php5_hash = false]);
*
* Reference: http://csrc.nist.gov/groups/ST/toolkit/secure_hashing.html
*
* 2007-12-13: Cleaned up for initial public release
* 2008-05-10: Moved all helper functions into a class. API access unchanged.
* 2009-06-23: Created abstraction of hash() routine
* 2009-07-23: Added detection of 32 vs 64bit platform, and patches.
* Ability to define "_NANO_SHA2_UPPER" to yeild upper case hashes.
* 2009-08-01: Added ability to attempt to use mhash() prior to running pure
* php code.
* 2022-05-19: PHP 8.1 부터 deprecate 되는 mhash() 삭제
*
* NOTE: Some sporadic versions of PHP do not handle integer overflows the
* same as the majority of builds. If you get hash results of:
* 7fffffff7fffffff7fffffff7fffffff7fffffff7fffffff7fffffff7fffffff
*
* If you do not have permissions to change PHP versions (if you did
* you'd probably upgrade to PHP 5 anyway) it is advised you install a
* module that will allow you to use their hashing routines, examples are:
* - mhash module : http://ca3.php.net/mhash
* - Suhosin : http://www.hardened-php.net/suhosin/
*
* If you install the Suhosin module, this script will transparently
* use their routine and define the PHP routine as _nano_sha256().
*
* If the mhash module is present, and $ignore_php5_hash = false the
* script will attempt to use the output from mhash prior to running
* the PHP code.
*/
if (!class_exists('nanoSha2'))
{
class nanoSha2
{
// php 4 - 5 compatable class properties
var $toUpper;
var $platform;
// Php 4 - 6 compatable constructor
// PHP Deprecated: Methods with the same name as their class will not be constructors in a future version of PHP
// function nanoSha2($toUpper = false) {
function __construct($toUpper = false) {
// Determine if the caller wants upper case or not.
$this->toUpper = is_bool($toUpper)
? $toUpper
: ((defined('_NANO_SHA2_UPPER')) ? true : false);
// Deteremine if the system is 32 or 64 bit.
$tmpInt = (int)4294967295;
$this->platform = ($tmpInt > 0) ? 64 : 32;
}
// Do the SHA-256 Padding routine (make input a multiple of 512 bits)
function char_pad($str)
{
$tmpStr = $str;
$l = strlen($tmpStr)*8; // # of bits from input string
$tmpStr .= "\x80"; // append the "1" bit followed by 7 0's
$k = (512 - (($l + 8 + 64) % 512)) / 8; // # of 0 bytes to append
$k += 4; // PHP Strings will never exceed (2^31)-1, 1st 32bits of
// the 64-bit value representing $l can be all 0's
for ($x = 0; $x < $k; $x++) {
$tmpStr .= "\0";
}
// append the 32-bits representing # of bits from input string ($l)
$tmpStr .= chr((($l>>24) & 0xFF));
$tmpStr .= chr((($l>>16) & 0xFF));
$tmpStr .= chr((($l>>8) & 0xFF));
$tmpStr .= chr(($l & 0xFF));
return $tmpStr;
}
// Here are the bitwise and functions as defined in FIPS180-2 Standard
function addmod2n($x, $y, $n = 4294967296) // Z = (X + Y) mod 2^32
{
$mask = 0x80000000;
if ($x < 0) {
$x &= 0x7FFFFFFF;
$x = (float)$x + $mask;
}
if ($y < 0) {
$y &= 0x7FFFFFFF;
$y = (float)$y + $mask;
}
$r = $x + $y;
if ($r >= $n) {
while ($r >= $n) {
$r -= $n;
}
}
return (int)$r;
}
// Logical bitwise right shift (PHP default is arithmetic shift)
function SHR($x, $n) // x >> n
{
if ($n >= 32) { // impose some limits to keep it 32-bit
return (int)0;
}
if ($n <= 0) {
return (int)$x;
}
$mask = 0x40000000;
if ($x < 0) {
$x &= 0x7FFFFFFF;
$mask = $mask >> ($n-1);
return ($x >> $n) | $mask;
}
return (int)$x >> (int)$n;
}
function ROTR($x, $n) { return (int)(($this->SHR($x, $n) | ($x << (32-$n)) & 0xFFFFFFFF)); }
function Ch($x, $y, $z) { return ($x & $y) ^ ((~$x) & $z); }
function Maj($x, $y, $z) { return ($x & $y) ^ ($x & $z) ^ ($y & $z); }
function Sigma0($x) { return (int) ($this->ROTR($x, 2)^$this->ROTR($x, 13)^$this->ROTR($x, 22)); }
function Sigma1($x) { return (int) ($this->ROTR($x, 6)^$this->ROTR($x, 11)^$this->ROTR($x, 25)); }
function sigma_0($x) { return (int) ($this->ROTR($x, 7)^$this->ROTR($x, 18)^$this->SHR($x, 3)); }
function sigma_1($x) { return (int) ($this->ROTR($x, 17)^$this->ROTR($x, 19)^$this->SHR($x, 10)); }
/*
* Custom functions to provide PHP support
*/
// split a byte-string into integer array values
function int_split($input)
{
$l = strlen($input);
if ($l <= 0) {
return (int)0;
}
if (($l % 4) != 0) { // invalid input
return false;
}
for ($i = 0; $i < $l; $i += 4)
{
$int_build = (ord($input[$i]) << 24);
$int_build += (ord($input[$i+1]) << 16);
$int_build += (ord($input[$i+2]) << 8);
$int_build += (ord($input[$i+3]));
$result[] = $int_build;
}
return $result;
}
/**
* Process and return the hash.
*
* @param $str Input string to hash
* @param $ig_func Option param to ignore checking for php > 5.1.2
* @return string Hexadecimal representation of the message digest
*/
function hash($str, $ig_func = false)
{
unset($binStr); // binary representation of input string
unset($hexStr); // 256-bit message digest in readable hex format
// check for php's internal sha256 function, ignore if ig_func==true
if ($ig_func == false) {
return hash("sha256", $str, false);
}
/*
* SHA-256 Constants
* Sequence of sixty-four constant 32-bit words representing the
* first thirty-two bits of the fractional parts of the cube roots
* of the first sixtyfour prime numbers.
*/
$K = array((int)0x428a2f98, (int)0x71374491, (int)0xb5c0fbcf,
(int)0xe9b5dba5, (int)0x3956c25b, (int)0x59f111f1,
(int)0x923f82a4, (int)0xab1c5ed5, (int)0xd807aa98,
(int)0x12835b01, (int)0x243185be, (int)0x550c7dc3,
(int)0x72be5d74, (int)0x80deb1fe, (int)0x9bdc06a7,
(int)0xc19bf174, (int)0xe49b69c1, (int)0xefbe4786,
(int)0x0fc19dc6, (int)0x240ca1cc, (int)0x2de92c6f,
(int)0x4a7484aa, (int)0x5cb0a9dc, (int)0x76f988da,
(int)0x983e5152, (int)0xa831c66d, (int)0xb00327c8,
(int)0xbf597fc7, (int)0xc6e00bf3, (int)0xd5a79147,
(int)0x06ca6351, (int)0x14292967, (int)0x27b70a85,
(int)0x2e1b2138, (int)0x4d2c6dfc, (int)0x53380d13,
(int)0x650a7354, (int)0x766a0abb, (int)0x81c2c92e,
(int)0x92722c85, (int)0xa2bfe8a1, (int)0xa81a664b,
(int)0xc24b8b70, (int)0xc76c51a3, (int)0xd192e819,
(int)0xd6990624, (int)0xf40e3585, (int)0x106aa070,
(int)0x19a4c116, (int)0x1e376c08, (int)0x2748774c,
(int)0x34b0bcb5, (int)0x391c0cb3, (int)0x4ed8aa4a,
(int)0x5b9cca4f, (int)0x682e6ff3, (int)0x748f82ee,
(int)0x78a5636f, (int)0x84c87814, (int)0x8cc70208,
(int)0x90befffa, (int)0xa4506ceb, (int)0xbef9a3f7,
(int)0xc67178f2);
// Pre-processing: Padding the string
$binStr = $this->char_pad($str);
// Parsing the Padded Message (Break into N 512-bit blocks)
$M = str_split($binStr, 64);
// Set the initial hash values
$h[0] = (int)0x6a09e667;
$h[1] = (int)0xbb67ae85;
$h[2] = (int)0x3c6ef372;
$h[3] = (int)0xa54ff53a;
$h[4] = (int)0x510e527f;
$h[5] = (int)0x9b05688c;
$h[6] = (int)0x1f83d9ab;
$h[7] = (int)0x5be0cd19;
// loop through message blocks and compute hash. ( For i=1 to N : )
$N = count($M);
for ($i = 0; $i < $N; $i++)
{
// Break input block into 16 32bit words (message schedule prep)
$MI = $this->int_split($M[$i]);
// Initialize working variables
$_a = (int)$h[0];
$_b = (int)$h[1];
$_c = (int)$h[2];
$_d = (int)$h[3];
$_e = (int)$h[4];
$_f = (int)$h[5];
$_g = (int)$h[6];
$_h = (int)$h[7];
unset($_s0);
unset($_s1);
unset($_T1);
unset($_T2);
$W = array();
// Compute the hash and update
for ($t = 0; $t < 16; $t++)
{
// Prepare the first 16 message schedule values as we loop
$W[$t] = $MI[$t];
// Compute hash
$_T1 = $this->addmod2n($this->addmod2n($this->addmod2n($this->addmod2n($_h, $this->Sigma1($_e)), $this->Ch($_e, $_f, $_g)), $K[$t]), $W[$t]);
$_T2 = $this->addmod2n($this->Sigma0($_a), $this->Maj($_a, $_b, $_c));
// Update working variables
$_h = $_g; $_g = $_f; $_f = $_e; $_e = $this->addmod2n($_d, $_T1);
$_d = $_c; $_c = $_b; $_b = $_a; $_a = $this->addmod2n($_T1, $_T2);
}
for (; $t < 64; $t++)
{
// Continue building the message schedule as we loop
$_s0 = $W[($t+1)&0x0F];
$_s0 = $this->sigma_0($_s0);
$_s1 = $W[($t+14)&0x0F];
$_s1 = $this->sigma_1($_s1);
$W[$t&0xF] = $this->addmod2n($this->addmod2n($this->addmod2n($W[$t&0xF], $_s0), $_s1), $W[($t+9)&0x0F]);
// Compute hash
$_T1 = $this->addmod2n($this->addmod2n($this->addmod2n($this->addmod2n($_h, $this->Sigma1($_e)), $this->Ch($_e, $_f, $_g)), $K[$t]), $W[$t&0xF]);
$_T2 = $this->addmod2n($this->Sigma0($_a), $this->Maj($_a, $_b, $_c));
// Update working variables
$_h = $_g; $_g = $_f; $_f = $_e; $_e = $this->addmod2n($_d, $_T1);
$_d = $_c; $_c = $_b; $_b = $_a; $_a = $this->addmod2n($_T1, $_T2);
}
$h[0] = $this->addmod2n($h[0], $_a);
$h[1] = $this->addmod2n($h[1], $_b);
$h[2] = $this->addmod2n($h[2], $_c);
$h[3] = $this->addmod2n($h[3], $_d);
$h[4] = $this->addmod2n($h[4], $_e);
$h[5] = $this->addmod2n($h[5], $_f);
$h[6] = $this->addmod2n($h[6], $_g);
$h[7] = $this->addmod2n($h[7], $_h);
}
// Convert the 32-bit words into human readable hexadecimal format.
$hexStr = sprintf("%08x%08x%08x%08x%08x%08x%08x%08x", $h[0], $h[1], $h[2], $h[3], $h[4], $h[5], $h[6], $h[7]);
return ($this->toUpper) ? strtoupper($hexStr) : $hexStr;
}
}
}
if (!function_exists('str_split'))
{
/**
* Splits a string into an array of strings with specified length.
* Compatability with older verions of PHP
*/
function str_split($string, $split_length = 1)
{
$sign = ($split_length < 0) ? -1 : 1;
$strlen = strlen($string);
$split_length = abs($split_length);
if (($split_length == 0) || ($strlen == 0)) {
$result = false;
} elseif ($split_length >= $strlen) {
$result[] = $string;
} else {
$length = $split_length;
for ($i = 0; $i < $strlen; $i++)
{
$i = (($sign < 0) ? $i + $length : $i);
$result[] = substr($string, $sign*$i, $length);
$i--;
$i = (($sign < 0) ? $i : $i + $length);
$length = (($i + $split_length) > $strlen)
? ($strlen - ($i + 1))
: $split_length;
}
}
return $result;
}
}
/**
* Main routine called from an application using this include.
*
* General usage:
* require_once('sha256.inc.php');
* $hashstr = sha256('abc');
*
* Note:
* PHP Strings are limitd to (2^31)-1, so it is not worth it to
* check for input strings > 2^64 as the FIPS180-2 defines.
*/
// 2009-07-23: Added check for function as the Suhosin plugin adds this routine.
if (!function_exists('sha256')) {
function sha256($str, $ig_func = false) {
$obj = new nanoSha2((defined('_NANO_SHA2_UPPER')) ? true : false);
return $obj->hash($str, $ig_func);
}
} else {
function _nano_sha256($str, $ig_func = false) {
$obj = new nanoSha2((defined('_NANO_SHA2_UPPER')) ? true : false);
return $obj->hash($str, $ig_func);
}
}
// support to give php4 the hash() routine which abstracts this code.
if (!function_exists('hash'))
{
function hash($algo, $data)
{
if (empty($algo) || !is_string($algo) || !is_string($data)) {
return false;
}
if (function_exists($algo)) {
return $algo($data);
}
}
}
+9
View File
@@ -0,0 +1,9 @@
<?php
if (!defined('_GNUBOARD_')) exit; // 개별 페이지 접근 불가
//삼성페이 또는 Lpay 또는 이니시스 카카오페이 사용시에만 해당함
if( ! ($default['de_inicis_lpay_use'] || $default['de_inicis_kakaopay_use']) || ('inicis' == $default['de_pg_service']) ){ //PG가 이니시스인 경우 아래 내용 사용 안함
return;
}
include_once(G5_SHOP_PATH.'/settle_inicis.inc.php');
+123
View File
@@ -0,0 +1,123 @@
<?php
if (!defined('_GNUBOARD_')) exit; // 개별 페이지 접근 불가
//이니시스 lpay 사용시에만 해당함
if( ! ($default['de_inicis_lpay_use'] || $default['de_inicis_kakaopay_use']) || ('inicis' == $default['de_pg_service']) ){ //PG가 이니시스인 경우 아래 내용 사용 안함
return;
}
add_javascript('<script language="javascript" type="text/javascript" src="'.$stdpay_js_url.'" charset="UTF-8"></script>', 10);
?>
<form name="inicis_pay_form" id="inicis_pay_form" method="POST">
<?php /* 주문폼 자바스크립트 에러 방지를 위해 추가함 */ ?>
<input type="hidden" name="good_mny" value="">
<?php
if($default['de_tax_flag_use']) {
?>
<input type="hidden" name="comm_tax_mny" value=""> <!-- 과세금액 -->
<input type="hidden" name="comm_vat_mny" value=""> <!-- 부가세 -->
<input type="hidden" name="comm_free_mny" value=""> <!-- 비과세 금액 -->
<?php
}
?>
<input type="hidden" name="version" value="1.0" >
<input type="hidden" name="mid" value="<?php echo $mid; ?>">
<input type="hidden" name="oid" value="<?php echo $od_id; ?>">
<input type="hidden" name="goodname" value="">
<input type="hidden" name="price" value="">
<input type="hidden" name="buyername" value="">
<input type="hidden" name="buyeremail" value="">
<input type="hidden" name="parentemail" value="">
<input type="hidden" name="buyertel" value="">
<input type="hidden" name="recvname" value="">
<input type="hidden" name="recvtel" value="">
<input type="hidden" name="recvaddr" value="">
<input type="hidden" name="recvpostnum" value="">
<!-- 기타설정 -->
<input type="hidden" name="currency" value="WON">
<!-- 결제방법 -->
<input type="hidden" name="gopaymethod" value="">
<!--
SKIN : 플러그인 스킨 칼라 변경 기능 - 6가지 칼라(ORIGINAL, GREEN, ORANGE, BLUE, KAKKI, GRAY)
HPP : 컨텐츠 또는 실물 결제 여부에 따라 HPP(1)과 HPP(2)중 선택 적용(HPP(1):컨텐츠, HPP(2):실물).
Card(0): 신용카드 지불시에 이니시스 대표 가맹점인 경우에 필수적으로 세팅 필요 ( 자체 가맹점인 경우에는 카드사의 계약에 따라 설정) - 자세한 내용은 메뉴얼 참조.
OCB : OK CASH BAG 가맹점으로 신용카드 결제시에 OK CASH BAG 적립을 적용하시기 원하시면 "OCB" 세팅 필요 그 외에 경우에는 삭제해야 정상적인 결제 이루어짐.
no_receipt : 은행계좌이체시 현금영수증 발행여부 체크박스 비활성화 (현금영수증 발급 계약이 되어 있어야 사용가능)
-->
<input type="hidden" name="acceptmethod" value="<?php echo $acceptmethod; ?>">
<!--
플러그인 좌측 상단 상점 로고 이미지 사용
이미지의 크기 : 90 X 34 pixels
플러그인 좌측 상단에 상점 로고 이미지를 사용하실 수 있으며,
주석을 풀고 이미지가 있는 URL을 입력하시면 플러그인 상단 부분에 상점 이미지를 삽입할수 있습니다.
-->
<!--input type="hidden" name="ini_logoimage_url" value="http://[사용할 이미지주소]"-->
<!--
좌측 결제메뉴 위치에 이미지 추가
이미지의 크기 : 단일 결제 수단 - 91 X 148 pixels, 신용카드/ISP/계좌이체/가상계좌 - 91 X 96 pixels
좌측 결제메뉴 위치에 미미지를 추가하시 위해서는 담당 영업대표에게 사용여부 계약을 하신 후
주석을 풀고 이미지가 있는 URL을 입력하시면 플러그인 좌측 결제메뉴 부분에 이미지를 삽입할수 있습니다.
-->
<!--input type="hidden" name="ini_menuarea_url" value="http://[사용할 이미지주소]"-->
<!--
플러그인에 의해서 값이 채워지거나, 플러그인이 참조하는 필드들
삭제/수정 불가
-->
<input type="hidden" name="timestamp" value="">
<input type="hidden" name="signature" value="">
<input type="hidden" name="returnUrl" value="<?php echo $returnUrl; ?>">
<input type="hidden" name="mKey" value="">
<input type="hidden" name="charset" value="UTF-8">
<input type="hidden" name="payViewType" value="overlay">
<input type="hidden" name="closeUrl" value="<?php echo $closeUrl; ?>">
<input type="hidden" name="popupUrl" value="<?php echo $popupUrl; ?>">
<input type="hidden" name="nointerest" value="<?php echo $cardNoInterestQuota; ?>">
<input type="hidden" name="quotabase" value="<?php echo $cardQuotaBase; ?>">
<?php if($default['de_tax_flag_use']) { ?>
<input type="hidden" name="tax" value="">
<input type="hidden" name="taxfree" value="">
<?php } ?>
</form>
<script language=javascript>
function make_signature(frm)
{
// 데이터 암호화 처리
var result = true;
$.ajax({
url: g5_url+"/shop/inicis/makesignature.php",
type: "POST",
data: {
price : frm.good_mny.value
},
dataType: "json",
async: false,
cache: false,
success: function(data) {
if(data.error == "") {
frm.timestamp.value = data.timestamp;
frm.signature.value = data.sign;
frm.mKey.value = data.mKey;
} else {
alert(data.error);
result = false;
}
}
});
return result;
}
function paybtn(f) {
INIStdPay.pay(f.id);
}
</script>
+74
View File
@@ -0,0 +1,74 @@
<?php
if (!defined("_GNUBOARD_")) exit; // 개별 페이지 접근 불가
//삼성페이 또는 L.pay 또는 이니시스 카카오페이 사용시에만 해당함
if( ! ($default['de_inicis_lpay_use'] || $default['de_inicis_kakaopay_use']) || ('inicis' == $default['de_pg_service']) ){ //PG가 이니시스인 경우 아래 내용 사용 안함
return;
}
?>
<script>
jQuery(function($){
$( document ).ready(function() {
var pf = document.forderform;
$(pf).on("form_sumbit_order_samsungpay", inicis_pay_form_submit);
function inicis_pay_form_submit(){
var $form = $(this),
pf = $form[0],
inicis_pay_form = document.inicis_pay_form,
inicis_settle_case = jQuery("input[name='od_settle_case']:checked").val();
inicis_pay_form.gopaymethod.value = (inicis_settle_case === "inicis_kakaopay") ? "onlykakaopay" : "onlylpay";
inicis_pay_form.acceptmethod.value = "cardonly";
inicis_pay_form.price.value = inicis_pay_form.good_mny.value = pf.good_mny.value;
inicis_pay_form.goodname.value = pf.od_goods_name.value;
inicis_pay_form.buyername.value = pf.od_name.value;
inicis_pay_form.buyeremail.value = pf.od_email.value;
inicis_pay_form.buyertel.value = pf.od_hp.value ? pf.od_hp.value : pf.od_tel.value;
inicis_pay_form.recvname.value = pf.od_b_name.value;
inicis_pay_form.recvtel.value = pf.od_b_hp.value ? pf.od_b_hp.value : pf.od_b_tel.value;
inicis_pay_form.recvpostnum.value = pf.od_b_zip.value;
inicis_pay_form.recvaddr.value = pf.od_b_addr1.value + " " +pf.od_b_addr2.value;
<?php if($default['de_tax_flag_use']) { ?>
inicis_pay_form.comm_tax_mny.value = pf.comm_tax_mny.value;
inicis_pay_form.comm_vat_mny.value = pf.comm_vat_mny.value;
inicis_pay_form.comm_free_mny.value = pf.comm_free_mny.value;
inicis_pay_form.tax.value = pf.comm_vat_mny.value;
inicis_pay_form.taxfree.value = pf.comm_free_mny.value;
<?php } ?>
// 주문 정보 임시저장
var order_data = $(pf).serialize();
var save_result = "";
$.ajax({
type: "POST",
data: order_data,
url: g5_url+"/shop/ajax.orderdatasave.php",
cache: false,
async: false,
success: function(data) {
save_result = data;
}
});
if(save_result) {
alert(save_result);
return false;
}
if(!make_signature(inicis_pay_form))
return false;
setTimeout(function(){
paybtn(inicis_pay_form);
}, 1);
return false;
}
});
});
</script>
+31
View File
@@ -0,0 +1,31 @@
<?php
include_once('./_common.php');
include_once(G5_SHOP_PATH.'/settle_inicis.inc.php');
if($default['de_pg_service'] != 'inicis' && ! ($default['de_inicis_lpay_use'] || $default['de_inicis_kakaopay_use']) )
die(json_encode(array('error'=>'올바른 방법으로 이용해 주십시오.')));
$orderNumber = get_session('ss_order_inicis_id');
$price = preg_replace('#[^0-9]#', '', $_POST['price']);
if(strlen($price) < 1)
die(json_encode(array('error'=>'가격이 올바르지 않습니다.')));
//
//###################################
// 2. 가맹점 확인을 위한 signKey를 해시값으로 변경 (SHA-256방식 사용)
//###################################
$mKey = hash("sha256", $signKey);
/*
//*** 위변조 방지체크를 signature 생성 ***
oid, price, timestamp 3개의 키와 값을
key=value 형식으로 하여 '&'로 연결한 하여 SHA-256 Hash로 생성 된값
ex) oid=INIpayTest_1432813606995&price=819000&timestamp=2012-02-01 09:19:04.004
* key기준 알파벳 정렬
* timestamp는 반드시 signature생성에 사용한 timestamp 값을 timestamp input에 그대로 사용하여야함
*/
$params = "oid=" . $orderNumber . "&price=" . $price . "&timestamp=" . $timestamp;
$sign = hash("sha256", $params);
die(json_encode(array('error'=>'', 'mKey'=>$mKey, 'timestamp'=>$timestamp, 'sign'=>$sign)));
+42
View File
@@ -0,0 +1,42 @@
<?php
if (!defined("_GNUBOARD_")) exit; // 개별 페이지 접근 불가
// 전자결제를 사용할 때만 실행
if($default['de_iche_use'] || $default['de_vbank_use'] || $default['de_hp_use'] || $default['de_card_use'] || $default['de_easy_pay_use']) {
add_javascript('<script language="javascript" type="text/javascript" src="'.$stdpay_js_url.'" charset="UTF-8"></script>', 10);
?>
<script language=javascript>
function make_signature(frm)
{
// 데이터 암호화 처리
var result = true;
$.ajax({
url: g5_url+"/shop/inicis/makesignature.php",
type: "POST",
data: {
price : frm.good_mny.value
},
dataType: "json",
async: false,
cache: false,
success: function(data) {
if(data.error == "") {
frm.timestamp.value = data.timestamp;
frm.signature.value = data.sign;
frm.mKey.value = data.mKey;
} else {
alert(data.error);
result = false;
}
}
});
return result;
}
function paybtn(f) {
INIStdPay.pay(f.id);
}
</script>
<?php }
+79
View File
@@ -0,0 +1,79 @@
<?php
if (!defined("_GNUBOARD_")) exit; // 개별 페이지 접근 불가
?>
<?php /* 주문폼 자바스크립트 에러 방지를 위해 추가함 */ ?>
<input type="hidden" name="good_mny" value="<?php echo $tot_price; ?>">
<?php
if($default['de_tax_flag_use']) {
?>
<input type="hidden" name="comm_tax_mny" value="<?php echo $comm_tax_mny; ?>"> <!-- 과세금액 -->
<input type="hidden" name="comm_vat_mny" value="<?php echo $comm_vat_mny; ?>"> <!-- 부가세 -->
<input type="hidden" name="comm_free_mny" value="<?php echo $comm_free_mny; ?>"> <!-- 비과세 금액 -->
<?php
}
?>
<input type="hidden" name="version" value="1.0" >
<input type="hidden" name="mid" value="<?php echo $mid; ?>">
<input type="hidden" name="oid" value="<?php echo $od_id; ?>">
<input type="hidden" name="goodname" value="<?php echo $goods; ?>">
<input type="hidden" name="price" value="<?php echo $tot_price; ?>">
<input type="hidden" name="buyername" value="">
<input type="hidden" name="buyeremail" value="">
<input type="hidden" name="parentemail" value="">
<input type="hidden" name="buyertel" value="">
<input type="hidden" name="recvname" value="">
<input type="hidden" name="recvtel" value="">
<input type="hidden" name="recvaddr" value="">
<input type="hidden" name="recvpostnum" value="">
<!-- 기타설정 -->
<input type="hidden" name="currency" value="WON">
<!-- 결제방법 -->
<input type="hidden" name="gopaymethod" value="">
<!--
SKIN : 플러그인 스킨 칼라 변경 기능 - 6가지 칼라(ORIGINAL, GREEN, ORANGE, BLUE, KAKKI, GRAY)
HPP : 컨텐츠 또는 실물 결제 여부에 따라 HPP(1)과 HPP(2)중 선택 적용(HPP(1):컨텐츠, HPP(2):실물).
Card(0): 신용카드 지불시에 이니시스 대표 가맹점인 경우에 필수적으로 세팅 필요 ( 자체 가맹점인 경우에는 카드사의 계약에 따라 설정) - 자세한 내용은 메뉴얼 참조.
OCB : OK CASH BAG 가맹점으로 신용카드 결제시에 OK CASH BAG 적립을 적용하시기 원하시면 "OCB" 세팅 필요 그 외에 경우에는 삭제해야 정상적인 결제 이루어짐.
no_receipt : 은행계좌이체시 현금영수증 발행여부 체크박스 비활성화 (현금영수증 발급 계약이 되어 있어야 사용가능)
-->
<input type="hidden" name="acceptmethod" value="<?php echo $acceptmethod; ?>">
<!--
플러그인 좌측 상단 상점 로고 이미지 사용
이미지의 크기 : 90 X 34 pixels
플러그인 좌측 상단에 상점 로고 이미지를 사용하실 수 있으며,
주석을 풀고 이미지가 있는 URL을 입력하시면 플러그인 상단 부분에 상점 이미지를 삽입할수 있습니다.
-->
<!--input type="hidden" name="ini_logoimage_url" value="http://[사용할 이미지주소]"-->
<!--
좌측 결제메뉴 위치에 이미지 추가
이미지의 크기 : 단일 결제 수단 - 91 X 148 pixels, 신용카드/ISP/계좌이체/가상계좌 - 91 X 96 pixels
좌측 결제메뉴 위치에 미미지를 추가하시 위해서는 담당 영업대표에게 사용여부 계약을 하신 후
주석을 풀고 이미지가 있는 URL을 입력하시면 플러그인 좌측 결제메뉴 부분에 이미지를 삽입할수 있습니다.
-->
<!--input type="hidden" name="ini_menuarea_url" value="http://[사용할 이미지주소]"-->
<!--
플러그인에 의해서 값이 채워지거나, 플러그인이 참조하는 필드들
삭제/수정 불가
-->
<input type="hidden" name="timestamp" value="">
<input type="hidden" name="signature" value="">
<input type="hidden" name="returnUrl" value="<?php echo $returnUrl; ?>">
<input type="hidden" name="mKey" value="">
<input type="hidden" name="charset" value="UTF-8">
<input type="hidden" name="payViewType" value="overlay">
<input type="hidden" name="closeUrl" value="<?php echo $closeUrl; ?>">
<input type="hidden" name="popupUrl" value="<?php echo $popupUrl; ?>">
<input type="hidden" name="nointerest" value="<?php echo $cardNoInterestQuota; ?>">
<input type="hidden" name="quotabase" value="<?php echo $cardQuotaBase; ?>">
<?php if($default['de_tax_flag_use']) { ?>
<input type="hidden" name="tax" value="<?php echo $comm_vat_mny; ?>">
<input type="hidden" name="taxfree" value="<?php echo $comm_free_mny; ?>">
<?php }
+12
View File
@@ -0,0 +1,12 @@
<?php
if (!defined("_GNUBOARD_")) exit; // 개별 페이지 접근 불가
?>
<div id="display_pay_button" class="btn_confirm">
<input type="button" value="주문하기" onclick="forderform_check(this.form);" class="btn_submit">
<a href="javascript:history.go(-1);" class="btn01">취소</a>
</div>
<div id="display_pay_process" style="display:none">
<img src="<?php echo G5_URL; ?>/shop/img/loading.gif" alt="">
<span>주문완료 중입니다. 잠시만 기다려 주십시오.</span>
</div>
+2
View File
@@ -0,0 +1,2 @@
<?php
if (!defined("_GNUBOARD_")) exit; // 개별 페이지 접근 불가;
+59
View File
@@ -0,0 +1,59 @@
<?php
if (!defined("_GNUBOARD_")) exit; // 개별 페이지 접근 불가
if($od['od_pg'] != 'inicis') return;
include_once(G5_SHOP_PATH.'/settle_inicis.inc.php');
$vat_mny = round((int)$tax_mny / 1.1);
$currency = 'WON';
$oldtid = $od['od_tno'];
$price = (int)$tax_mny + (int)$free_mny; // 취소요청 금액
$confirm_price = (int)$od['od_receipt_price'] - (int)$od['od_refund_price'] - $price; // 부분취소 후 남은금액
$buyeremail = $od['od_email'];
$tax = (int)$tax_mny - $vat_mny; // 부가세
$taxfree = (int)$free_mny; // 비과세
$args = array(
'paymethod' => get_type_inicis_paymethod($od['od_settle_case']),
'tid' => $od['od_tno'],
'msg' => $od['od_id'].' '.$mod_memo,
'price' => $price,
'confirmPrice' => $confirm_price,
'tax' => $tax,
'taxFree' => $taxfree
);
$response = inicis_tid_cancel($args, true); // KG 이니시스 부분취소일 경우 inicis_tid_cancel 함수 2번째 인자값을 true로
$result = json_decode($response, true);
if(isset($result['resultCode']) && $result['resultCode'] == '00') {
// 환불금액기록
$tno = $result['prtcTid'];
$re_price = $result['prtcPrice'];
$sql = " update {$g5['g5_shop_order_table']}
set od_refund_price = od_refund_price + '$re_price',
od_shop_memo = concat(od_shop_memo, \"$mod_memo\")
where od_id = '{$od['od_id']}'
and od_tno = '$tno' ";
sql_query($sql);
// 미수금 등의 정보 업데이트
$info = get_order_info($od_id);
$sql = " update {$g5['g5_shop_order_table']}
set od_misu = '{$info['od_misu']}',
od_tax_mny = '{$info['od_tax_mny']}',
od_vat_mny = '{$info['od_vat_mny']}',
od_free_mny = '{$info['od_free_mny']}'
where od_id = '$od_id' ";
sql_query($sql);
} else {
if (isset($result['resultCode'])){
alert($result['resultMsg'].' 코드 : '.$result['resultCode']);
} else {
alert('curl 오류로 부분환불에 실패했습니다.');
}
}
+1
View File
@@ -0,0 +1 @@
<script language="javascript" type="text/javascript" src="https://stdpay.inicis.com/stdjs/INIStdPay_popup.js" charset="UTF-8"></script>
+197
View File
@@ -0,0 +1,197 @@
<?php
if (!defined("_GNUBOARD_")) exit; // 개별 페이지 접근 불가
?>
<script>
// 현금영수증 MAIN FUNC
function jsf__pay_cash( form )
{
jsf__show_progress(true);
if ( jsf__chk_cash( form ) == false )
{
jsf__show_progress(false);
return;
}
form.submit();
}
// 진행 바
function jsf__show_progress( show )
{
if ( show == true )
{
window.show_pay_btn.style.display = "none";
window.show_progress.style.display = "inline";
}
else
{
window.show_pay_btn.style.display = "inline";
window.show_progress.style.display = "none";
}
}
// 포맷 체크
function jsf__chk_cash( form )
{
if ( form.tr_code[0].checked )
{
if ( form.id_info.value.length != 10 &&
form.id_info.value.length != 11 &&
form.id_info.value.length != 13 )
{
alert("주민번호 또는 휴대폰번호를 정확히 입력해 주시기 바랍니다.");
form.id_info.select();
form.id_info.focus();
return false;
}
}
else if ( form.tr_code[1].checked )
{
if ( form.id_info.value.length != 10 )
{
alert("사업자번호를 정확히 입력해 주시기 바랍니다.");
form.id_info.select();
form.id_info.focus();
return false;
}
}
return true;
}
function jsf__chk_tr_code( form )
{
var span_tr_code_0 = document.getElementById( "span_tr_code_0" );
var span_tr_code_1 = document.getElementById( "span_tr_code_1" );
if ( form.tr_code[0].checked )
{
span_tr_code_0.style.display = "inline";
span_tr_code_1.style.display = "none";
}
else if (form.tr_code[1].checked )
{
span_tr_code_0.style.display = "none";
span_tr_code_1.style.display = "inline";
}
}
</script>
<div id="scash" class="new_win">
<h1 id="win_title"><?php echo $g5['title']; ?></h1>
<section>
<h2>주문정보</h2>
<div class="tbl_head01 tbl_wrap">
<table>
<colgroup>
<col class="grid_3">
<col>
</colgroup>
<tbody>
<tr>
<th scope="row">주문 번호</th>
<td><?php echo $od_id; ?></td>
</tr>
<tr>
<th scope="row">상품 정보</th>
<td><?php echo $goods_name; ?></td>
</tr>
<tr>
<th scope="row">주문자 이름</th>
<td><?php echo $od_name; ?></td>
</tr>
<tr>
<th scope="row">주문자 E-Mail</th>
<td><?php echo $od_email; ?></td>
</tr>
<tr>
<th scope="row">주문자 전화번호</th>
<td><?php echo $od_tel; ?></td>
</tr>
</tbody>
</table>
</div>
</section>
<section>
<h2>현금영수증 발급 정보</h2>
<form method="post" action="<?php echo G5_SHOP_URL; ?>/inicis/taxsave_result.php">
<input type="hidden" name="tx" value="<?php echo $tx; ?>">
<input type="hidden" name="od_id" value="<?php echo $od_id; ?>">
<div class="tbl_head01 tbl_wrap">
<table>
<colgroup>
<col class="grid_3">
<col>
</colgroup>
<tbody>
<tr>
<th scope="row">원 거래 시각</th>
<td><?php echo $trad_time; ?></td>
</tr>
<tr>
<th scope="row">발행 용도</th>
<td>
<input type="radio" name="tr_code" value="0" id="tr_code1" onClick="jsf__chk_tr_code( this.form )" checked>
<label for="tr_code1">소득공제용</label>
<input type="radio" name="tr_code" value="1" id="tr_code2" onClick="jsf__chk_tr_code( this.form )">
<label for="tr_code2">지출증빙용</label>
</td>
</tr>
<tr>
<th scope="row">
<label for="id_info">
<span id="span_tr_code_0" style="display:inline">주민(휴대폰)번호</span>
<span id="span_tr_code_1" style="display:none">사업자번호</span>
</label>
</th>
<td>
<input type="text" name="id_info" id="id_info" class="frm_input" size="16" maxlength="13"> ("-" 생략)
</td>
</tr>
<tr>
<th scope="row"><label for="buyeremail">이메일</label></th>
<td><input type="text" name="buyeremail" id="buyeremail" value="<?php echo $od_email; ?>" required class="required frm_input" size="30"></td>
</tr>
<tr>
<th scope="row"><label for="buyertel">휴대폰</label></th>
<td><input type="text" name="buyertel" id="buyertel" value="" required class="required frm_input" size="20"></td>
</tr>
<tr>
<th scope="row">거래금액 총합</th>
<td><?php echo number_format($amt_tot); ?>원</td>
</tr>
<tr>
<th scope="row">공급가액</th>
<td><?php echo number_format($amt_sup); ?>원<!-- ((거래금액 총합 * 10) / 11) --></td>
</tr>
<tr>
<th scope="row">봉사료</th>
<td><?php echo number_format($amt_svc); ?>원</td>
</tr>
<tr>
<th scope="row">부가가치세</th>
<td><?php echo number_format($amt_tax); ?>원<!-- 거래금액 총합 - 공급가액 - 봉사료 --></td>
</tr>
</tbody>
</table>
</div>
<div id="scash_apply">
<span id="show_pay_btn">
<button type="button" onclick="jsf__pay_cash( this.form )">등록요청</button>
</span>
<span id="show_progress" style="display:none">
<b>등록 진행중입니다. 잠시만 기다려주십시오</b>
</span>
</div>
</form>
</section>
</div>
+220
View File
@@ -0,0 +1,220 @@
<?php
include_once('./_common.php');
include_once(G5_SHOP_PATH.'/settle_inicis.inc.php');
$iv = get_inicis_iniapi_iv();
if (strlen($iv) !== 16){
alert('쇼핑몰설정 < KG이니시스 INIAPI IV 값을 16자리로 설정 후 이용해 주세요.');
}
/*
*
* 현금결제(실시간 은행계좌이체, 무통장입금)에 대한 현금결제 영수증 발행 요청한다.
*
*
* http://www.inicis.com
* http://support.inicis.com
*/
$companynumber = isset($_REQUEST['companynumber']) ? clean_xss_tags($_REQUEST['companynumber'], 1, 1) : '';
if($tx == 'personalpay') {
$od = sql_fetch(" select * from {$g5['g5_shop_personalpay_table']} where pp_id = '$od_id' ");
if (!$od)
die('<p id="scash_empty">개인결제 내역이 존재하지 않습니다.</p>');
if($od['pp_cash'] == 1)
alert('이미 등록된 현금영수증 입니다.');
$buyername = $od['pp_name'];
$goodname = $od['pp_name'].'님 개인결제';
$amt_tot = (int)$od['pp_receipt_price'];
$amt_sup = (int)round(($amt_tot * 10) / 11);
$amt_svc = 0;
$amt_tax = (int)($amt_tot - $amt_sup);
} else {
$od = sql_fetch(" select * from {$g5['g5_shop_order_table']} where od_id = '$od_id' ");
if (!$od)
die('<p id="scash_empty">주문서가 존재하지 않습니다.</p>');
if($od['od_cash'] == 1)
alert('이미 등록된 현금영수증 입니다.');
$buyername = $od['od_name'];
$goods = get_goods($od['od_id']);
$goodname = $goods['full_name'];
$amt_tot = (int)$od['od_tax_mny'] + (int)$od['od_vat_mny'] + (int)$od['od_free_mny'];
$amt_sup = (int)$od['od_tax_mny'] + (int)$od['od_free_mny'];
$amt_tax = (int)$od['od_vat_mny'];
$amt_svc = 0;
}
$reg_num = $id_info;
$useopt = $tr_code;
$currency = 'WON';
//step1. 요청을 위한 파라미터 설정
// 가맹점관리자 > 상점정보 > 계약정보 > 부가정보 > INIAPI key 생성조회, IV 도 조회 가능
$key = get_inicis_iniapi_key();
$iv = get_inicis_iniapi_iv();
$type = "Issue";// 고정
$paymethod = "Receipt";// 고정
$timestamp = date("YmdHis");
$clientIp = $_SERVER['SERVER_ADDR'];// 가맹점 요청 서버IP (추후 거래 확인 등에 사용됨)
$mid = $default['de_inicis_mid'];
$goodName = $goodname; // 상품명
$crPrice = $amt_tot;// 총 현금결제 금액
$supPrice = $amt_sup;// 공급가액
$tax = $amt_tax;// 부가세
$srcvPrice = $amt_svc;// 봉사료
$buyerName = $buyername;// 구매자 성명
$buyerEmail = $buyeremail;// 구매자 이메일 주소
$buyerTel = $buyertel;// 구매자 전화번호
$useOpt = $useopt;// 현금영수증 발행용도 ("1" - 소비자 소득공제용, "2" - 사업자 지출증빙용)
$regNum = $reg_num;// 현금결제자 주민등록번호
// AES 암호화 (regNum)
if (function_exists('openssl_encrypt')) {
$enregNum = base64_encode(openssl_encrypt($regNum, 'aes-128-cbc', $key, OPENSSL_RAW_DATA, $iv));
} else if (function_exists('mcrypt_encrypt')) {
$padSize = 16 - (strlen($regNum) % 16);
$value = $regNum.str_repeat(chr($padSize), $padSize);
$enregNum = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $value, MCRYPT_MODE_CBC, $iv));
} else {
alert('openssl_encrypt 함수가 없어서 실행할수 없습니다.');
}
// SHA512 Hash 암호화
// INIAPIKey + type + paymethod + timestamp + clientIp + mid + tid + crPrice + supPrice + srcvPrice + enregNum
$hashData = hash("sha512", (string)$key.(string)$type.(string)$paymethod.(string)$timestamp.(string)$clientIp.(string)$mid.(string)$crPrice.(string)$supPrice.(string)$srcvPrice.(string)$enregNum);
//step2. key=value 로 post 요청
$data = array(
'type' => $type,
'paymethod' => $paymethod,
'timestamp' => $timestamp,
'clientIp' => $clientIp,
'mid' => $mid,
'goodName' => $goodName,
'crPrice' => $crPrice,
'supPrice' => $supPrice,
'tax' => $tax,
'srcvPrice' => $srcvPrice,
'buyerName' => $buyerName,
'buyerEmail' => $buyerEmail,
'buyerTel' => $buyerTel,
'regNum' => $enregNum,
'useOpt' => $useOpt,
'compayNumber' => $companynumber,
'hashData'=> $hashData
);
$url = "https://iniapi.inicis.com/api/v1/receipt";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded; charset=utf-8'));
curl_setopt($ch, CURLOPT_POST, 1);
$response = curl_exec($ch);
curl_close($ch);
//step3. 요청 결과
$ini_result = json_decode($response, true);
if (isset($ini_result['resultCode']) && $ini_result['resultCode'] == '00') {
// DB 반영
$cash_no = $ini_result['authNo']; // 현금영수증 승인번호
$cash = array();
$cash['TID'] = $ini_result['tid'];
$cash['ApplNum'] = $cash_no;
$cash['ApplDate'] = $ini_result['authDate'];
$cash['ApplTime'] = $ini_result['authTime'];
$cash['CSHR_Type'] = $ini_result['authUseOpt'];
$cash_info = serialize($cash);
if($tx == 'personalpay') {
$sql = " update {$g5['g5_shop_personalpay_table']}
set pp_cash = '1',
pp_cash_no = '$cash_no',
pp_cash_info = '$cash_info'
where pp_id = '$od_id' ";
} else {
$sql = " update {$g5['g5_shop_order_table']}
set od_cash = '1',
od_cash_no = '$cash_no',
od_cash_info = '$cash_info'
where od_id = '$od_id' ";
}
$result = sql_query($sql, false);
}
$g5['title'] = '현금영수증 발급';
include_once(G5_PATH.'/head.sub.php');
?>
<script>
function showreceipt() // 현금 영수증 출력
{
var showreceiptUrl = "https://iniweb.inicis.com/DefaultWebApp/mall/cr/cm/Cash_mCmReceipt.jsp?noTid=<?php echo($ini_result['tid']); ?>" + "&clpaymethod=22";
window.open(showreceiptUrl,"showreceipt","width=380,height=540, scrollbars=no,resizable=no");
}
</script>
<div id="lg_req_tx" class="new_win">
<h1 id="win_title">현금영수증 - KG이니시스</h1>
<div class="tbl_head01 tbl_wrap">
<table>
<colgroup>
<col class="grid_4">
<col>
</colgroup>
<tbody>
<tr>
<th scope="row">결과코드</th>
<td><?php echo $ini_result['resultCode']; ?></td>
</tr>
<tr>
<th scope="row">결과 메세지</th>
<td><?php echo $ini_result['resultMsg']; ?></td>
</tr>
<tr>
<th scope="row">현금영수증 거래번호</th>
<td><?php echo $ini_result['tid']; ?></td>
</tr>
<tr>
<th scope="row">현금영수증 승인번호</th>
<td><?php echo $ini_result['authNo']; ?></td>
</tr>
<tr>
<th scope="row">승인시간</th>
<td><?php echo preg_replace("/([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})/", "\\1-\\2-\\3 \\4:\\5:\\6",$ini_result['authDate'].$ini_result['authTime']); ?></td>
</tr>
<tr>
<th scope="row">현금영수증 URL</th>
<td>
<button type="button" name="receiptView" class="btn_frmline" onClick="javascript:showreceipt();">영수증 확인</button>
<p>영수증 확인은 실 등록의 경우에만 가능합니다.</p>
</td>
</tr>
<tr>
<td colspan="2"></td>
</tr>
</tbody>
</table>
</div>
</div>
<?php
include_once(G5_PATH.'/tail.sub.php');