Programming/node.js2016. 12. 27. 23:04
NPM : https://github.com/voltrue2/in-app-purchase
var iap = require('in-app-purchase');

iap.config({
    verbose: true,
    //googlePublicKeyStrSandbox: "", //LIVE 먼저 실행하고 에러나면 SandBox 테스트실행함
    googlePublicKeyStrLive: "MII...............",
    googleAccToken: "6/h...........",
    googleRefToken: "9/d...........",
    googleClientID: "99.......kv.7dc.ap...ps.g....nt.com",
    googleClientSecret: "9.....4Qu"
});

iap.setup(function (error) {
    if (error) {
        // error hmm
    }
    var googleReceipt = {
        "data":'{"packageName":"kr.co.test","productId":"kr.co.test.is1","purchaseTime":155435321,
                 "purchaseState":0,"purchaseToken":"oksdf........"}', //{stringified data object}
        "signature": "qSVwa8E9z........."
    };
    iap.validate(iap.GOOGLE, googleReceipt, function (error, response) {
        if (error) {
            console.log(error);
        }
        if (iap.isValidated(response)) {
            var purchaseDataList = iap.getPurchaseData(response);
            console.log(purchaseDataList);
        }
    });
});


API 통신 로직 : node_modules\in-app-purchase\lib\google.js 참고

/** * Function to check subscription status in Google Play * @param {Object} data receipt data * @param {Function} cb callback function */ function checkSubscriptionStatus(data, cb) { data.service = constants.SERVICES.GOOGLE; if (!checkSubscriptionState) { return cb(null, data); } var packageName = data.packageName; var subscriptionID = data.productId; var purchaseToken = data.purchaseToken; var url = 'https://www.googleapis.com/androidpublisher/v2/applications/' + packageName + '/purchases/subscriptions/' + subscriptionID + '/tokens/' + purchaseToken; var state; var getSubInfo = function (next) { verbose.log(NAME, 'Get subscription info from', url); getSubscriptionInfo(url, function (error, response, body) { if (error || 'error' in body) { verbose.log(NAME, 'Failed to get subscription info from', url, error, body); state = constants.VALIDATION.FAILURE; // we must move on to validate() next(); return; }


1. googleClientID / googleClientSecret 생성하기

 1) 설정 => API 액세스 => 기존프로젝트 연결 또는 새프로젝트만들기

 

 2) Google 개발자 콘솔 들어가기 ( https://console.developers.google.com/apis/library?project=xxxx )

3) 사용자 인증 ( 프로젝트 확인 꼭!! ) oauth 생성 > 웹어플리케이션 > 리디렉션 URL ( https://developers.google.com/oauthplayground ) > clientId 및 clientSecret 확인



2. Access 및 Refresh Tokens 얻기

 1) https://developers.google.com/oauthplayground 이동 > 우측설정에서 CilentID와 Client secret 입력


2) Google Play Developer API v2 > 개발자 계정 확인 및 관리 허용 


3) Access Token (googleAccToken) / Refresh Token (googleRefToken)


※ Access Not Configured. Google Play Developer API has not been used in project

   => Google Play Android Developer API 사용으로 설정



※ The project id used to call the Google Play Developer API has not been linked in the Google Play Developer Console.

=> 설정 > API 액세스 > 프로젝트가 잘 연결되었는지 OAUTH 클라이언트 ID가 존재하는지 확인 할것



※  errors: [ [Object] ], code: 400, message: 'Invalid Value' } } 

   => 판매되는 상품에 따라서 lib/google.js 에서 url 정보를 purchases/subscriptions => purchases/products 

        변경해야되는 이슈 있음 해당 NPM 보니까 구독(subscriptions) 경우만 지원하므로
        자세한 내용은 아래 API 레퍼런스 참고 해서 수정 하거나 소스 참고해서 새로 짜는 방안도 있다.

        https://developers.google.com/android-publisher/api-ref/purchases/products
        https://developers.google.com/android-publisher/api-ref/purchases/subscriptions

         



Posted by 시니^^
Programming/node.js2016. 12. 27. 20:33

NPM : https://github.com/voltrue2/in-app-purchase


var iap = require('in-app-purchase');
iap.config({
    //verbose: true,
    //googlePublicKeyStrSandbox: "", //LIVE 먼저 실행하고 에러나면 SandBox 테스트실행함
    googlePublicKeyStrLive: "MIIBIj............",
});


iap.setup(function (error) {
    if (error) {
        console.log(error);
    }
    var googleReceipt = {
        "data":'{"packageName":"kr.co.test","productId":"kr.co.test.is1","purchaseTime":155435321,
                 "purchaseState":0,"purchaseToken":"oksdf........"}', //{stringified data object}
        "signature": "qSVwa8E9z........."
    };
    iap.validate(iap.GOOGLE, googleReceipt, function (error, response) {
        if (error) {
            console.log(error);
        }
        console.log(iap.isValidated(response));
    });
});


유니티에서 받는 데이터 중  GoogleReceipt data 값 어떤 걸로 넣는지 찾는데 삽질 2시간 OTL....... 



Hash 검증 로직 : node_modules\in-app-purchase\lib\google.js 참고

function validatePublicKey(receipt, pkey, cb) {
    if (!receipt || !receipt.data) {
        return cb(new Error('missing receipt data'));
    }
    if (!pkey) {
        return cb(new Error('missing public key'));
    }
    if (typeof receipt.data !== 'string') {
        return cb(new Error('receipt.data must be a string'));
    }
    var validater = crypto.createVerify('SHA1');
    var valid;
    validater.update(receipt.data);
    try {
        valid = validater.verify(pkey, receipt.signature, 'base64');
    } catch (error) {
        return cb(error);
    }
    if (valid) {
        // validated successfully
        var data = JSON.parse(receipt.data);
        data.status = constants.VALIDATION.SUCCESS;
        return cb(null, data);
    }
    // failed to validate
    cb(new Error('failed to validate purchase'));
}


GooglePublicKey는 해당 어플리케이션 들어가서 확인 



Posted by 시니^^
Programming/node.js2016. 12. 22. 11:01

https://github.com/expressjs/body-parser


A new body object containing the parsed data is populated on the request object after the middleware (i.e. req.body). This object will contain key-value pairs, where the value can be a string or array (when extended is false), or any type (when extended is true).


POST FORM (Content-Type:application/x-www-form-urlencoded)

$ curl --noproxy '*' -i -XPOST 'http://localhost/post_test' -d 'array[key1][key2]=233'
app.use(bodyParser.urlencoded({ extended: false }));
 // req.body : { 'array[key1][key2]': '233' }
app.use(bodyParser.urlencoded({ extended: true })); 
// req.body : { array: { key1: { key2: '233' } } }


Posted by 시니^^