강좌게시판

제목 [ci 드라이버] 한국 pg(결제) 드라이버 만들기 (2) -- 수정중
글쓴이 스미 작성시각 2016/02/19 10:33:07
댓글 : 5 추천 : 0 스크랩 : 1 조회수 : 35525   RSS

일단 이니시스 모듈은 제가 파악한것은

INIbill41         -- 일반적인 결제 구형 utf8 미지원

INIpay50        -- 일반적인 결제 신형 utf8 미지원

INIpay50-utf8  -- 일반적인 결제 신형 utf8 지원

INIformbill41   -- 카드정보를 받아 빌링키 생성, 이후 시스템에서 결제가 필요할때마다 빌링키로 결제

이렇게 있더라구요. 그중 INIformbill41 사용예제입니다.

INIformbill41 좀더 설명드리면

1. 사용자에게 설치요구를 하지않습니다. -- 모바일 사용에 용의합니다.

2. 빌링키로 결제가 진행되어 초기 카드등록후 결제시마다 카드정보가 필요없습니다.


-- 파일 수정

application/config/paymentgateway.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
if (defined('BASE_URL') == false) define('BASE_URL', CI::$APP->config->item('base_url'));

$config['pg_test'] = FALSE;
$config['pg_driver'] = 'INIformbill41';

$config['pg_default_field']['dummy'] = array();

$config['pg_default_field']['INIformbill41'] = array(
    'home_url' => BASE_URL,                            // 홈페이지 URL
    'pg_module_path' => null,                    // 이니페이 홈디렉터리 NULL입력시 자동입력
    'debug' => 'true',                        // 디버그(bloon 값 아님)
    'pg_mid_password' => '*****',                // 키패스워드(상점아이디에 따라 변경)
    'pg_mid' => '*********',                    // 상점아이디
    'acceptmethod' => 'below1000=1',                // 1000원 미만 승인을 위한 필드추가

    'currency' => 'WON',                    // 화폐 단위 WON : 원화결제일 경우 USD :   달러결제일 경우
    'auth_user' => '00',                    // 00:본인인증(카드번호,유효기간, 생년월일 6 자리, 비밀번호 앞 2 자리) 01:세미인증(카드번호, 유효기간, 생년월일 6 자리)
    'quotaInterest' => '0',                    // 무이자 유무 일반할부 : 0 무이자할부 : 1
);

6. 변경 dummy -> INIformbill41

10-21. 추가

application/libraries/Paymentgateway/Paymentgateway.php

