블로그 이미지
래머
오늘도 열심히 개발하는 개발자입니다.

calendar

1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31

Notice

2016. 10. 28. 14:02 안드로이드

원문 : https://developers.google.com/identity/sign-in/web/backend-auth


구글플레이 서비스 SDK를 통해서 클라이언트측에서 로그인하고 인증 정보를 서버로 넘겨서 서버측에서 클라이언트의 인증 정보를 검증하는 방법은 아래와 같다.


https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=XYZ123

위주소의 XYZ123부분에 클라이언트가 보내온 액세스 토큰을 넣고 Post또는 Get요청을 보내면 응답을 받을 수 있다.


HTTP 200응답이 수신될경우 JSON포맷의 결과 값을 받게 되고, 대략 아래와 같은 형태이다.



{
 // These six fields are included in all Google ID Tokens.
 "iss": "https://accounts.google.com",
 "sub": "110169484474386276334",
 "azp": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com",
 "aud": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com",
 "iat": "1433978353",
 "exp": "1433981953",

 // These seven fields are only included when the user has granted the "profile" and
 // "email" OAuth scopes to the application.
 "email": "testuser@gmail.com",
 "email_verified": "true",
 "name" : "Test User",
 "picture": "https://lh4.googleusercontent.com/-kYgzyAWpZzJ/ABCDEFGHI/AAAJKLMNOP/tIXL9Ir44LE/s99-c/photo.jpg",
 "given_name": "Test",
 "family_name": "User",
 "locale": "en"
}

이중에서 aud값에 앱의 클라이언트 ID를 담고 있는데 일치 하는지 확인하고 일치한다면,

sub 항목을 유저의 ID로 사용하면된다. sub항목은 구글에서 개인을 식별할 수 있는 유니크 ID이다.



posted by 래머
2014. 6. 1. 05:50 안드로이드

이클립스로 안드로이드 레이아웃편집시 이클립스의 응답속도가 지나치게 느리다면

자바메모리 힙이 부족하지 않은지 확인해봐야 한다.

메모리가 부족할 경우 이클립스의 작업 응답속도가 느려질 수 있다.


이럴때는 다음과 같이 이클립스의 바로가기 설정을 통해서 자바의 메모리 관련 설정을 해줄 수 있다.



F:\adt-bundle-windows-x86\eclipse\eclipse.exe -vmargs - Xms1024m -Xmx1024m -XX:MaxPermSize=256m








posted by 래머
2014. 5. 3. 23:43 안드로이드

첨부된 바운시캐슬 암호화 라이브러리를 참조에 추가하고 사용해야 한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
using System;
 
using System.Security.Cryptography;
 
using System.IO;
 
using System.Text;
 
using System.Xml;
 
using System.Collections.Generic;
 
using System.Linq;
 
using Org.BouncyCastle.Security;
 
using Org.BouncyCastle.Crypto;
 
using Org.BouncyCastle.Crypto.Parameters;
 
 
 
 
/*
사용법
GoogleSignatureVerify gsv = new GoogleSignatureVerify("발급받은 API키");
if (gsv.Verify("결제데이터", 사인데이터))
{
//성공시 처리
}
*/
 
public class GoogleSignatureVerify
 
    {
 
        RSAParameters _rsaKeyInfo;
 
 
 
 
        public GoogleSignatureVerify(String GooglePublicKey)
 
        {
 
            RsaKeyParameters rsaParameters = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(GooglePublicKey));
 
 
 
 
            byte[] rsaExp = rsaParameters.Exponent.ToByteArray();
 
            byte[] Modulus = rsaParameters.Modulus.ToByteArray();
 
 
 
 
            // Microsoft RSAParameters modulo wants leading zero's removed so create new array with leading zero's removed
 
            int Pos = 0;
 
            for (int i = 0; i < Modulus.Length; i++)
 
            {
 
                if (Modulus[i] == 0)
 
                {
 
                    Pos++;
 
                }
 
                else
 
                {
 
                    break;
 
                }
 
            }
 
            byte[] rsaMod = new byte[Modulus.Length - Pos];
 
            Array.Copy(Modulus, Pos, rsaMod, 0, Modulus.Length - Pos);
 
 
 
 
            // Fill the Microsoft parameters
 
            _rsaKeyInfo = new RSAParameters()
 
            {
 
                Exponent = rsaExp,
 
                Modulus = rsaMod
 
            };
 
        }
 
 
 
 
        public bool Verify(String Message, String Signature)
 
        {
 
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
 
            {
 
                rsa.ImportParameters(_rsaKeyInfo);
 
                return rsa.VerifyData(Encoding.ASCII.GetBytes(Message), "SHA1", Convert.FromBase64String(Signature));
 
            }
 
        }
 
    }
 
 
 
cs

BouncyCastle.Crypto.dll

유니티를 사용하신다면 아래 유니티 패키지를 임포트 하시면 바운시 캐슬 라이브러리소스가 임포트됩니다.


BouncyCastle.unitypackage



posted by 래머
2014. 5. 3. 23:11 안드로이드
유니티에서 사용하고자 하는경우 아래 코드를 추가하시고
InitCertificateValidationCallback()을 영수증 검증 루틴 실행전 한번 호출해줄필요가 있습니다.

public static void InitCertificateValidationCallback()
        {
            ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(ValidateServerCertificate);
        }

        static bool ValidateServerCertificate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }

c#으로 작성된 서버 또는 유니티 등에서 티스토어의 인앱 결제 영수증 검증을 다음과 같이 하면된다.



readonly string TSTORE_RECEIPT_VERIFY_URL_PRODUCT = "https://iap.tstore.co.kr/digitalsignconfirm.iap";  //실서비스용서버주소

        readonly string TSTORE_RECEIPT_VERIFY_URL_DEV = "https://iapdev.tstore.co.kr/digitalsignconfirm.iap"; //개발용서버주소

        readonly string TSTORE_RECEIPT_VERIFY_FORMAT = "{{\"txid\" : \"{0}\", \"appid\" : \"{1}\", \"signdata\" : \"{2}\"}}";

        //TStore 영수증 검중구현, 

//bProduct : 서비스/개발용 서버중 어느 서버에서 검증할지

//strAppID : 티스토어에 배포한 프로그램에 할당받은 ID

//strTXID : 인앱 결제후 결과 값으로 넘어온 것중 txid

//strReceipt : 인앱결제 후 결과 값으로 넘어온 영수증 정보

//리턴값이 true인경우 영수증검증에 성공한것이다.

//애플의 영수증을 검증하는 것처럼 먼저 bProduct에 true를 해서 영수증검증을 해보고 만일 실패 하는경우

