본문 바로가기

IT개념

애플페이 웹연동 - 1. 인증 연동 가이드

728x90

애플페이 인증 연동개발을 하게 됐습니다.

국내 간편결제사처럼 친절한 가이드나 레퍼런스가 없어 어려움을 겪었는데요,

승인을 위해 인증결과 데이터 복호화가 필요했는데, 이 부분에서 많이 헤매었습니다.

애플페이를 연동하는 국내 다른 웹 개발자 분들에게 도움이 됐으면 싶어 가이드를 작성합니다.

 

https://developer.apple.com/documentation/apple_pay_on_the_web/setting_up_your_server

이하 내용은 위 링크의 developer 가이드를 기반으로 Web 연동에 대해 작성했습니다.

 

 

 

1. 서버 세팅

1-1. 애플페이 연동을 위해서 우선 본인의 웹사이트가 필요합니다.

* TLS 1.2 이상의 인증이 완료된 HTTPS 서버여야 합니다.

 

1-2. Apple Pay IP를 허용합니다.

https://developer.apple.com/documentation/apple_pay_on_the_web/setting_up_your_server#3172427

 

Apple Developer Documentation

 

developer.apple.com

IP 목록은 위 링크와 같습니다.

 

 

 

 

2. 환경 세팅

Apple Pay를 이용하기 위해서는 사전 Apple에 가맹점 ID(Merchant ID), 지불 처리 인증서(Payment Processing Certificate), 가맹점 인증서(MerchantIdentity Certificate) 이렇게 총 3가지를 등록하여야 합니다.

 

2-1. 가맹점 ID(Merchant ID)를 등록합니다.

      Merchant ID, 가맹점임을 인증하기 위해 Apple에 등록하는 식별자입니다. 


      https://help.apple.com/developer-account/#/dev1731126fb

 

https://help.apple.com/developer-account/#/dev1731126fb

To see this page, you must enable JavaScript. Pour afficher cette page, vous devez activer JavaScript. Zur Anzeige dieser Seite müssen Sie JavaScript aktivieren. このページを表示するには、JavaScript を有効にする必要があります。

help.apple.com

 

2-2. 지불 처리 인증서(Payment Processing Certificate)를 등록합니다.

인증서 가맹점 ID와 연결되며 가맹점 식별자와 연결되어 결제 정보를 암호화하는 데 사용됩니다. 25개월의 만료기간이 있으며 취소하고 다시 만들 수 있습니다.

https://help.apple.com/developer-account/#/devb2e62b839?sub=devf31990e3f 

 

https://help.apple.com/developer-account/#/devb2e62b839?sub=devf31990e3f

To see this page, you must enable JavaScript. Pour afficher cette page, vous devez activer JavaScript. Zur Anzeige dieser Seite müssen Sie JavaScript aktivieren. このページを表示するには、JavaScript を有効にする必要があります。

help.apple.com

 

2-3. 가맹점 인증서(MerchantIdentity Certificate)를 등록합니다.

결제 시도 시 요청하는 사이트가 등록되어있는 올바른 가맹점이맞는지 검증하기 위한 인증서입니다. 별도의 만료기간은 없습니다.

 

애플페이 가맹점 인증 시 SSL을 이용한 연결이 필요합니다.

*trustStore을 이용하여 애플에 업로드한 인증서를 저장하고 요청 시 SSL통신을 통해 인증할 수 있습니다.

https://help.apple.com/developer-account/#/devb2e62b839?sub=dev103e030bb 

 

https://help.apple.com/developer-account/#/devb2e62b839?sub=dev103e030bb

To see this page, you must enable JavaScript. Pour afficher cette page, vous devez activer JavaScript. Zur Anzeige dieser Seite müssen Sie JavaScript aktivieren. このページを表示するには、JavaScript を有効にする必要があります。

help.apple.com

 

*2022-12-09

애플 공식 가이드가 수정되어 위 링크를 참고할 수 없는 것 같습니다.

맥의 경우 키체인을 통해 인증서를 발급받아 업로드하면 되고 윈도우의 경우 openSSL을 사용하여 인증서를 생성하여 업로드하면 됩니다.

서버 인증시에는 업로드한 파일을 다시 Download하여 pem파일 또는 p12파일로 변환하여 서버에 사용하면 되는데 이 과정이 조금 멜랑꼴리합니다. 구글링 하시면 다른 분들이 작성한 가이드가 많이 있더라고요,, 참고하시길..!

 

 

 

 

2-4. 도메인 인증 (verify)

가맹점 등록 후 도메인 인증 txt 파일을 다운로드받아 서버 내 지정된 위치에 업로드 후 verify하는 과정이 필요합니다.

 

이 과정이 완료 되면 우선 환경 설정은 모두 끝났습니다.

인증과정이 많아 상당히 복잡합니다...

 

 

 

3. 연동 개발

이제 결제창을 띄울 화면을 만들면 되는데요, developer에서 제공하는 가이드를 보면 상당히 난해하게 느껴집니다.

별도 데모 페이지에서 제공해주는 샘플이 더 직관적으로 와닿으므로 이 방법을 추천드립니다.

https://applepaydemo.apple.com/

 

Apple Pay on the Web Demo

Learn how to enable Apple Pay on the web using Apple Pay JS.

applepaydemo.apple.com

 

위 링크에 들어가면 WebDemo 원문을 볼 수 있습니다.

JS 방식과 API 방식이 있는데 둘 다 JS로 약간 다른 형식의 같은 소스를 소개하고 있는데요, 저는 전자의 방식을 기준으로 설명드리겠습니다.

 

 