<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Paymentgateway extends CI_Driver_Library {

	protected $valid_drivers = array(
		'INIformbill41',
		'dummy'
	);

6. 추가


-- 파일 추가

application/libraries/Paymentgateway/drivers/Paymentgateway_INIformbill41.php

<?php defined('BASEPATH') OR exit('No direct script access allowed');

class CI_Paymentgateway_INIformbill41 extends CI_Driver
{

    protected $validation_rules = array();
    protected $formauth_validation_rules = array(
        array('field' => 'buyer_name', 'label' => '구매자명', 'rules' => 'required|trim|max_length[30]',),
        array('field' => 'price', 'label' => '상품결제 금액', 'rules' => 'required|trim|integer|is_natural_no_zero|max_length[20]',),
        array('field' => 'card_number', 'label' => '카드번호', 'rules' => 'required|trim|integer|is_natural_no_zero|max_length[20]',),
        array('field' => 'card_exp_month', 'label' => '유효기간 월', 'rules' => 'required|trim|integer|is_natural_no_zero|exact_length[2]',),
        array('field' => 'card_exp_year', 'label' => '유효기간 년', 'rules' => 'required|trim|integer|is_natural_no_zero|exact_length[2]',),
        array('field' => 'auth_field1', 'label' => '생년월일', 'rules' => 'required|trim|integer|is_natural_no_zero|min_length[6]|max_length[10]',),
        array('field' => 'auth_field2', 'label' => '신용카드 비밀번호 앞 2자리', 'rules' => 'required|trim|integer|exact_length[2]',),
    );

    protected $reqrealbill_validation_rules = array(
        array('field' => 'currency', 'label' => '화폐단위', 'rules' => 'trim|in_list[WON,USD]',),

        array('field' => 'quotaInterest', 'label' => '무이자 유무', 'rules' => 'trim|is_natural|in_list[0,1]',),
        array('field' => 'card_quota', 'label' => '할부 기간', 'rules' => 'required|trim|is_natural|less_than_equal_to[24]',),

        array('field' => 'bill_key', 'label' => 'Billing Key', 'rules' => 'required|trim|max_length[40]',),
        array('field' => 'card_password', 'label' => '신용카드 비밀번호 앞 2자리', 'rules' => 'required|trim|is_natural|exact_length[2]',),
        array('field' => 'auth_user', 'label' => '본인인증유무', 'rules' => 'trim|is_natural|in_list[00,01]',),
        array('field' => 'reg_number', 'label' => '생년월일6자리(사업자 번호)', 'rules' => 'trim|integer|is_natural|min_length[6]|max_length[10]',),

        array('field' => 'buyer_name', 'label' => '구매자명', 'rules' => 'required|trim',),
        array('field' => 'buyer_phone', 'label' => '구매자 이동전화번호', 'rules' => 'required|trim|numeric',),
        array('field' => 'buyer_email', 'label' => '구매자 이메일', 'rules' => 'required|trim|valid_email',),

        array('field' => 'payment_uid', 'label' => '주문번호', 'rules' => 'required|trim|is_natural_no_zero',),
        array('field' => 'good_name', 'label' => '상품명', 'rules' => 'required|trim',),
        array('field' => 'price', 'label' => '구매자 이메일', 'rules' => 'required|trim|is_natural_no_zero',),
    );

    public $PG_ROOT = null;
    public $INIPAY = FALSE;

    public $_pgCompany = 'inicis';
    public $_pgCommand = FALSE;
    public $_pgDefaultParams = array();
    public $_pgParams = array();

    public function __construct()
    {
        $CI =& get_instance();
        $this->PG_ROOT = dirname(__FILE__) . '/inicis/INIformbill41';
    }

    public function setPG()
    {
        $paymethod = NULL;
        $quotainterest = NULL;
        require_once $this->PG_ROOT . '/sample/INIpay41Lib.php';
        $this->INIPAY = new INIpay41;
        return $this->INIPAY;
    }

    public function setCommand($pgCommand = FALSE)
    {
        $this->_pgCommand = FALSE;
        if (empty($pgCommand)) return FALSE;
        switch ($pgCommand) {

            case('bill'): // 빌링
                $this->_pgCommand = "formauth";
                break;
            case('pay'): // 빌링 결제
                $this->_pgCommand = "reqrealbill";
                break;
            default:        // 상기 지불수단 외 추가되는 지불수단의 경우 기본으로 paymethod가 4자리로 넘어온다.
                $this->_pgCommand = method_exists($this, $pgCommand) == TRUE ? $pgCommand : null;
        }
        return $this->_pgCommand;
    }

    public function getCommand()
    {
        return $this->_pgCommand;
    }

    public function setDefaultParams($pgDefaultParams = null, $test)
    {
        $paramsKey = array(
            'm_url' => 'home_url',                        // 홈페이지 결제시에만 사용
            'm_currency' => 'currency',                    // 화폐단위 WON : 원화결제일 경우 USD :   달러결제일 경우
            'm_authentification' => 'auth_user',            // 본인인증여부 (00-YES)

            'm_inipayHome' => 'pg_module_path',            // 이니페이 홈디렉터리 NULL입력시 자동입력
            'm_subPgIp' => FALSE,                        // 고정(절대 수정금지)
            'm_debug' => 'debug',                        // 디버그
            'm_keyPw' => 'pg_mid_password',                // 키패스워드(상점아이디에 따라 변경)
            'm_mid' => 'pg_mid',                            // 상점아이디
            'm_merchantReserved3' => 'acceptmethod',            // 사용옵션
        );
        $paramsTemp = array();
        foreach ($paramsKey as $k => $v) {
            if (isset($pgDefaultParams[$v])) $paramsTemp[$k] = $pgDefaultParams[$v];
        }
        if($test){
            $paramsTemp['m_mid'] = 'INIBillTst';
            $paramsTemp['m_keyPw'] = '1111';
        }
        $paramsTemp['m_subPgIp'] = '203.238.3.10';
        if (empty($paramsTemp['m_inipayHome'])) {
            $paramsTemp['m_inipayHome'] = $this->PG_ROOT;
        }
        $this->_pgDefaultParams = array_merge($this->_pgDefaultParams, $paramsTemp);
        return $this->_pgDefaultParams;
    }

    public function purgeParams()
    {
        $this->_pgCommand = array();
    }

    public function setParams($pgParams = null)
    {

        if (empty($this->_pgCommand)) return FALSE;
        if (is_array($this->_pgParams) == false) $this->_pgParams = array();
        $params_keys = array(
            'formauth' => array(
                'm_type' => FALSE,                            // 고정(절대 수정금지)
                'm_pgId' => FALSE,                            // 고정(절대 수정금지)
                'm_payMethod' => FALSE,                        // 결제방법(절대 수정금지)
                'm_billtype' => FALSE,                        // 결제방법(절대 수정금지)
                'm_url' => 'home_url',                        // 홈페이지

                'm_price' => 'price',                        // 금액
                'm_buyerName' => 'buyer_name',                // 구매자명
                'm_cardNumber' => 'card_number',                // 신용카드번호
                'm_authentification' => 'auth_user',            // 본인인증여부 (00-YES)
                'm_authfield1' => 'auth_field1',                // 생년월일
                'm_authfield2' => 'auth_field2',                // 신용카드 비밀번호 앞 2자리
                'm_cardExpy' => 'card_exp_year',                // 신용카드 유효기간-년 (YY)
                'm_cardExpm' => 'card_exp_month',                // 신용카드 유효기간-월 (MM)
            ),
            'reqrealbill' => array(
                'm_type' => FALSE,                           // 고정(절대 수정금지)
                'm_pgId' => FALSE,                           // 고정(절대 수정금지)
                'm_payMethod' => FALSE,                      // 결제방법
                'm_billtype' => FALSE,                       // 결제방법(절대 수정금지)
                'm_merchantReserved3' => 'acceptmethod',            // 사용옵션 1000원 미만
                'm_url' => 'home_url',                        // 홈페이지
                'm_currency' => 'currency',                   // 화폐단위

                'm_quotaInterest' => 'quotaInterest',         // 무이자할부여부 (1-YES)
                'm_cardQuota' => 'card_quota',                // 할부개월

                'm_billKey' => 'bill_key',                    // Billing 결제요청을 위한 key
                'm_cardpass' => 'card_password',              // 신용카드 비밀번호 앞 2자리
                'm_authentification' => 'auth_user',          // 본인인증여부 (00-생년월일필수)
                'm_regNumber' => 'reg_number',                // 생년월일6자리(사업자 번호)
                'm_buyerName' => 'buyer_name',                // 구매자명
                'm_buyerTel' => 'buyer_phone',                // 구매자 이동전화번호
                'm_buyerEmail' => 'buyer_email',              // 구매자 이메일

                'm_uid' => 'payment_uid',                    // 상점 주문번호
                'm_goodName' => 'good_name',                  // 상품명
                'm_price' => 'price',                         // 금액
            ),
            'cancel' => array(
                'm_type' => FALSE,               // 고정(절대 수정금지)

                'm_tid' => 'pg_code2',                    // 취소할 거래의 거래아이디
                'm_cancelMsg' => 'cancel_msg'               //
            )
        );
        $paramsKey = $params_keys[$this->_pgCommand];
        $paramsTemp = array();
        foreach ($paramsKey as $k => $v) {
            if (isset($pgParams[$v]) && $v !== NULL && $v !== FALSE) {
                $paramsTemp[$k] = $pgParams[$v];
            }
        }

        if ($this->_pgCommand == 'formauth') {
            $paramsTemp['m_type'] = 'formauth_bill';
            $paramsTemp['m_pgId'] = 'INIpayBill';
            $paramsTemp['m_payMethod'] = 'Auth';
            $paramsTemp['m_billtype'] = 'Card';
        } elseif ($this->_pgCommand == 'reqrealbill') {
            $paramsTemp['m_type'] = 'reqrealbill';
            $paramsTemp['m_pgId'] = 'INIpayBill';
            $paramsTemp['m_payMethod'] = 'Card';
            $paramsTemp['m_billtype'] = 'Card';
        } else if ($this->_pgCommand == 'cancel') {
            $paramsTemp['m_type'] = 'cancel';
        }
        $this->_pgParams = array_merge($this->_pgParams, $paramsTemp);
    }

    public function run($pgCommand = null, $pgParams = null)
    {
        if (!is_object($this->INIPAY)) $this->INIPAY = $this->setPG();
        if (!empty($pgCommand)) {
            $this->setCommand($pgCommand);
        }
        if (empty($this->_pgCommand)) return false;

        if (!empty($pgParams) && is_array($pgParams)) {
            $this->setParams($pgParams);
        }
        if (empty($this->_pgParams)) return false;

        return call_user_func(array($this, $this->_pgCommand));
    }

    public function cancel($pgParams = null)
    {
        if (!empty($pgParams) && is_array($pgParams)) {
            $this->setParams($pgParams);
        }
        if (empty($this->_pgParams)) return false;
        $this->assign_params($this->_pgParams);
        ob_start();
        $this->INIPAY->startAction();
        ob_clean();
        $result = $this->sanitize_result();
        return $result;
    }

    public function formauth($pgParams = null)
    {
        if (!empty($pgParams) && is_array($pgParams)) {
            $this->setParams($pgParams);
        }
        if (empty($this->_pgParams)) return false;
        $this->assign_params($this->_pgParams);
        ob_start();
        $this->INIPAY->startAction();
        ob_clean();
        $result = $this->sanitize_result();
        return $result;
    }

    public function reqrealbill($pgParams = null)
    {
        if (!empty($pgParams) && is_array($pgParams)) {
            $this->setParams($pgParams);
        }
        if (empty($this->_pgParams)) return false;
        $this->assign_params($this->_pgParams);
        ob_start();
        $this->INIPAY->startAction();
        ob_clean();
        $result = $this->sanitize_result();
        return $result;
    }

    public function assign_params($params = null)
    {
        if (!is_object($this->INIPAY)) $this->INIPAY = $this->setPG();
        if (!empty($pgParams) && is_array($pgParams)) {
            $this->setParams($pgParams);
        }
        if (empty($this->_pgParams) or !is_array($this->_pgParams)) return false;
        if (empty($this->_pgDefaultParams) or !is_array($this->_pgDefaultParams)) return false;
        $params = array_merge($this->_pgDefaultParams, $this->_pgParams);
        foreach ($params as $k => $v) {
            $this->INIPAY->{$k} = iconv('UTF-8', 'EUC-KR', $v);
        }
    }

    public function sanitize_result()
    {
        if (!is_object($this->INIPAY)) $this->INIPAY = $this->setPG();

        $resultKeys = array(
            'formauth' => array(
                'm_tid' => 'pg_code2',                            // 거래번호
                'm_resultCode' => 'pg_code1',                    // 결과코드 ("00"이면 결제 성공)
                'm_resultMsg' => 'pg_msg',                        // 결과내용 (결제결과에 대한 설명)
                'm_billKey' => 'bill_key',                        // 빌링키
                'm_cardCode' => 'pg_card_code',                    // 신용카드사 코드 (매뉴얼 참조)
                'm_authCertain' => 'pg_auth_certain',            // 본인인증 수행여부("00"이면 수행) (비정상 여부 확인)
                'm_authCode' => 'pg_auth_code',                    // 신용카드 승인번호
                'm_pgAuthDate' => 'pg_auth_date',                // 이니시스 승인날짜 (YYYYMMDD)
                'm_pgAuthTime' => 'pg_auth_time',                // 이니시스 승인시각 (HHMMSS)
                'm_cardPass' => 'card_password',                    // 카드 비밀번호 앞 두자리
                'm_cardKind' => 'card_kind',                    // 카드종류(개인-0,법인-1)
            ),
            'reqrealbill' => array(
                'm_tid' => 'pg_code2',                            // 거래번호
                'm_resultCode' => 'pg_code1',                    // 결과코드 ("00"이면 결제 성공)
                'm_resultMsg' => 'pg_msg',                        // 결과내용 (결제결과에 대한 설명)
                'm_authCode' => 'pg_auth_code',                    // 신용카드 승인번호
                'm_cardCode' => 'pg_card_code',                    // 신용카드사 코드 (매뉴얼 참조)
                'm_cardIssuerCode' => 'pg_cardissuer_code',        // 카드발급사 코드 (매뉴얼 참조)
                'm_authCertain' => 'pg_auth_certain',            // 본인인증 수행여부("00"이면 수행)
                'm_pgAuthDate' => 'pg_auth_date',                // 이니시스 승인날짜 (YYYYMMDD)
                'm_pgAuthTime' => 'pg_auth_time',                // 이니시스 승인시각 (HHMMSS)
//				'm_ocbSaveAuthCode'=>'pgOKCashbagSaveAuthCode',	// OK Cashbag 적립 승인번호
//				'm_ocbUseAuthCode'=>'pgOKCashbagUseAuthCode',	// OK Cashbag 사용 승인번호
//				'm_ocbAuthDate'=>'pgOKCashbagAuthDate',			// OK Cashbag 승인일시 (YYYYMMDDHHMMSS)
//				'm_eventFlag'=>'pgEventFlag',				// 각종 이벤트 적용 여부
            ),
            'cancel' => array(
                'm_tid' => 'pg_code2',                            // 거래번호
                'm_resultCode' => 'pg_code1',                    // 결과코드 ("00"이면 결제 성공)
                'm_resultMsg' => 'pg_msg',                        // 결과내용 (결제결과에 대한 설명)
                'm_pgCancelDate' => 'pg_cancel_date',                    // 신용카드 승인번호
                'm_pgCancelTime' => 'pg_cancel_time',                    // 신용카드사 코드 (매뉴얼 참조)
                'm_rcash_cancel_noappl' => 'pg_rcash_cancel_noappl',        //  현금영수증 취소 승인번호 (현금영수증 발급 취소시에만 리턴됨)
            )
        );
        $commandResult = $resultKeys[$this->_pgCommand];
        $result = array();
        foreach ($commandResult as $k => $v) {
            $result[$v] = isset($this->INIPAY->{$k}) ? iconv('EUC-KR', 'UTF-8', $this->INIPAY->{$k}) : FALSE;
//			$result[$v] = isset($this->INIPAY->{$k})?$this->INIPAY->{$k}:FALSE;
        }
        if (isset($result['pg_card_code'])) {
            $cardCodeKey = array(
                '01' => '외환',
                '03' => '롯데',
                '04' => '현대',
                '06' => '국민',
                '11' => 'BC',
                '12' => '삼성',
                '13' => 'LG',
                '14' => '신한',
                '15' => '한미',
                '16' => 'NH',
                '17' => '하나 SK 카드',
                '21' => '해외비자',
                '22' => '해외마스터',
                '23' => 'JCB',
                '24' => '해외아멕스',
                '25' => '해외다이너스'
            );
            $result['pg_card_code_name'] = isset($cardCodeKey[$result['pg_card_code']]) ? $cardCodeKey[$result['pg_card_code']] : '기타';
        }
        return $result;
    }

    // 이니시스 사용가능여부 체크
    public function is_supported()
    {
        $required_extensions = array('mcrypt', 'sockets', 'xml', 'openssl', 'iconv');
        foreach ($required_extensions as $ext_name) {
            if (!extension_loaded($ext_name)) {
                log_message('debug', 'Paymentgateway driver "' . $this->_pg_driver . '" "' . $ext_name . '" extension not loaded.');
                return FALSE;
            }
        }
        return TRUE;
    }
}

7-15. bill(빌링키 생성) 검증 룰

17-35 pay(결제) 검증 룰

-- 추가설명 수정중

application/libraries/Paymentgateway/drivers/inicis/INIformpay41

이니시스 INIformpay41 모듈 복사및 퍼미션


 

추가 드라이버 를 만든다면

다시 올리도록 하겠습니다.

 다음글 4월 9일 MS Community Open Camp 발... (3)
 이전글 [ci 드라이버] 한국 pg(결제) 드라이버 만들기 (... (4)

댓글

한대승(불의회상) / 2016/02/19 12:59:49 / 추천 0

좋은 강의 감사 합니다.

기대하고 있겠습니다. ^^

쌈닭 / 2016/02/23 17:32:56 / 추천 0

감사합니다...

드라이버는...사랑입니다...

누구야 / 2016/03/21 12:22:05 / 추천 0

좋은 강의입니다

잘 봤습니다!!

fazi / 2020/08/23 03:41:48 / 추천 0

Hi, I'm trying to create this driver in my codeignitor site, but I didn't find 이니시스 INIformpay41 모듈 복사및 퍼미션.

Can anyone here help me

변종원(웅파) / 2020/08/24 10:33:39 / 추천 0

fazi/ Payment module must be requested from INICIS. :)

https://manual.inicis.com/stdpay/