//false를 줘서 검증을 시도하도록 하면 된다.

        bool VerifyTStoreReceipt(bool bProduct, string strAppID, string strTXID, string strReceipt)

        {

            try

            {

                // Verify the receipt with Apple

                string postString = String.Format(TSTORE_RECEIPT_VERIFY_FORMAT, strTXID, strAppID, strReceipt);

                ASCIIEncoding ascii = new ASCIIEncoding();

                byte[] postBytes = ascii.GetBytes(postString);

                HttpWebRequest request;


                if (bProduct)

                    request = WebRequest.Create(TSTORE_RECEIPT_VERIFY_URL_PRODUCT) as HttpWebRequest;

                else

                    request = WebRequest.Create(TSTORE_RECEIPT_VERIFY_URL_DEV) as HttpWebRequest;


                request.Method = "POST";

                request.ContentType = "application/json";

                request.ContentLength = postBytes.Length;

                Stream postStream = request.GetRequestStream();

                postStream.Write(postBytes, 0, postBytes.Length);

                postStream.Close();


                HttpWebResponse response = request.GetResponse() as HttpWebResponse;

                StringBuilder sb = new StringBuilder();

                byte[] buf = new byte[8192];

                Stream resStream = response.GetResponseStream();

                string tempString = null;


                int count = 0;


                do

                {

                    count = resStream.Read(buf, 0, buf.Length);

                    if (count != 0)

                    {

                        tempString = Encoding.ASCII.GetString(buf, 0, count);

                        sb.Append(tempString);

                    }

                } while (count > 0);


                var fd = JObject.Parse(sb.ToString());


                try

                {

                    resStream.Close();

                    response.Close();

                }

                catch

                {

                }


                string strResult = fd["status"].ToString();

                string strDetail = fd["detail"].ToString();


                // Receipt not valid

                if (strResult == null || strResult != "0" || strDetail == null || strDetail != "0000")

                {

#if DEBUG

                    CLogMng.Instance().Debug("tstore purchase failed : " + sb.ToString());

                    CLogMng.Instance().Debug("txid : " + strTXID);

                    CLogMng.Instance().Debug("signdata : " + strReceipt);

#endif

                    return false;

                }

            }

            catch// (Exception ex)

            {

                // We crashed and burned -- do something intelligent

                return false;

            }


            return true;

        }




posted by 래머
2014. 5. 2. 00:51 안드로이드



프로가드 오류

SDK에 기본적으로 포함되어있는 프로가드를 사용해서 유니티 프로젝트로 부터 뽑은 안드로이드 프로젝트를 난독화 하게 되면
오류가 발생한다.
유니티의 classes.jar 파일이 이미 난독화 처리가 되어 프로가드가 해당 파일을 읽을때 오류가 발생하는 문제인데
Caused by: java.io.IOException: Can't process class [com/unity3d/player/UnityPlayer.class] (Unknown verification type [230] in stack map frame)
대략 이런 유형의 에러메시지가 난다.

이번에 ADT버전업을 하면서 프로가드 까지 갱신되버려서 또 같은 문제가 생겼다.

 인터넷에 나와 있는 여러가지 해결책을 모두 적용해봐도 해결이 안돼서 한동안 고심했었다.
프로가드 제작자가 제시한 해결책은 stack map frame관련해서 소스의 특정 부분을 어떤 값으로 바꾸고 재컴파일하면된다고
했던 기억만 가물가물하게 나는데
구체적으로 어떻게 해결했는지 자세히 기억은 안나지만
소스를 수정하고 다시 컴파일해서 proguard.jar파일을 만든다음
해당 파일을 안드로이드 sdk의 
adt-bundle-windows-x86\sdk\tools\proguard\lib\ 대략 이런 경로에 있는 프로가드 jar파일과 교체하면된다.

Unknown verification type [230] in stack map frame 라고 구글링을 해보면 자세한 내용이 나올테지만 귀찮아서 안할란다.
다행히 그때 만든 jar파일을 하드 구석탱이에서 찾아서 넣어보니 잘된다.



다운로드 링크

proguard.jar







posted by 래머
2014. 5. 2. 00:50 안드로이드



[구글인앱]Testing Your In-app Billing Application(인앱 빌링 애플리케이션 테스트) #5


Testing Your In-app Billing Application(인앱빌링 애플리케이션 테스트)


To ensure that In-app Billing is functioning correctly in your application, you should test the test the application before you publish it on Google Play. Early testing also helps to ensure that the user flow for purchasing in-app items is not confusing or slow, and that users can see their newly purchased items in a timely way.
당신의 애플리케이션에서 인앱빌링 기능이 올바르게 동작하는것을 보증하기 위해, 구글 플레이에 게시전 애플리케이션을 테스트해야한다. 초기의 테스트는 또한 유저의 인앱 아이템 결제 흐름이 혼란스럽거나 느리지 않는지 확인하고, 유저가 그들의 새로운 구매 아이템을 적시에 보여줄 수 있는지 확인하는데 도움된다.

Test with Static Responses(정적응답을 통한 테스트)



Test your In-app Billing application with static responses by using Google Play’s reserved product IDs.By using reserved product IDs instead of actual product IDs, you can test the purchase flow without specifying an actual payment method or transferring money. To learn more about the reserved product IDs, see Testing In-app Billing

구글의 예약된 제품Id들을 사용해서 정적인 응답으로 애플리케이션을 테스트할수 있다. 실제 제품의 ID들 대신에 예비된 제품ID를 사용하는것으로, 당신은 실제 지불메소드나, 금전 지급을 하지 않고 구매 흐름을 테스트할 수 있다. 예비된 제품 ID들에 대해서 좀더 알기 위해, Testing In-app Billing을보라.

Test with Your Own Product IDs(자신의 제품ID를 사용한 테스트)


Because Google Play does not allow you to use your developer account to directly purchase in-app products that you have created yourself, you'll need to create test acccounts under your developer account profile. To create a test account, simply enter a valid Google email address. Users with these test accounts will then be able to make in-app-billing purchases from uploaded, unpublished applications that you manage.
구글은 당신 자신이 생성한 인앱 제품들에 당신의 개발자 계정을 직접적으로 사용하는 것을허용하지 않기 때문에, 당신의 개발자 계정 프로파일에 테스트 계정을 생성할 필요가 있다. 테스트 계정을 생성하기 위해서, 단순하게 올바른 구글 이메일 주소를 입력하면된다. 이 테스트계정의 유저들은 당신이 관리하는 업로드된, 아직 계시하지 않은 애플리케이션들로 부터 인앱 빌링 구매를 사용할 수 있다.
To test your In-app Billing Version 3 application using your own product IDs:(당신의 제품ID를 사용하여 인앱 빌링 버전3애플리케이션 테스트하기:)
  1. In the Developer Console, add one or more tester accounts to the developer account that you are using to publish your application.(개발자 콘솔에서, 하나 또는 더많은 테스터 계정을 당신에 출시할 애플리케이션의 개발자 계정에 추가한다, )
    1. Login to the Developer Console with your developer account.(개발자 계정으로 개발자 콘솔에 로그인)
    2. Click Settings > Account details, then in the License Testing section, add the Google email addresses for your tester accounts.(셋팅클릭->계정세부, 이때 라이센스 테스팅 섹션에서, 당신의 테스터들의 이메일 계정을 추가한다)
  2. Build a signed APK file for your In-app Billing application. To learn how to build and sign your APK, seeBuilding Your Application for Release. Make sure that you are using your final (not debug) certificate and private key to sign your application.(당신의 인앱빌링 애플리케이션을 서명된 APK로 빌드한다. 서명된 APK 빌드 방법을 배우기 위해 Building Your Application for Release를 보라. 당신의 최종(디버그가아닌) 인증서와 개인키로 사인하는지 확인한다.)
  3. Make sure that you have uploaded the signed APK for your application to the Developer Console, and associated one or more in-app products with your application. You don't need to publish the application on Google Play to test it.(개발자 콘솔에 사인된 APK를 업로드하고, 하나 이상의 인앱 제품을 애플리케이션과 연합시킨다. 당신은 구글플레이에서의 테스트를 위해서 제품을 게시할 필요없다.)
    Warning: It may take up to 2-3 hours after uploading the APK for Google Play to recognize your updated APK version. If you try to test your application before your uploaded APK is recognized by Google Play, your application will receive a ‘purchase cancelled’ response with an error message “This version of the application is not enabled for In-app Billing.”
    경고 : 구글플레이에서 당신이 업데이트한 APK의 버전을 확인하기까지 2~3시간정도 소요딘다. 만일 구글플레이에서 APK확인전에 테스트를 시도할 경우, 당신의 애플리케이션은 '결제취소'응답을 에러메시지('이버전의 애플리케이션은 인앱 빌링이 허용되지 않는다')와 함께 수신할 것이다.
  4. Install the APK file to your physical test device by using the adb tool. To learn how to install the application, see Running on a Device. Make sure that:(APK파일을 adb 툴을 사용하여 물리 디바이스에 인스톨한다. 애플리케이션을 어떻게 인스톨하는지 배우기 위해, Running on a Device를 보라. 확인사항들 : )
    • Your test device is running on Android SDK Version 2.2 (API level 8) or higher, and is installed with Google Play client Version 3.9.16 or higher.(당신의 테스트 디바이스는, 안드로이드 SDK 버전 2.2(API 레벨 8) 또는 그이상의 버전과, 구글 플레이 클라이언트 버전 3.9.16 또는 이상의 버전을 실행 중 이어야 한다)
    • The android:versionCode and android:versionName attributes values in the AndroidManifest.xml of the application that you are installing matches the values of your APK in the Developer Console.(AndroidManifest.xml android:versionCode 와 android:versionName 속성값들은 개발자 콘솔의 업로드한 APK의 값과 인스톨한 버전의 값이 일치하는 값을 가져야한다.)
    • Your application is signed with the same certificate that you used for the APK that you uploaded to the Developer Console, before installing it on your device.(당신의 애플리케이션은 디바이스에 인스톨하기 전에 개발자 콘솔에 업로드한 APK가 사용하는것과 같은 인증서로 서명되어야 한다.)
  5. Login to the test device by using a tester account. Test your In-app Billing application by purchasing a few items, and fix any issues that you encounter. Remember to refund the purchases if you don’t want your testers to be actually charged!(테스트 계정을 사용하여, 테스트디바이스에 로그인한다. 몇 몇 아이템들을 구매하는 것으로 인앱 빌링 애플리케이션을 테스트하고, 발생하는 문제들을 고친다. 기억해야 할것은 테스터들이 실제 지불하는 것을 원하지 않는다면, 구매 환불을 해야한다.)