3-1. CDN 추가

<script src="https://applepay.cdn-apple.com/jsapi/v1/apple-pay-sdk.js"></script>

 

 

연동할 페이지에 위 script를 추가합니다.

 

 

3-2. 샘플 소스 추가하기

 

function onApplePayButtonClicked() { 	// 결제버튼을 클릭할 시 이 함수를 실행시켜야 합니다.

    if (!ApplePaySession) {	// ApplePay 세션이 살아있는지 확인합니다. (애플페이는 사파리에서만 가능)
        return;
    }
    
    // Define ApplePayPaymentRequest	// 결제정보 객체입니다.
    const request = {
        "countryCode": "US",			// 국가코드
        "currencyCode": "USD",			// 화폐코드
        "merchantCapabilities": [		// 결제 타입 종류 선언
            "supports3DS"				// 필수 값
        ],
        "supportedNetworks": [			// 결제 가능한 카드사 선언
            "visa",
            "masterCard",
            "amex",
            "discover"
        ],
        "total": {						// 상품명, 가격.. 인증창 호출 시 표기됩니다.
            "label": "Demo (Card is not charged)",
            "type": "final",
            "amount": "1.99"
        }
    };
    
    // Create ApplePaySession 애플페이 세션 생성 (요청버전, 요청객체)
    const session = new ApplePaySession(3, request);
    
    session.onvalidatemerchant = async event => {	// 가맹점 검증 (보안 상 server to server로 검증하여야 합니다.)
        $.ajax({
			url : "/applepay/validate",		// 소유한 서버의 URL
			data : {
				"validationURL":event.validationURL	// *중요! applepay에 검증요청할 URL입니다.
			},
			method: "POST",
			cache : false
		}).then(function (merchantSession) {
			// 가맹점 검증 이후 동작하는 로직입니다.
			session.completeMerchantValidation(JSON.parse(merchantSession));	// 검증 complete 이벤트 호출
		});
    };
    
    // 애플페이 화면에서 결제수단 선택 및 변경 시 호출할 이벤트 입니다. (가맹점 페이지 상황에 맞게 사용)
    session.onpaymentmethodselected = event => {
        // Define ApplePayPaymentMethodUpdate based on the selected payment method.
        // No updates or errors are needed, pass an empty object.
        const update = {};
        session.completePaymentMethodSelection(update);
    };
    
    // 애플페이 화면에서 발송방법 선택 및 변경 시 호출 이벤트 (가맹점 페이지 상황에 맞게 사용)
    session.onshippingmethodselected = event => {
        // Define ApplePayShippingMethodUpdate based on the selected shipping method.
        // No updates or errors are needed, pass an empty object. 
        const update = {};
        session.completeShippingMethodSelection(update);
    };
    
    // 배송 주소 선택 시 호출 이벤트 (locality, country, postalCode, administrativeArea, contryCode)
    session.onshippingcontactselected = event => {
        // Define ApplePayShippingContactUpdate based on the selected shipping contact.
        const update = {};
        session.completeShippingContactSelection(update);
    };
    
    // 인증 성공시 호출 메소드 (가맹점의 결제 로직을 아래 호출부에 함께 작성하여 구현하게 될 것 입니다.)
    session.onpaymentauthorized = event => {	// event 인자에 인증결과 데이터가 들어있음..!
        // Define ApplePayPaymentAuthorizationResult
        const result = {
            "status": ApplePaySession.STATUS_SUCCESS
        };
        session.completePayment(result);
    };
    
    // 쿠폰코드 입력 시 호출 이벤트
    session.oncouponcodechanged = event => {
        // Define ApplePayCouponCodeUpdate
        const newTotal = calculateNewTotal(event.couponCode);
        const newLineItems = calculateNewLineItems(event.couponCode);
        const newShippingMethods = calculateNewShippingMethods(event.couponCode);
        const errors = calculateErrors(event.couponCode);
        
        session.completeCouponCodeChange({
            newTotal: newTotal,
            newLineItems: newLineItems,
            newShippingMethods: newShippingMethods,
            errors: errors,
        });
    };
    
    // 결제 취소시 호출 이벤트
    session.oncancel = event => {
        // Payment cancelled by WebKit
    };
    
    session.begin();
}

 

 

이 과정을 완료하면 애플 페이 인증 연동이 완료되며 이후 승인단은 인증 이후 함수에서 서버 전송을 통해 처리하면 됩니다.

 

 

3-3. 애플 페이 버튼 디자인

기본 html 버튼으로 애플페이 결제버튼을 만들어도 상관없지만 애플에서는 Apple Pay의 UI를 사용하기 권장하고 있습니다.

https://developer.apple.com/documentation/apple_pay_on_the_web/displaying_apple_pay_buttons_using_javascript

 

Apple Developer Documentation

 

developer.apple.com

부트스트랩처럼 field class에 nameing 부여해주면 되니 위 링크 참고해주세요.

 

 

 

대략적인 흐름에 대해 적어보았는데 각 필드나 함수에 대해 더 자세한 정보는 Apple에서 제공하는 가이드 문서에 검색하여 보는 것을 추천드립니다.

 

 

 

다음 기회가 되면 결제 데이터 복호화하는 과정에 대해서도 작성해보겠습니다.

 

'IT개념' 카테고리의 다른 글

애플페이 웹연동 - 2. 결제 데이터 복호화  (0) 2022.12.07