Debian Codegraph @

src/services/castleinapppurchases.pas

raw
1 {
2 Copyright 2015-2023 Michalis Kamburelis.
3
4 This file is part of "Castle Game Engine".
5
6 "Castle Game Engine" is free software; see the file COPYING.txt,
7 included in this distribution, for details about the copyright.
8
9 "Castle Game Engine" is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 ----------------------------------------------------------------------------
14 }
15
16 { In-app purchases (TInAppPurchases).
17 See https://castle-engine.io/in_app_purchases
18 for detailed instructions how to use this. }
19 unit CastleInAppPurchases;
20
21 {$I castleconf.inc}
22
23 interface
24
25 uses Classes, Generics.Collections,
26 CastleStringUtils;
27
28 type
29 { A product that can be bought by in-app purchases (TInAppPurchases). }
30 TInAppProduct = class
31 private
32 FName: string;
33 FPriceRaw, FTitle, FDescription, FPriceCurrencyCode: string;
34 FPriceAmountMicros: Int64;
35 FOwns: boolean;
36 FSuccessfullyConsumed: boolean;
37 public
38 { Short product identifier, uniquely identifying it in the store. }
39 property Name: string read FName;
40
41 { Price, as a string in local user currency.
42 Empty before receiving information about the product from the store.
43 This may contain various UTF-8 local characters used to describe currency,
44 which do not have to be supported in all fonts.
45
46 Use @link(Price) to display the price as a "safe" string, with most unusual
47 characters replaced with ASCII (so it should work reliably with any font),
48 and with special value if not received yet. }
49 property PriceRaw: string read FPriceRaw;
50
51 { The price, as a string in local user currency,
52 with most unusual characters replaced with ASCII
53 (so it should work reliably with any font),
54 and with special value if not received yet.
55 @seealso PriceRaw }
56 function Price(const ValueWhenUnknown: string = 'loading...'): string;
57
58 { Title of the product, as defined in the store.
59 Empty if not known yet.
60 May be translated to current user language. }
61 property Title: string read FTitle;
62
63 { Description of the product, as defined in the store.
64 Empty if not known yet.
65 May be translated to current user language. }
66 property Description: string read FDescription;
67
68 { Price in micro-units, where 1,000,000 micro-units equal one unit of the currency.
69 0 if not known yet. }
70 property PriceAmountMicros: Int64 read FPriceAmountMicros;
71
72 { ISO 4217 currency code for price.
73 Empty if not known yet. }
74 property PriceCurrencyCode: string read FPriceCurrencyCode;
75
76 { Is the product owned now. Use this for non-consumable items
77 (things that user buys, and then "owns" for the rest of his life).
78
79 Caution: @italic(this may not be up-to-date knowledge).
80 Call @link(TInAppPurchases.RefreshPurchases) to refresh it
81 (on Android, this happens automatically on app launch;
82 but on iOS, it cannot be done automatically, as it requires logging to AppStore
83 -- this is also explicitly said in Apple docs).
84 Watch for @link(TInAppPurchases.Owns) and @link(TInAppPurchases.OnRefreshedPurchases)
85 then.
86
87 Do not depend on this for consumables (use SuccessfullyConsumed
88 for them, and be sure to call @link(TInAppPurchases.SuccessfullyConsumed)
89 from @link(TInAppPurchases.Owns) for them). }
90 property Owns: boolean read FOwns;
91
92 { Item was consumable, and was just consumed. We should "provision"
93 it now, which means that we should set @code(SuccessfullyConsumed:=false),
94 and perform whatever is necessary upon consuming --- e.g. continue
95 the game or increase player's gold. }
96 property SuccessfullyConsumed: boolean read FSuccessfullyConsumed write FSuccessfullyConsumed;
97 end;
98
99 { Information about product possible to be bought given to
100 @link(TInAppPurchases.SetAvailableProducts). }
101 TAvailableProduct = record
102 { Unique product identifier. }
103 Name: string;
104
105 { Category. For now used only for analytics. }
106 Category: string;
107 end;
108
109 { Manage in-app purchases in your game.
110 See https://castle-engine.io/in_app_purchases
111 for detailed instructions how to use this. }
112 TInAppPurchases = class(TComponent)
113 private
114 type
115 TProductList = {$ifdef FPC}specialize{$endif} TObjectList<TInAppProduct>;
116 var
117 FDebugMockupBuying: boolean;
118 List: TProductList;
119 FLastAvailableProducts: string;
120 FOnRefreshedPrices: TNotifyEvent;
121 FOnRefreshedPurchases: TNotifyEvent;
122 function MessageReceived(const Received: TCastleStringList;
123 const ReceivedStream: TMemoryStream): boolean;
124 procedure ReinitializeJavaActivity(Sender: TObject);
125 procedure LogProducts(const Message: string);
126 protected
127 { Called when the knowledge about what do we own is complete. }
128 procedure KnownCompletely; virtual; deprecated 'use RefreshedPrices or RefreshedPurchases';
129
130 { See @link(OnRefreshedPrices) for information when is this called.
131 The default implementation of this method in this class just calls
132 @link(OnRefreshedPrices). }
133 procedure RefreshedPrices; virtual;
134
135 { See @link(OnRefreshedPurchases) for information when is this called.
136 The default implementation of this method in this class just calls
137 @link(OnRefreshedPurchases). }
138 procedure RefreshedPurchases; virtual;
139
140 { Called when the product is successfully consumed,
141 in response to the @link(Consume) call.
142
143 In this class, this simply
144 sets @code(Product.SuccessfullyConsumed) flag to @true,
145 and waits for some other code (maybe overridden SuccessfullyConsumed
146 implementation, maybe something else) will handle it and reset
147 the @code(Product.SuccessfullyConsumed) flag to @false. }
148 procedure SuccessfullyConsumed(const AProduct: TInAppProduct); virtual;
149
150 { Called when we know the product is owned, in particular when it's
151 successfully bought.
152
153 If the product is @bold(not consumable) (which means that it can be owned
154 only once, and it's owned forever once bought): Note that this method
155 may be called multiple times, because there are various situations in which
156 we may "gain knowledge" that user owns this item (e.g.
157 each @link(RefreshPurchases) call).
158 Write your code to react gracefullly to this, such that calling this method
159 on an already-owned item is handled correctly.
160
161 E.g. if you increase some stat (e.g. "gold owned")
162 when user buys a "chest of gold", and "chest of gold"
163 is non-consumable (you can only own it once, and then you just own it forever),
164 then store the fact that you "already increased gold because of the chest ownership"
165 in the user persistent data (see https://castle-engine.io/manual_user_prefs.php).
166 Do not just increase the "gold owned" at every call of this method.
167
168 If the product is a @bold(consumable), which means it has a one-time use
169 (and should disappear afterwards, until user will buy it again), then:
170
171 @orderedList(
172 @item(@bold(Call the @link(Consume) method) once you know the item is
173 owned. You can call @link(Consume) directly from the overridden
174 implementation of @name, this is often the simplest approach.)
175
176 @item(@bold(Actually perform the consumption) (bump the player gold,
177 grant extra life and so on) @bold(only when the item
178 is successfully consumed). You are notified about this by the
179 @link(SuccessfullyConsumed) call (you can override it),
180 or you can watch if the @link(TInAppProduct.SuccessfullyConsumed)
181 flag is set.
182
183 @bold(Do not give any one-time gain as a response to the @name
184 call.) Always wait for @link(SuccessfullyConsumed) call.
185
186 This protects you from the scenario when you're notified that
187 you own the item multiple times (which
188 may happen, since purchases may be resumed asynchronously while
189 other code is executing), and you call @link(Consume) twice.
190 The @link(SuccessfullyConsumed) will only fire once, if user
191 bought item once.)
192 ) }
193 procedure Owns(const AProduct: TInAppProduct); virtual;
194 public
195 constructor Create(AOwner: TComponent); override;
196 destructor Destroy; override;
197
198 { Initialize a list of products for which to query prices from server.
199 The overloaded version with TAvailableProduct allows to provide additional
200 information to the in-app payment system, see @link(TAvailableProduct) docs.
201 @groupBegin }
202 procedure SetAvailableProducts(const Names: array of string); overload;
203 procedure SetAvailableProducts(const Products: array of TAvailableProduct); overload;
204 { @groupEnd }
205
206 { Initiate a purchase of given item. }
207 procedure Purchase(const AProduct: TInAppProduct);
208
209 { Initiate a consumption of a consumable item.
210 You should listen on a "successful consumption" (override
211 @link(SuccessfullyConsumed)
212 method and/or watch @link(TInAppProduct.SuccessfullyConsumed))
213 until you actually act on the consumption (increase player gold or such). }
214 procedure Consume(const AProduct: TInAppProduct);
215
216 { Find product with given name.
217
218 Creates and adds new product, if not found (useful in case
219 you asked for a product before information about it arrived from the net,
220 or before you even called SetAvailableProducts with it). }
221 function Product(const ProductName: string): TInAppProduct;
222
223 { Purely for debug purposes, mockup buying (pretend that all purchases succeed). }
224 property DebugMockupBuying: boolean
225 read FDebugMockupBuying write FDebugMockupBuying default false;
226
227 { Call to refresh the state of owned (purchased) items from server.
228 This will call @link(Owns) on the owned items, and then @link(RefreshedPurchases)
229 or @link(OnRefreshedPurchases).
230
231 This is necessary to be called explicitly on iOS (for AppStore), as it will ask
232 user to login to AppStore.
233 On Android, this is done automatically at app start, and doesn't ask user anything. }
234 procedure RefreshPurchases;
235
236 { For debug purposes, immediately set all @link(TInAppProduct.Owns) to @false.
237 This does @italic(not) reset any persistent knowledge about the ownership of the items
238 of course, it merely resets the temporary (in CGE) knowledge about what is owned.
239 If the purchases communicate with any store (Google Play on Android, AppStore on iOS)
240 then the purchases will be restored next time the @link(RefreshPurchases) are done. }
241 procedure DebugClearPurchases;
242 published
243 { Called when the prices (and other shop-related information)
244 are known about the products. The information is stored inside
245 @link(TInAppProduct) instances, e.g. query @link(TInAppProduct.Price),
246 @link(TInAppProduct.Title) and so on. Get the @link(TInAppProduct) instance
247 by @link(Product) method.
248
249 This signals that we queried the shop for the product information
250 like @link(TInAppProduct.Price) and @link(TInAppProduct.Title) and
251 @link(TInAppProduct.Description). This is automatically done always
252 when launching the application, and sometimes later too.
253
254 It does not mean that we have queried the ownership status of the products,
255 for this see @link(OnRefreshedPurchases).
256
257 See also @link(RefreshedPrices) method. Instead of assigning this event,
258 you can also override @link(RefreshedPrices) method in descendants. }
259 property OnRefreshedPrices: TNotifyEvent read FOnRefreshedPrices write FOnRefreshedPrices;
260
261 { Called when the ownership status of all products is known.
262 The information is stored inside @link(TInAppProduct.Owns),
263 you can get the @link(TInAppProduct) instance using the @link(Product) method.
264
265 The ownership status is automatically queried when the application starts on Android.
266 On iOS, it must be explicitly invoked using @link(RefreshPurchases) (this is a limitation
267 of iOS user-interface around this, so it cannot be hidden / workarounded by us). }
268 property OnRefreshedPurchases: TNotifyEvent read FOnRefreshedPurchases write FOnRefreshedPurchases;
269 end;
270
271 implementation
272
273 uses SysUtils,
274 CastleMessaging, CastleUtils, CastleLog, CastleUnicode,
275 CastleApplicationProperties;
276
277 { Convert many UTF-8 special characters to their ASCII counterparts.
278 This is useful for converting arbitrary UTF-8 strings for display,
279 when your font may not contain various local UTF-8 special characters. }
280 function ConvertSpecialsToAscii(const S: string): string;
281 begin
282 Result := SReplacePatterns(S,
283 { useful list of local chars from
284 http://stackoverflow.com/questions/2096667/convert-unicode-to-ascii-without-changing-the-string-length-in-java/2097224#comment46476953_2097224
285 with something from
286 http://www.xe.com/symbols.php
287 }
288 [' ', 'r̀', 'r̂', 'r̃', 'r̈', 'ʼ' , 'ŕ', 'ř', 't̀', 't̂', 'ẗ', 'ţ', 'ỳ', 'ỹ', 'ẙ', 'ʼ' , 'y̎', 'ý', 'ÿ', 'ŷ', 'p̂', 'p̈', 's̀', 's̃', 's̈', 's̊', 'ʼ' , 's̸', 'ś', 'ŝ', 'Ş', 'ş', 'š', 'd̂', 'd̃', 'd̈', 'ď', 'ʼ' , 'ḑ', 'f̈', 'f̸', 'g̀', 'g̃', 'g̈', 'ʼ̧', '‌', '​', '‌', '​', '́', 'ĝ', 'ǧ', 'ḧ', 'ĥ', 'j̈', 'j', 'ʼ' , 'ḱ', 'k̂', 'k̈', 'k̸', 'ǩ', 'l̂', 'l̃', 'l̈', 'Ł', 'ł', 'ẅ', 'ẍ', 'c̃', 'c̈', 'c̊', 'c', 'ʼ' , 'c̸', 'Ç', 'ç', 'ç', 'ć', 'ĉ', 'č', 'v̂', 'v̈', 'v', 'ʼ' , 'v̸', 'b́', 'b̧', 'ǹ', 'n̂', 'n̈', 'n̊', 'n', 'ʼ' , 'ń', 'ņ', 'ň', 'ñ', 'm̀', 'm̂', 'm̃', '‌', '​', 'm̈', '‌', '​', 'm̊', 'm̌', 'ǵ', 'ß', '€', '£'],
289 [' ', 'r', 'r', 'r', 'r', '''', 'r', 'r', 't', 't', 't', 't', 'y', 'y', 'y', '''', 'y', 'y', 'y', 'y', 'p', 'p', 's', 's', 's', 's', '''', 's', 's', 's', 'S', 's', 's', 'd', 'd', 'd', 'd', '''', 'd', 'f', 'f', 'g', 'g', 'g', '' , '', '', '', '', '', 'g', 'g', 'h', 'h', 'j', 'j', '''', 'k', 'k', 'k', 'K', 'k', 'l', 'l', 'l', 'L', 'l', 'w', 'x', 'c', 'c', 'c', 'c', '''', 'c', 'C', 'c', 'c', 'c', 'c', 'c', 'v', 'v', 'v', '''', 'v', 'b', 'b', 'n', 'n', 'n', 'n', 'n', '''', 'n', 'n', 'n', 'n', 'm', 'm', 'm', '', '', 'm', '', '', 'm', 'm', 'g', 'B', 'EUR', 'L'],
290 false);
291 end;
292
293 { TInAppProduct -------------------------------------------------------------- }
294
295 function TInAppProduct.Price(const ValueWhenUnknown: string): string;
296 begin
297 if PriceRaw = '' then
298 Result := ValueWhenUnknown
299 else
300 { note: do not use SReplaceChars, as these are UTF-8 chars, not 8-bit chars. }
301 Result := ConvertSpecialsToAscii(PriceRaw);
302 end;
303
304 { TInAppPurchases ------------------------------------------------------------ }
305
306 constructor TInAppPurchases.Create(AOwner: TComponent);
307 begin
308 inherited;
309 List := TProductList.Create(true);
310 Messaging.OnReceive.Add({$ifdef FPC}@{$endif} MessageReceived);
311 ApplicationProperties.OnInitializeJavaActivity.Add({$ifdef FPC}@{$endif} ReinitializeJavaActivity);
312 end;
313
314 destructor TInAppPurchases.Destroy;
315 begin
316 if Messaging <> nil then
317 Messaging.OnReceive.Remove({$ifdef FPC}@{$endif} MessageReceived);
318 if ApplicationProperties(false) <> nil then
319 ApplicationProperties(false).OnInitializeJavaActivity.Remove({$ifdef FPC}@{$endif} ReinitializeJavaActivity);
320 FreeAndNil(List);
321 inherited;
322 end;
323
324 procedure TInAppPurchases.ReinitializeJavaActivity(Sender: TObject);
325 begin
326 { in case Java activity got killed and is created again, reinitialize services }
327 if FLastAvailableProducts <> '' then
328 Messaging.Send(['in-app-purchases-set-available-products', FLastAvailableProducts]);
329 end;
330
331 function TInAppPurchases.MessageReceived(const Received: TCastleStringList;
332 const ReceivedStream: TMemoryStream): boolean;
333 var
334 P: TInAppProduct;
335 begin
336 Result := false;
337 if (Received.Count = 7) and
338 (Received[0] = 'in-app-purchases-can-purchase') then
339 begin
340 P := Product(Received[1]);
341 P.FPriceRaw := Received[2];
342 P.FTitle := Received[3];
343 P.FDescription := Received[4];
344 P.FPriceAmountMicros := StrToInt64(Received[5]);
345 P.FPriceCurrencyCode := Received[6];
346 Result := true;
347 end else
348 if (Received.Count = 2) and
349 (Received[0] = 'in-app-purchases-owns') then
350 begin
351 Owns(Product(Received[1]));
352 Result := true;
353 end else
354 if (Received.Count = 2) and
355 (Received[0] = 'in-app-purchases-consumed') then
356 begin
357 SuccessfullyConsumed(Product(Received[1]));
358 Result := true;
359 end else
360 if (Received.Count = 1) and
361 (Received[0] = 'in-app-purchases-refreshed-purchases') then
362 begin
363 RefreshedPurchases;
364 Result := true;
365 end else
366 if (Received.Count = 1) and
367 (Received[0] = 'in-app-purchases-refreshed-prices') then
368 begin
369 RefreshedPrices;
370 Result := true;
371 end;
372 end;
373
374 function TInAppPurchases.Product(const ProductName: string): TInAppProduct;
375 var
376 I: Integer;
377 begin
378 for I := 0 to List.Count - 1 do
379 if List[I].Name = ProductName then
380 Exit(List[I]);
381
382 { not found, so create new }
383 Result := TInAppProduct.Create;
384 Result.FName := ProductName;
385 if DebugMockupBuying then
386 Result.FPriceRaw := '10,00 USD'; //'6,15 zł';
387 List.Add(Result);
388 end;
389
390 procedure TInAppPurchases.Owns(const AProduct: TInAppProduct);
391 begin
392 AProduct.FOwns := true;
393 end;
394
395 procedure TInAppPurchases.Purchase(const AProduct: TInAppProduct);
396 begin
397 if DebugMockupBuying then
398 Owns(AProduct)
399 else
400 Messaging.Send(['in-app-purchases-purchase', AProduct.Name]);
401 end;
402
403 procedure TInAppPurchases.Consume(const AProduct: TInAppProduct);
404 begin
405 if DebugMockupBuying then
406 SuccessfullyConsumed(AProduct) else
407 Messaging.Send(['in-app-purchases-consume', AProduct.Name]);
408 end;
409
410 procedure TInAppPurchases.SuccessfullyConsumed(const AProduct: TInAppProduct);
411 begin
412 AProduct.SuccessfullyConsumed := true;
413 end;
414
415 procedure TInAppPurchases.SetAvailableProducts(const Names: array of string);
416 var
417 Products: array of TAvailableProduct;
418 I: Integer;
419 begin
420 SetLength(Products, Length(Names));
421 for I := 0 to High(Names) do
422 begin
423 Products[I].Name := Names[I];
424 Products[I].Category := '';
425 end;
426 SetAvailableProducts(Products);
427 end;
428
429 procedure TInAppPurchases.SetAvailableProducts(const Products: array of TAvailableProduct);
430 var
431 I: Integer;
432 begin
433 FLastAvailableProducts := '';
434 for I := 0 to High(Products) do
435 begin
436 FLastAvailableProducts := FLastAvailableProducts + Products[I].Name + Chr(3) + Products[I].Category;
437 if I < High(Products) then
438 FLastAvailableProducts := FLastAvailableProducts + Chr(2);
439 end;
440 Messaging.Send(['in-app-purchases-set-available-products', FLastAvailableProducts]);
441 end;
442
443 procedure TInAppPurchases.LogProducts(const Message: string);
444 var
445 I: Integer;
446 LogStr: string;
447 begin
448 LogStr := Message + NL;
449 for I := 0 to List.Count - 1 do
450 LogStr := LogStr + 'Product ' + List[I].Name +
451 ', price: ' + List[I].PriceRaw +
452 ', owned: ' + BoolToStr(List[I].Owns, true) +
453 ', title: ' + List[I].Title +
454 ', description: ' + List[I].Description +
455 ', price amount micros: ' + IntToStr(List[I].PriceAmountMicros) +
456 ', price currency code: ' + List[I].PriceCurrencyCode +
457 NL;
458 WritelnLogMultiline('InAppPurchases', LogStr);
459 end;
460
461 procedure TInAppPurchases.KnownCompletely;
462 begin
463 end;
464
465 procedure TInAppPurchases.RefreshPurchases;
466 begin
467 Messaging.Send(['in-app-purchases-refresh-purchases']);
468 end;
469
470 procedure TInAppPurchases.RefreshedPrices;
471 begin
472 LogProducts('Refreshed prices (and other store information) about all products:');
473 if Assigned(OnRefreshedPrices) then
474 OnRefreshedPrices(Self);
475 end;
476
477 procedure TInAppPurchases.RefreshedPurchases;
478 begin
479 LogProducts('Refreshed purchases (ownership status) of all products:');
480 if Assigned(OnRefreshedPurchases) then
481 OnRefreshedPurchases(Self);
482
483 {$warnings off} // deliberately calling deprecated, to keep it working
484 KnownCompletely;
485 {$warnings on}
486 end;
487
488 procedure TInAppPurchases.DebugClearPurchases;
489 var
490 I: Integer;
491 begin
492 for I := 0 to List.Count - 1 do
493 List[I].FOwns := false;
494 end;
495
496 end.