posted by 래머
2014. 5. 2. 00:48 안드로이드



[구글인앱]Purchasing In-app Billing Products(인앱 빌링 제품 구매하기) #4


Purchasing In-app Billing Products(인앱 빌링 제품 구매하기)

Once your application is connected to Google Play, you can initiate purchase requests for in-app products. Google Play provides a checkout interface for users to enter their payment method, so your application does not need to handle payment transactions directly.
단한번 당신의 애플리케이션은 구글플레이에 연결되고, 인앱 제품의 구매 요구를 시작할 수 있다. 구글플레이는 유저가 그들의 지불 메소드에 진입할 수 있도록 결제 인터페이스를 제공한다, 그렇기 때문에 당신의 애플리케이션은 지불 트랜젝션을 직접적으로 다룰필요 없다.
When an item is purchased, Google Play recognizes that the user has ownership of that item and prevents the user from purchasing another item with the same product ID until it is consumed. You can control how the item is consumed in your application, and notify Google Play to make the item available for purchase again.
아이템이 구매되었을때, 구글플레이는 사용자가 아이템을 소유했음을 인지하고, 유저가 같은 ID를 가진 아이템을 소모하기 전에  재구매하는 것을 방지한다. 당신은 애플리케이션에서 어떻게 아이템이 소비될지 제어 할 수 있고, 구글플레이에 다시 구매가 가능한 아이템으로 만들 수 있다.
You can also query Google Play to quickly retrieve the list of purchases that were made by the user. This is useful, for example, when you want to restore the user's purchases when your user launches your app.
당신은 또한, 구글 플레이로 부터 빠르게 유저가 구매한 아이템들의 목록을 되찾을 수 있다. 이것은 유저가 당신의 앱을 실핼 할때 구매한 제품들을 다시 복구하는데 유용하다.

Purchase an Item(아이템 구매)


To start a purchase request from your app, call launchPurchaseFlow(Activity, String, int, OnIabPurchaseFinishedListener, String) on your IabHelper instance. You must make this call from the main thread of your Activity. Here’s an explaination of the launchPurchaseFlow method parameters:
앱에서 구매 요구를 시작하기 위해서, launchPurchaseFlow(Activity, String, int, OnIabPurchaseFinishedListener, String) 메소드를  IabHelper 의 인스턴스에서 호출한다. 당신은 반드시 액티비티의 메인 쓰레드에서 호출되도록해야한다. 여기에 launchPurchaseFlow 파라메터들의 설명이있다:
  • The first argument is the calling Activity.(첫번쨰 인자는 호출하는 액티비티다.)
  • The second argument is the product ID (also called its SKU) of the item to purchase. Make sure that you are providing the ID and not the product name. You must have previously defined and activated the item in the Developer Console, otherwise it won’t be recognized.(두번째 인자는 구매할 제품의 ID다(또한 SKU라 불려진다). 재품의 이름이 아닌 제품의 ID를 제공하는 지 확인해야한다. 반드시 이전에 개발자 콘솔에서 아이템을 선언하고 할성화 시켜야한다, 그렇지 않을경우 그것은 인정되지 않을것이다.)
  • The third argument is a request code value. This value can be any positive integer. Google Play reurns this request code to the calling Activity’s onActivityResult along with the purchase response.(세번째 인자는 요청 코드 값이다 이것은 임의의 양의 정수 값이 될 수 있다. 구글 플레이는 구매 응답시 Activity 의 onActivityResult 호출할때 요청코드를 되돌려준다.)
  • The fourth argument is a listener that is notified when the purchase operation has completed and handles the purchase response from Google Play.(네번째 인자는 구매 작업이 완료될때 통지 받는 리스너다, 구글 플레이로 부터 구매 응답을 받아 다룬다.)
  • The fifth argument contains a ‘developer payload’ string that you can use to send supplemental information about an order (it can be an empty string). Typically, this is used to pass in a string token that uniquely identifies this purchase request. If you specify a string value, Google Play returns this string along with the purchase response. Subsequently, when you make queries about this purchase, Google Play returns this string together with the purchase details.(5번쨰 인자는 '개발자 payload' 스트링을 담고 있다, 당신은 주문에 대한 추가정보를 담아 보낼 수 있다(이것은 빈문자열이 될수있다). 일반적으로, 이것은 구매 요청의 유일한 식별자를 담는 스트링 토큰으로 전될되는데 사용된다. 만일 스트링 값을 지정하는 경우, 구글플레이는 구매 응답과 함께 스트링을 되돌려준다. 이어서, 이 구매에 대해 조회할때, 구글 플레이는 응답 상세 정보에 스트링을 함께 포함하여 되돌려준다.)
    Security Recommendation: It’s good practice to pass in a string that helps your application to identify the user who made the purchase, so that you can later verify that this is a legitimate purchase by that user. For consumable items, you can use a randomly generated string, but for non-consumable items you should use a string that uniquely identifies the user.
    보안권고 : 스트링에 어떤유저가 구매하는지 애플리케이션에 도움이 되는 식별자를 담아 보내는것은 좋은 습관이다, 이럴경우 당신은 이후에 구매가 합법적인지 검증할 수 있다. 소모성 아이템들에 대해서, 임의로 생성된 스트링을 사용할 수 있다, 그러나 비 소모성 아이템들은 유저별 고유식별자를 사용하여야한다.
The following example shows how you can make a purchase request for a product with ID SKU_GAS, using an arbitrary value of 10001 for the request code, and an encoded developer payload string.
다음의 예는 제품 ID SKU_GAS의 구매 요청을 어떻게 만드는지 보여준다, 임의의 10001 값을 요청 코드로 하고 , 인코딩된 payload 문자열을 사용한다.
mHelper.launchPurchaseFlow(this, SKU_GAS, 10001,   
   mPurchaseFinishedListener, "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ");
If the purchase order is successful, the response data from Google Play is stored in an Purchase object that is passed back to the listener.
구매 주문이 성공한다면, 구글플레이로부터의 응답 데이터는 Purchase 오브젝트를  담아 리스너에 전달된다.
The following example shows how you can handle the purchase response in the listener, depending on whether the purchase order was completed successfully, and whether the user purchased gas or a premium upgrade. In this example, gas is an in-app product that can be purchased multiple times, so you should consume the purchase to allow the user to buy it again. To learn how to consume purchases, see the Consuming Productssection. The premium upgrade is a one-time purchase so you don’t need to consume it. It is good practice to update the UI immediately so that your users can see their newly purchased items.
다음 예는 구매 주문이 성공했는지에 따라서, 유저가 가스 또는 프리미엄 업그레이드를 하는지에 따라서 리스너에서 구매 응답을 어떻게 다루는지 보여준다. 예제에서, 가스 인앱 제품은 계속적인 구매가 가능하다, 그렇기 때문에 유저가 그것을 다시 살수 있게 하기 위해서 소비를 해야한다. 구매를 어떻게 소비하는지 배우기 위해서, Consuming Products를 보라. 프리이엄 업그레이드는 단 한번 구매한다, 그렇기 때문에 그것을 소비할 필요없다. 즉각 적인 UI업데이트는 좋은 방법이다, 유저는 그들이 새로 구매한 아이템들을 볼 수 있을 것이다.
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener 
   = new IabHelper.OnIabPurchaseFinishedListener() {
   public void onIabPurchaseFinished(IabResult result, Purchase purchase) 
   {
      if (result.isFailure()) {
         Log.d(TAG, "Error purchasing: " + result);
         return;
      }      
      else if (purchase.getSku().equals(SKU_GAS)) {
         // consume the gas and update the UI
      }
      else if (purchase.getSku().equals(SKU_PREMIUM)) {
         // give user access to premium content and update the UI
      }
   }
};
Security Recommendation: When you receive the purchase response from Google Play, make sure to check the returned data signature, the orderId, and the developerPayload string in the Purchase object to make sure that you are getting the expected values. You should verify that the orderId is a unique value that you have not previously processed, and the developerPayload string matches the token that you sent previously with the purchase request. As a further security precaution, you should perform the verification on your own secure server.
보안권고 : 구글 플레이로부터 구매 응답을 수신했을때, Purchase로 되돌려진 데이터의 서명(signature), orderId
와 developerPayload  가 올바른 값인지 확인하라. 당신은 아마 orderId가 이전에 처리하지않은  유일한 값인지 , developerPayload가  이전 구매 요청때 전송된 값과 일치하는지 검증할것이다. 그 이상의 보안 예방으로, 당신은 자신의 서버에서 검증을 구현할 수 있다.

Query Purchased Items(구매 아이템 조회)


Upon a successful purchase, the user’s purchase data is cached locally by Google Play’s In-app Billing service. It is good practice to frequently query the In-app Billing service for the user’s purchases, for example whenever the app starts up or resumes, so that the user’s current in-app product ownership information is always reflected in your app.
구매 성공시에, 유저의 구매 데이터는 구글 플레이의 인앱 빌링 서비스의 로컬에 캐시된다. 이것은 빈번하게 인앱빌링 서비스에 유저의 구매를 조회하는데 유용하다, 예를 들어, 앱이 시작또는 재시작 될때, 유저의 현재 소유한 인앱 재품의 정보를 항상 앱에 반영할 수 있다.
To retrieve the user’s purchases from your app, call queryInventoryAsync(QueryInventoryFinishedListener) on your IabHelper instance. The QueryInventoryFinishedListener argument specifies a listener that is notified when the query operation has completed and handles the query response. It is safe to make this call fom your main thread.
당신의 앱에서 유저의 구매제품들을 되찾기 위해서, queryInventoryAsync(QueryInventoryFinishedListener) 메소드를 IabHelper 인스턴스에서 호출 할 수 있다. QueryInventoryFinishedListener 인자는 조회 작업이 완료되고 조회의 결과를 다룰 수 있을때 통지 받는 리스너이다. 당신의 메인쓰레드에서 이것을 호출하는것이 안전하다.
mHelper.queryInventoryAsync(mGotInventoryListener);
If the query is successful, the query results are stored in an Inventory object that is passed back to the listener. The In-app Billing service returns only the purchases made by the user account that is currently logged in to the device.
만일 조회가 성공한다면, 조회의 결과들은 Inventory 오브젝트를 담아 리스너에 전달된다. 인앱 빌링 서비스는 오직 현재 디바이스에 로그인한 유저의 계정으로 부터 만들어진 구매들만 돌려준다.
IabHelper.QueryInventoryFinishedListener mGotInventoryListener 
   = new IabHelper.QueryInventoryFinishedListener() {
   public void onQueryInventoryFinished(IabResult result,
      Inventory inventory) {

      if (result.isFailure()) {
        // handle error here
      }
      else {
        // does the user have the premium upgrade?
        mIsPremium = inventory.hasPurchase(SKU_PREMIUM);        
        // update UI accordingly
      }
   }
};

Consume a Purchase(구입물 소비)


You can use the In-app Billing Version 3 API to track the ownership of purchased items in Google Play. Once an item is purchased, it is considered to be "owned" and cannot be purchased again from Google Play while in that state. You must send a consumption request for the item before Google Play makes it available for purchase again. All managed in-app products are consumable. How you use the consumption mechanism in your app is up to you. Typically, you would implement consumption for products with temporary benefits that users may want to purchase multiple times (for example, in-game currency or replenishable game tokens). You would typically not want to implement consumption for products that are purchased once and provide a permanent effect (for example, a premium upgrade).
당신은 인앱 빌링 버전3의 API를 사용하여 구글플레이에서 구매된 소유물을 추적할 수 있다. 단한번, 아이템은 구매되며, 그것은 소유된것으로 취급되어 해당 상태에 있는 이상은 구글 플레이로 부터 다시 구매할 수 없다. 당신은 구글 플레이가 아이템을 다시 구매 가능한 상태로 만들도록 아이템 소비를 전송해야만 한다. 모든 관리되는 제품들은 소비 가능하다. 어떻게 소비하는지에 대한 매커니즘은 당신의 앱에 설정하는것에 달려있다. 보통, 당신은 제품의 소비를 통해서 일시적인 이득을 주고 유저가 계속적으로 구매할 수 있게 하기를 원할것이다(예를 들어, 인게임통화나 게임토큰보충).당신은 한번의 구매로 영구적인 효과를 주는 제품의 소비를 원하지 않을 것이다(예를 들어, 프리미엄 업그레이드)
It's your responsibility to control and track how the in-app product is provisioned to the user. For example, if the user purchased in-game currency, you should update the player's inventory with the amount of currency purchased.
유저에게 인앱 제품이 어떻게 지급되는지 추적하고 제어하는 것은 당신의 책임이다. 예를들어, 유저가 인게임 통화를 구매하면, 당신은 플레이어의 인벤토리에 구매한 만큼의 통화를 업데이트해야한다.
Security Recommendation: You must send a consumption request before provisioning the benefit of the consumable in-app purchase to the user. Make sure that you have received a successful consumption response from Google Play before you provision the item.
보안권고 : 당신은 유저에게 인앱제품의 소비를 통해 이득을 지급하기 전에 소비 요청을 반드시 전송해야한다. 당신은 아이템 지급전 구글플레이로 부터 성공적인 소비 응답수신을 확인해야한다.
To record a purchase consumption, call consumeAsync(Purchase, OnConsumeFinishedListener) on yourIabHelper instance. The first argument that the method takes is the Purchase object representing the item to consume. The second argument is a OnConsumeFinishedListener that is notified when the consumption operation has completed and handles the consumption response from Google Play. It is safe to make this call fom your main thread.
구입물 소비를 기록하기 위해, consumeAsync(Purchase, OnConsumeFinishedListener) 를 IabHelper 인스턴스에서 호출해야한다. 메소드의 첫번째 인자는 소비될 아이템을 나타내는 Purchase 오브젝트이다. 두번째 인자는 OnConsumeFinishedListener 리스너로 소비 작업이 완료되고 구글플레이로 부터 소비 응답을 받아 다룰수 있는 경우 통지받게 된다. 이것을 당신의 메인쓰레드에서 호출하는것이 안전하다.
In this example, you want to consume the gas item that the user has previously purchased in your app.
다음 예에서, 당신은 앱에서 유저가 이전에 구매한 아이템인 gas를 소비하기를 원한다.
mHelper.consumeAsync(inventory.getPurchase(SKU_GAS), 
   mConsumeFinishedListener);
The following example shows how to implement the OnConsumeFinishedListener.
다음 예는 OnConsumeFinishedListener를 어떻게 구현하는지 보여준다.
IabHelper.OnConsumeFinishedListener mConsumeFinishedListener =
   new IabHelper.OnConsumeFinishedListener() {
   public void onConsumeFinished(Purchase purchase, IabResult result) {
      if (result.isSuccess()) {
         // provision the in-app purchase to the user(인앱 제품을 유저에게 지급한다)
         // (for example, credit 50 gold coins to player's character, 예를들어 50Gold의 코인을 플레이어 캐릭터에 지급)
      }
      else {
         // handle error
      }
   }
};

Check for Consumable Items on Startup(시작시 소비성 아이템 확인)

It’s important to check for consumable items when the user starts up your application. Typically, you would first query the In-app Billing service for the items purchased by the user (via queryInventoryAsync), then get the consumable Purchase objects from the Inventory. If your application detects that are any consumable items that are owned by the user, you should send a consumption request to Google Play immediately and provision the item to the user. See the TrivialDrive sample for an example of how to implement this checking at startup.
유저가 당신의 애플리케이션을 시작시 소비성 아템들을 확인하는 것은 중요하다. 보통, 당신은 유저가 구매한 아이템들을 인앱빌링서비스에 조회할 것이다(queryInventoryAsync를통해서), 그때 인벤토리로 부터 소비가능한 Purchase 오브젝트를 얻는다. 만일 애플리케이션에서 유저가 소유한 소모성 아이템이 감지된다면, 당신은 소비 요청을 구글 플레이에 즉각적으로 보내고, 유저의 아이템을 지급하면된다. TrivialDrive 샘플의 예에서 시작시 어떻게 이를 구현하는지 보라.




posted by 래머
2014. 5. 2. 00:47 안드로이드



[구글인앱]Establishing In-app Billing Products for Sale(판매를 위한 인앱 제품 개설) #3


Establishing In-app Billing Products for Sale(판매를 위한 인앱 제품 개설)

Before publishing your In-app Billing application, you'll need to define the product list of digital goods available for purchase in the Google Play Developer Console.
인앱빌링 앱 출시전, 당신은 구글플레이 개발자 콘솔에서 이용가능한 디지털 상품의 목록을 설정해야 할것이다.

Specify In-app Products in Google Play(구글플레이에 인앱 제품 상술하기(추가하기))


From the Developer Console, you can define product information for in-app products and associate the product list with your application. 개발자 콘솔로부터, 당신은 앱과 연계된 제품의 목록과 인앱 제품의  정보를 선언할 수 있다.
To add new in-app products to your product list:(제품 목록에 인앱 제품 추가하기)
  1. Build a signed APK file for your In-app Billing application. To learn how to build and sign your APK, seeBuilding Your Application for Release. Make sure that you are using your final (not debug) certificate and private key to sign your application.(서명된 인앱 빌링 애플리케이션을 빌드한다. 어떻게 빌드 및 서명하는지 배우기 위해 Building Your Application for Release을 보라. 애플리케이션을 서명하기 위한 최종의(디버그가아닌) 인증서와 개인키인지 확인한다.)
  2. In the Developer Console, open the application entry that you created earlier.(개발자 콘솔에서, 이전에 생성했던 애플리케이션 시작점을 연다.)
  3. Click on the APK tab then click on Upload new APK. Upload the signed APK file to the Developer Console. Don’t publish the app yet!(APK탭을 클릭하고  APK를 업로드 클릭한다. 서명된 앱을 개발자 콘솔에 업로드 한다. 아직 앱을 게시하지 말라.)
  4. Navigate to the uploaded app listing, and click on In-app Products.(업로드된 앱 목록을 찾아서 인앱 제품 항목을 클릭한다.)
  5. Click on the option to add a new product, then complete the form to specify the product information such as the item’s unique product ID (also called its SKU), description, price, and country availability. Note down the product ID since you might need this information to query purchase details in your application later.(새제품 추가하기 옵션을 클릭하고, 아이템의 유니크제품ID(또한 SKU라 불려진다), 설명, 가격, 이용국가 같은 제품의 정보의 상세를 기록한다/ 제품ID는 이후에 당신의 앱에서 제품의 상세를 조회하기위한 정보로 필요할 것이다.)
  6. Important: The In-app Billing Version 3 service only supports managed in-app products, so make sure that you specify that the purchase type is 'Managed' when you add new items to your product list in the Developer Console.(중요 : 인앱 빌링 버전 3은 오직 관리되는 인앱 제품만 지원한다, 그렇기 때문에 개발자 콘솔에 당신의 새로운 제품목록을 추가할때 구매 타입이 '관리된'타입인지 확인 해야한다.)
  7. Once you have completed the form, activate the product so that your application can purchase it.(당신의 앱에서 그것을 구매하기 하기 위해 제품을 활성하고 형식을 완성시킨다.)
    Warning: It may take up to 2-3 hours after uploading the APK for Google Play to recognize your updated APK version. If you try to test your application before your uploaded APK is recognized by Google Play, your application will receive a ‘purchase cancelled’ response with an error message “This version of the application is not enabled for In-app Billing.”
    경고 : 구글 플레이가 당신의 업데이트된 APK  버전을 확이하기 위해  APK 업로드 후 2 ~ 3시간 정도 필요하다. 구글플레이에서 당신의 앱이 확인도기 전에 앱을 테스트할경우, 당신의 앱은, "이버전의 앱은 인앱빌링이 허가되지않았다는 오류 메시지와 함께 결제 취소를 수신받을 것이다."

Query Items Available for Purchase(구매를 위해 이용 가능 아이템 조회 )


You can query Google Play to programmatically retrieve details of the in-app products that are associated with your application (such as the product’s price, title, description, and type). This is useful, for example, when you want to display a listing of unowned items that are still available for purchase to users.
당신은 앱에 제휴된 인앱 제품의 상세를 구글 플레이로 부터 조회하여 수신할 수 있다(제품의 가격, 타이틀, 설명, 타입등과 같은). 이것은 당신이 유저에게 구매 가능 상태의 아이템 목록을 출력하기를 원할때 유용할 수 있다.
Note: When making the query, you will need to specify the product IDs for the products explicitly. You can manually find the product IDs from the Developer Console by opening the In-app Products tab for your application. The product IDs are listed under the column labeled Name/ID.
주의 : 쿼리를 만들때, 제품을 위한 명시적인 ID를 명기할 필요가 있을것이다. 당신은 개발자 콘솔의 인앱 제품 탭을 열어서 제품의 ID들을 수동으로 찾을 수 있다. 제품의 ID들은 Name/ID 표의 컴럼 아래에 목록화 되어 있다.
To retrieve the product details, call queryInventoryAsync(boolean, List, QueryInventoryFinishedListener) on your IabHelper instance.
제품의 상세를 되찾기 위해서, queryInventoryAsync(boolean, List, QueryInventoryFinishedListener) 메소드를 IabHelper 인스터스에서 호출한다.
  • The first input argument indicates whether product details should be retrieved (should be set to true).
  • The List argument consists of one or more product IDs (also called SKUs) for the products that you want to query.
  • Finally, the QueryInventoryFinishedListener argument specifies a listener is notified when the query operation has completed and handles the query response.
  • 첫번째 입력인자는 제품이 상세 정보를 수신할지를 가르킨다(true로 설정될것이다)
  • 두번째 List 인자는 당신이 조회 하기 원하는 제품들의 하나 이상의 ID들(SKUs라 불리는)로 되어 있다.
  • 마지막으로,QueryInventoryFinishedListener 인자는, 조회 작업이 완료되어 조회 응답을 다룰 수 있을때 통지를 받는 리스너이다.
If you use the convenience classes provided in the sample, the classes will handle background thread management for In-app Billing requests, so you can safely make queries from the main thread of your application.
만일 샘플에서 제공된 편의기능 클래스들을 사용한다면, 클래스들은 백그라운드 쓰레드에서 인앱빌링 요구들을 다룰것이다. 그렇기 때문에 당신은 애플리케이션의 메인쓰레드로 부터 조회들을 안전하게 만들어야 한다.

The following code shows how you can retrieve the details for two products with IDs SKU_APPLE and SKU_BANANAthat you previously defined in the Developer Console.
다음의 코드는 이전에 당신이 개발자 콘슬에 선언했던() SKU_APPLE 과 SKU_BANANA를 ID로 가진 두 제품의 상세를 어떻게 되찾는지 보여준다.
List<string> additionalSkuList = new List<string>();
additionalSkuList.add(SKU_APPLE);
additionalSkuList.add(SKU_BANANA);
mHelper.queryInventoryAsync(true, additionalSkuList,
   mQueryFinishedListener);
</string></string>
If the query is successful, the query results are stored in an Inventory object that is passed back to the listener.
The following code shows how you can retrieve the item prices from the result set.
쿼리가 성공한다면,쿼리의 결과에는 Inventory 오브젝트가 담기고 리스너에 전달될 것이다. 
다음의 코드는 결과 셋으로 부터 어떻게 아이템 가격을 되찾는지 보여준다.
IabHelper.QueryInventoryFinishedListener 
   mQueryFinishedListener = new IabHelper.QueryInventoryFinishedListener() {
   public void onQueryInventoryFinished(IabResult result, Inventory inventory)   
   {
      if (result.isFailure()) {
         // handle error
         return;
       }

       String applePrice =
          inventory.getSkuDetails(SKU_APPLE).getPrice();
       String bananaPrice =
          inventory.getSkuDetails(SKU_BANANA).getPrice();

       // update the UI 
   }
}




posted by 래머
2014. 5. 2. 00:45 안드로이드



[구글인앱]Preparing Your In-app Billing Application(인앱 빌링 어플리케이션준비) #2

Preparing Your In-app Billing Application(인앱 어플리케이션준비)

THIS LESSON TEACHES YOU TO

  1. Download the Sample App(샘플앱 다운로드)
  2. Add Your App to the Developer Console(개발자콘솔에앱등록)
  3. Add the In-app Billing Library(인앱빌링라이브러리추가)
  4. Set the Billing Permission(빌링권한추가)
  5. Initiate a Connection with Google Play(구글플레이 연결 초기화)

YOU SHOULD ALSO READ

Before you can start using the In-app Billing service, you'll need to add the library that contains the In-app Billing Version 3 API to your Android project. 
인앱 빌링 서비스를 사용하기 전에, 인앱빌링3 API를 담고 있는 라이브러리를 안드로이드 프로젝트에 추가해야 한다.
You also need to setting the permissions for your application to communicate with Google Play. 
또한 구글플레이와 통신하기 위해서 당신의 애플리케이션에 권한을 설정해야한다.
In addition, you'll need to establish a connection between your application and Google Play. You should also verify that the In-app Billing API version that you are using in your application is supported by Google Play.
부가적으로, 구글플레이와 당신의 앱 사이에서 연결을 수립해야 한다. 또한 애플리케이션에서 사용하고자 하는 인앱 빌링 API버전을 구글플레이가 지원하는지 검증해야 할것이다.

Download the Sample Application(샘플 애플리케이션 받기)


In this training class, you will use a reference implementation for the In-app Billing Version 3 API called the TrivialDrive sample application. The sample includes convenience classes to quickly set up the In-app Billing service, marshal and unmarshal data types, and handle In-app Billing requests from the main thread of your application.
이 훈련 수업에서,  인앱 버전 3 API 구현 참조에 TrivialDrive 이라 불리는 샘플 어플리케이션을 사용할 것이다.
샘플에서는 구글인앱 빌링 서비스를 빠르게 설정하기위한 편의 기능 클래스와, marshal 및 unmarshal 데이터 타입들, 애플리케이션의 메인쓰레드에서 인앱빌링 요청을 다루는 방법을 포함하고 있다.
To download the sample application:(샘플 애플리케이션다운로드를하기)
  1. Open the Android SDK Manager.(안드로이드 SDK 매니저 열기)
  2. In the SDK Manager, expand the Extras section.(SDK매니저에서 Extras 색션을 확장한다)
  3. Select Google Play Billing Library.(Google Play Billing Library를 선택)
  4. Click Install packages to complete the download.(다운로드 완료를 위해 인스톨 패키지 클릭)
The sample files will be installed to <sdk>/extras/google/play_billing/.
샘플파일들은 <sdk>/extras/google/play_billing/ 위치에 인스톨 될것이다.

Add Your Application to the Developer Console(앱을 개발자 콘솔에 등록)


The Google Play Developer Console is where you publish your In-app Billing application and manage the various digital goods that are available for purchase from your application. When you create a new application entry in the Developer Console, it automatically generates a public license key for your application. You will need this key to establish a trusted connection from your application to the Google Play servers. You only need to generate this key once per application, and don’t need to repeat these steps when you update the APK file for your application.
구글플레이 개발자 콘솔은 당신의 인앱 빌링 앱을 게시하고 앱에서 구매 가능한 다양한 디지털 상품을 관리하는 장소다. 당신이 새로운 앱을 개발자 콘솔에 생성했을때, 자동적으로 당신의 앱을 위한 공개 라이센스 키가 발급된다.
당신은 앱에서 구글플레이로 신뢰된 연결을 수립하기 위해 이 키가 필요하다. 오직 단한번 앱을 위한 키생성이 필요하며, 당신의 앱을 갱신시에 다시 이과정을 반복할 필요는 없다.
To add your application to the Developer Console:(앱을 개발자 콘솔에 등록하기)
  1. Go to the Google Play Developer Console site and log in. You will need to register for a new developer account, if you have not registered previously. To sell in-app items, you also need to have a Google Walletmerchant account.
  2. 구글 플레이 개발자 콘솔 사이트로 이동 후 로그인한다. 만일 이전에 등록하지 않았다면, 새로운 개발자 계정 등록이 필요할 것이다. 또한 인앱 아이템 판매를 위해, Google Walletmerchant  계정이 필요하다.
  3. Click on Try the new design to access the preview version of the Developer Console, if you are not already logged on to that version.  
  4. In the All Applications tab, add a new application entry.(All Applications 탭에서 새로운 앱 시작점을 추가한다)
    1. Click Add new application. (새애플리케이션추가클릭)
    2. Enter a name for your new In-app Billing application.(새 인앱 빌링 앱 이름추가)
    3. Click Prepare Store Listing.(상점목록 준비 클릭)
  5. In the Services & APIs tab, find and make a note of the public license key that Google Play generated for your application. This is a Base64 string that you will need to include in your application code later.(서비스와 API탭에서, 구글플레이가 당신의 앱에 생성한 공개 라이센스키 기록을 찾거나 만들 수 있다. 이것은 이후에 당신의 애플리케이션 코드에 포함할 필요가 있는 Base64 문자열이다.)
Your application should now appear in the list of applications in Developer Console.
이제 개발자 콘솔의 애플리케이션 목록에 당신의 앱이 나타날것이다.

Add the In-app Billing Library(인앱빌링라이브러리추가)


To use the In-app Billing Version 3 features, you must add the IInAppBillingService.aidl file to your Android project. This Android Interface Definition Language (AIDL) file defines the interface to the Google Play service.
인앱빌링 버전3기능을 사용하기 위해, 반드시 IInAppBillingService.aidl  파일을 안드로이드 프로젝트에 추가해야한다. 이 안드로이드 인터페이스 선언 언어 파일은(AIDL) 구글 플레이 서비스를 위한 인터페이스를 선언한다.
You can find the IInAppBillingService.aidl file in the provided sample app. Depending on whether you are creating a new application or modifying an existing application, follow the instructions below to add the In-app Billing Library to your project.
IInAppBillingService.aidl 파일은 제공된 샘플 앱에서 찾을 수 있다. 당신이 새로운 애플리케이션을 생성하는지, 기존의 애플리케이션을 수정하는지에 따라서, 아래의 인앱 빌링 라이브러리를 추가 방법을 따라가면된다.

New Project(새프로젝트)

To add the In-app Billing Version 3 library to your new In-app Billing project:(새 프로젝트에 인앱빌링 버전3 추가)
  1. Copy the TrivialDrive sample files into your Android project.(TrivialDrive 샘플 파일을 당신의 안드로이드 프로젝트에 복사한다.)
  2. Modify the package name in the files you copied to use the package name for your project. In Eclipse, you can use this shortcut: right-click the package name, then select Refactor > Rename. (복사된 파일들의 패키지 이름을 당신의 어플리케이션이 사용하는 패키지 이름으로 바꾼다. 이클립스에서, 당신은 이 단축법을 사용할 수 있다 : 패키지이름에서 우클릭, 그때 Refactor > Rename 선택.)
  3. Open the AndroidManifest.xml file and update the package attribute value to use the package name for your project.(AndroidManifest.xml 파일을 열고 패키지 속성값을 당신의 프로젝트에서 사용하는 패키지 이름으로 업데이트한다.)
  4. Fix import statements as needed so that your project compiles correctly. In Eclipse, you can use this shortcut: press Ctrl+Shift+O in each file showing errors.(프로젝트가 제대로 컴파일되도록 프로젝트 임포트 명세를 고친다. 이클립스에서, 다음 숏컷을 사용할 수 있다 : 각파일에서 Ctrl + Shift + O를 누를 경우 오류를 보여준다.)
  5. Modify the sample to create your own application. Remember to copy the Base64 public license key for your application from the Developer Console over to your MainActivity.java.(샘플을 수정해서 당신 자신의 애플리케이션을 만든다. 개발자 콘솔에서 얻은 앱의 Base64 공개키를 MainActivity.java에 복사하는 것을 기억하라.)

Existing Project(기존프로젝트)

To add the In-app Billing Version 3 library to your existing In-app Billing project:
인앱 빌링 버전 3 라이브러리를 당신의 기존 프로젝트에 추가하기:
  1. Copy the IInAppBillingService.aidl file to your Android project.(IInAppBillingService.aidl 파일을 안드로이드 프로젝트에 복사한다.)
    • If you are using Eclipse: Import the IInAppBillingService.aidl file into your /src directory.
    • If you are developing in a non-Eclipse environment: Create the following directory/src/com/android/vending/billing and copy the IInAppBillingService.aidl file into this directory.
    • 이클립스를 사용하는경우: IInAppBillingService.aidl 파일을 프로젝트의 /src 디렉터리에 임포트 한다.
    • 이클립스 환경이 아니경우 : /src/com/android/vending/billing 디렉터리를 만들고 IInAppBillingService.aidl 파일을 이 디렉터리에 복사한다.
  2. Build your application. You should see a generated file named IInAppBillingService.java in the /gendirectory of your project.(앱을 빌드한다. 프로젝트 /gen 디렉토리에 IInAppBillingService.java 이름의 파일이 생성된것이 보일것이다.)
  3. Add the helper classes from the /util directory of the TrivialDrive sample to your project. Remember to change the package name declarations in those files accordingly so that your project compiles correctly.(TrivialDrive 샘플의 /util 디렉터리에 있는 헬퍼클래스들을 프로젝트에 추가한다. 프로젝트가 올바르게 컴파일되도록 패키지 이름 선언들을 변경해야 한다는 하는것을 기억하라.)
Your project should now contain the In-app Billing Version 3 library.
당신의 프로젝트는 이제 인앱 빌링 3 라이브러리를 담고 있을 것이다.

Set the Billing Permission(빌링 권한 설정)


Your app needs to have permission to communicate request and response messages to the Google Play’s billing service. To give your app the necessary permission, add this line in your AndroidManifest.xml manifest file:(당신의 앱은 구글 플레이 빌링 서비스와 통신하여 요청하고 응답 메시지를 받기 위한 권한을 가져야한다. 앱에 필요한 권한을 주기 위해서, 다음 라인을 앱의 AndroidManifest.xml 파일에 추가한다.)
<uses-permission android:name="com.android.vending.BILLING" />

Initiate a Connection with Google Play(구글플레이와 연결시작)


You must bind your Activity to Google Play’s In-app Billing service to send In-app Billing requests to Google Play from your application. The convenience classes provided in the sample handles the binding to the In-app Billing service, so you don’t have to manage the network connection directly.
당신의 앱에서 구글 플레이에 인앱 빌링 요청을 보내기 위해서 구글 플레이의 인앱 빌링 서비스에 당신의 액티비티를 반드시 연결해야한다. 샘플에서 다루어지는 편의 기능 클래스들은 인앱빌링 서비스에 연결을 제공한다, 그렇기 떄문에 직접적으로 네트워크 연결을 다룰 필요는 없다.
To set up synchronous communication with Google Play, create an IabHelper instance in your activity'sonCreate method. In the constructor, pass in the Context for the activity, along with a string containing the public license key that was generated earlier by the Google Play Developer Console.
구글플레이와 동기화된 통신 설정을 위해서, IabHelper 인스턴스를 액티비티의  onCreate 메소드에서 생성한다. 생성자에서 액티비티를 위한 컨텍스트와 이전에 구글 플레이 개발자 콘솔에서 생성한 라이센스키가 전달된다. 
Security Recommendation: It is highly recommended that you do not hard-code the exact public license key string value as provided by Google Play. Instead, you can construct the whole public license key string at runtime from substrings, or retrieve it from an encrypted store, before passing it to the constructor. This approach makes it more difficult for malicious third-parties to modify the public license key string in your APK file.
보안 권고구글플레일 부터 제공된 공개 라이센스키를 변경없이 하드코딩 형태로 소스에 포함하지 말것을 강력하게 권장한다. 그대신 생성자에 전달전, 런타임에 일련의 스트링으로 부터 공개 라이센스키를 생성하거나, 암호화된 저장소로 부터 회수할 수 있다. 이러한 접근은 악의 적인 목적을 가진 사람들이 당신의 apk파일로 부터 공개 라이센스키를 변경하는 것을 좀더 어렵게 만든다.(역자주: 어짜피 생성자에 전달하는 키만 교체 하면 끝인데 내키를 암호화 해본들 무슨소용???)
IabHelper mHelper;
@Override
public void onCreate(Bundle savedInstanceState) {
   // ...
   String base64EncodedPublicKey;
   
   // compute your public key and store it in base64EncodedPublicKey(공개 키를 계산하고 base64EncodedPublicKey에 저장한다)
   mHelper = new IabHelper(this, base64EncodedPublicKey);
}
Next, perform the service binding by calling the startSetup method on the IabHelper instance that you created. Pass the method an OnIabSetupFinishedListener instance, which is called once the IabHelper completes the asynchronous setup operation. As part of the setup process, the IabHelper also checks if the In-app Billing Version 3 API is supported by Google Play. If the API version is not supported, or if an error occured while establishing the service binding, the listener is notified and passed an IabResult object with the error message.
다음으로, 당신이 생성한 IabHelper 인스턴스의 startSetup 메소드를 호출하여 서비스와 바인딩을 실행한다.메소드에 전달된 OnIabSetupFinishedListener 인스턴스는, IabHelper 의 비동기 작업처리가 완료될때 한번 호출된다. 또한 셋업 프로세스의 한 부분으로 IabHelper 는 구글플레이로 부터 인앱 빌링 버전3이 지원되는지 확인한다. 만일 API버전이 지원되지 않거나, 서비스바인딩중 오류가 발생한다면,  리스너는 오류 메시지와 함께 IabResult 를 포함한 통지를 받게 된다.
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() { //OnIabSetupFinishedListener는 IabHelper에정의된 인터페이스로, 인앱 빌링 설정의 결과를 통지 받기 위한 용도를 가지고 있다
   public void onIabSetupFinished(IabResult result) {
      if (!result.isSuccess()) {
         // Oh noes, there was a problem. 아 젠장, 뭔가 문제 있다.
         Log.d(TAG, "Problem setting up In-app Billing: " + result);
      }            
         // Hooray, IAB is fully set up!  아싸, IAB가 완전히 설정됐다!
   }
});
If the setup completed successfully, you can now use the mHelper reference to communicate with the Google Play service. When your application is launched, it is a good practice to query Google Play to find out what in-app items are owned by a user. This is covered further in the Query Purchased Items section.
만일 설정이 완전히 성공한다면, 이제부터  mHelper 레퍼런스를 사용하여 구글 플레이 서비스와 통신할 수 있다. 당신의 애플리케이션이 시작될때, 유저가 어떤 인앱 아이템을 소유하고 있는지 찾기위해 구글플레이로 부터 조회 하는 것은 좋은 방법이다. 이것은 이후에 Query Purchased Items 부분에서 다룰것이다.
Important: Remember to unbind from the In-app Billing service when you are done with your activity. If you don’t unbind, the open service connection could cause your device’s performance to degrade. To unbind and free your system resources, call the IabHelper's dispose method when your Activity gets destroyed.
중요 : 당신의 액티비티가 종료될때 인앱 빌링 서비스로 부터 언바인드 해야하는것을 기억하라. 언바인드 하지 않으경우, 열려진 서비스 연결은 디바이스의 성능 저하의 원인이 될 수 있다. 언바인드하고 시스템 리소를 해제하기 위해서, IabHelper 의 dispose 메소드를 액티비티 종료 신호시 호출한다.
@Override
public void onDestroy() {
   super.onDestroy();
   if (mHelper != null) mHelper.dispose();
   mHelper = null;
}




posted by 래머
2014. 5. 2. 00:39 안드로이드



[구글인앱]Selling In-app Products(인앱 제품 판매) #1

Selling In-app Products(인앱 제품판매)

DEPENDENCIES AND PREREQUISITES(의존성과 필요조건)

  • Android 2.2 or higher(안드로이드2.2 또는 상위버전)

YOU SHOULD ALSO READ(당신은 또한 다음을 읽을 수 있다)

In this class, you'll learn how to perform common In-app Billing operations from Android applications.
이 수업에서, 당신은 안드로이드 어플리케이션의 공통된 인앱 빌링 작
업을 어떻게 수행하는지 배울것이다.
In-app billing is a service hosted on Google Play that lets you charge for digital content or for upgrades in your app. 
인앱 빌링은 당신의 앱에있는 디지털 컨텐트에 요금을 부과하거나 업그레이드가 가능하도록  구글 플레이에서 호스트하는 서비스이다.
The In-app Billing API makes it easy for you to integrate In-app Billing into your applications. 
인앱빌링 API는 당신의 어플리케이션에 인앱빌링을 쉽게 통합하게 만든다.
You can request product details from Google Play, issue orders for in-app products, and quickly retrieve ownership information based on users' purchase history. 
당신은 제품의 상세를 구글플레이로 부터 요청하거나, 인앱제품 결제 주문을 내거나, 유저의 구매 내역으로 부터 소유권 정보를 빠르게 되찾을 수 있다.
You can also query the Google Play service for details about in-app products, such as local pricing and availability. 
또한, 지역별 가격 및 유효성과 같은 인앱 제품의 상세정보를 구글플레이 서비스로 부터 조회 할 수 있다. 
Google Play provides a checkout interface that makes user interactions with the In-app Billing service seamless, and provides a more intuitive experience to your users.
구글 플레이는  유저 상호작용 결제 인터페이스로 매끄러운 인앱 빌링 서비스를 제공하며, 좀더 직관 적인 경험을 당신의 사용자에게 제공한다.
This class describes how to get started with the Version 3 API. To learn how to use the version 2 API, seeImplementing In-App Billing (V2).
이 수업에서 어떻게 Version3 API를 시작하는지 설명한다. 버전 2 API 사용 방법을 배우기 위해, 인앱빌링2(http://developer.android.com/google/play/billing/v2/billing_integrate.html) 구현을 보라.

Lessons



Preparing Your In-app Billing Application(인앱 빌링 어플레케이션준비)
In this lesson, you will learn how to prepare your application to use the In-app Billing API and communicate with Google Play. You will also learn how to establish a connection to communicate with Google Play and verify that the In-app Billing API version that you are using is supported.
이수업에서, 당신은 인앱 빌링을 사용하기 위해서 당신의 어플리케이션이 어떤 준비를 해야 하며 어떻게 구글플레이와 소통하는지 배우게 된다. 또한 구글플레이와 통신하기 위해 연결을 수립하고, 사용하고자 하는 인앱 빌링 API를 검증하는 법을 배우게 될것이다.
Establishing In-app Billing Products for Sale(판매를 위한 인앱빌링 제품 개설)


In this lesson, you will learn how to specify the In-app Billing products for your app in Google Play and query the product details.
이수업에서, 앱의 인앱 빌링 제품 정보를 구글플레이에 어떻게 개설 하는지와 조회 하는지에 대해 배우게된다.
Purchase In-app Billing Products(인앱 빌링 제품 결제)
In this lesson, you will learn how to purchase In-app Billing products, track consumption of purchased items, and query for details of purchased items.
이수업에서는, 인앱 빌링 제품 구매방법, 구매 아이템을 소비하는법, 구매 아이템의 상세 정보조회에 대해서 배우게된다.
Testing Your In-app Billing Application(인앱 빌링 어플리케이션 테스트)
In this lesson, you will learn how to test your application to ensure that In-app Billing is functioning correctly.
이수업에서는, 인앱빌링 기능이 올바르게 작동하는지 보증하기 위해서 당신의 어플리케이션을 어떻게 테스트 하는지 배우게 될것이다.




posted by 래머
prev 1 next