diff --git a/content/blog/cocos-tg-2/P1.jpg b/content/blog/cocos-tg-2/P1.jpg new file mode 100644 index 0000000..7d43075 Binary files /dev/null and b/content/blog/cocos-tg-2/P1.jpg differ diff --git a/content/blog/cocos-tg-2/P2.jpg b/content/blog/cocos-tg-2/P2.jpg new file mode 100644 index 0000000..557db90 Binary files /dev/null and b/content/blog/cocos-tg-2/P2.jpg differ diff --git a/content/blog/cocos-tg-2/P3.jpg b/content/blog/cocos-tg-2/P3.jpg new file mode 100644 index 0000000..e7595df Binary files /dev/null and b/content/blog/cocos-tg-2/P3.jpg differ diff --git a/content/blog/cocos-tg-2/P4.jpg b/content/blog/cocos-tg-2/P4.jpg new file mode 100644 index 0000000..d6fb91c Binary files /dev/null and b/content/blog/cocos-tg-2/P4.jpg differ diff --git a/content/blog/cocos-tg-2/index.md b/content/blog/cocos-tg-2/index.md new file mode 100644 index 0000000..c3972c9 --- /dev/null +++ b/content/blog/cocos-tg-2/index.md @@ -0,0 +1,132 @@ ++++ +title = "CocosCreator with Telegram Game (Part 2) - TON Payment" +description = "Learning how to use CocosCreator to develop Telegram game and use the TON payment" +date = 2024-09-19T18:50:42+00:00 +updated = 2024-9-19T18:50:42+00:00 +draft = false +template = "blog/page.html" + +[taxonomies] +authors = ["Zypher Dev"] + +[extra] +toc = true +lead = "Learning how to use CocosCreator to develop Telegram game and use the TON payment" ++++ + +# CocosCreator Development of Telegram Games (Part Two) - TON Payment + +In this article, we will continue to explore how to develop Telegram games using `CocosCreator`, focusing on how to integrate TON payment functionality. Through this tutorial, you will learn how to connect to `TON Connect` in your game, implement wallet connection, payment, and the verification after pay, and then providing decentralized payment for your game. Next, we will introduce how to implement TON payment integration step by step. We hope this tutorial will be helpful to you. + +## CocosCreator + Telegram +If you don't know much about CocosCreator and Telegram, you can read [previous blog](https://docs.zypher.network/blog/cocos-tg/) first. + +## Integrate TON Connect into your game +### 1. Add `tonconnect-ui.min.js` to the index.html +```html + +``` + +### 2. Add a div to use the wallet +```html + +
+``` + +### 3. Initialize TonconnectUI +```javascript +// TonConnectUI +// @ts-ignore +this.tonConnectUI = new window.TON_CONNECT_UI.TonConnectUI( +{ + manifestUrl: 'https://xxxxxxxx/tonconnect-manifest.json', + buttonRootId: 'ton-connect', // confirm this ID is the same as above div + chain: 'testnet', + network: 'testnet', // mainnet +}); + +// Redirect the user to the Telegram mini program after the wallet is connected +this.tonConnectUI.uiOptions = { + twaReturnUrl: 'https://t.me/RainbowJourneyBot', +}; +``` + +![P1](P1.jpg) + +### 4. Connect to wallet +```javascript +const connectedWallet = await this.tonConnectUI.connectWallet().catch(error => { + console.error('Error connecting to wallet:', error); +}); + +// disconnect wallet +await tonConnectUI.disconnect(); +``` + +![P2](P2.jpg) + +![P3](P3.jpg) + +### 5. Pay +```javascript +const time = Math.floor(Date.now() / 1000) + 600; +const str = `${PlayerModel.inst.tg_userInfo.id}||${time}`; +const body = beginCell() + .storeUint(0, 32) // write 32 zero bits to indicate that a text comment will follow + .storeStringTail(str) // write our text comment + .endCell(); + +const paymentRequest = { + address: 'UQB7RFm0dj-LYhs7UYtsYna_xxxxx_jrUoemFQmO9JT', // receiver address + amount: amount.toString(), // amount, unit is ns (1 TON = 1,000,000,000ns ) + payload: body.toBoc().toString('base64'), // optional, external payload data +}; + +const response = await this.tonConnectUI.sendTransaction({ + validUntil: time, // peroid time, unit is seconds + messages: [paymentRequest], +}); + +// after pay, continue ... +``` + +### 6. Verify +After the payment is completed, you will get the `boc`, and take the boc to the backend for verification to obtain the in-game items. +```javascript +{ + boc: "te6cckEBAwEA4QAC44gBZUPZ6qi8Dtmm1cot1P175lXUARlUVwlfMM19lkERK1oCUB3RqDxAFnPpeo191X/jiimn9Bwnq3zwcU/MMjHRNN5sC5tyymBV3SJ1rjyyscAjrDDFAIV/iE+WBySEPP9wCU1NGLsfcvVgAAACSAAYHAECAGhCAFlQ9nqqLwO2abVyi3U/XvmVdQBGVRXCV8wzX2WQRErWoAmJaAAAAAAAAAAAAAAAAAAAAGZCAFlQ9nqqLwO2abVyi3U/XvmVdQBGVRXCV8wzX2WQRErWnMS0AAAAAAAAAAAAAAAAAAADkk4U" +} + +const address = Address.parse('UQB7RFm0dj-LYhs7UYtsYna_xxxxxx_jrUoemFQmO9JT'); +const client = new TonClient({ + endpoint: 'https://testnet.toncenter.com/api/v2/jsonRPC', +}); +const pollInterval = 3000; // 3 seconds +const maxAttempts = 20; // 1 minute max wait time (3 seconds * 20 attempts) +const checkTransactions = async (attempt: number) => { + try { + const trans = await client.getTransactions(address, { inclusive: false, limit: 1 }); + + for (const tran of trans) { + if (tran.inMessage) { + //@ts-ignore + const payCoins = tran.inMessage.info.value.coins; + const desStr = tran.inMessage.body.beginParse().loadStringTail(); + // next check order + if (attempt < maxAttempts) { + setTimeout(() => checkTransactions(attempt + 1), pollInterval); + } else { + // update tx status to failed + transaction.status = 'failed'; + return res.status(200).json({ errorcode: 4, error: 'no message' }); + }}; + } catch (err) { + console.error('process-transaction error:', err); + res.status(200).json({ errorcode: 6, error: 'internal server error' }); + } +} +``` + +![P4](P4.jpg) + +That's all, the centralized game connect to Telegram payment in ton has ended. I hope it will be helpful to you. diff --git a/content/blog/cocos-tg/index.md b/content/blog/cocos-tg/index.md index 095471e..db6dec8 100644 --- a/content/blog/cocos-tg/index.md +++ b/content/blog/cocos-tg/index.md @@ -1,5 +1,5 @@ +++ -title = "CocosCreator Development Telegram Game" +title = "CocosCreator with Telegram Game" description = "Learning how to use CocosCreator to develop Telegram game" date = 2024-08-28T18:50:42+00:00 updated = 2024-08-28T18:50:42+00:00 @@ -141,12 +141,14 @@ Through these steps, you can successfully start and publish a Cocos Creator proj ## 4. Protect Trump Cocos Code Explanation -4.1. Create a new scene, create a node in the scene, and attach the script GameLanch.ts. +### 4.1 New project +Create a new scene, create a node in the scene, and attach the script GameLanch.ts. (I also placed the background image for the main interface here for preloading, but it can be omitted.) ![P1](P1.png) -4.2. GameLanch.ts. +### 4.2 Game Lanch +GameLanch.ts. ```javascript // Manage global data PlayerModel.inst.init(); @@ -165,7 +167,7 @@ Use the uiManager interface to control the UI uiManager.open(UIID.UILoading); ``` -4.3. Telegram Data Retrieval +### 4.3 Telegram Data Retrieval Add the following script reference in the template folder build-teleplates/web-mobile/index.html ```html @@ -245,7 +247,8 @@ Send the retrieved window[‘Telegram’]?.WebApp?.initData to the server for ve ![P2](P2.png) -4.4. Add the UIRank.ts script to the rank page. After UIRank inherits from the UIView class, it can be managed through the uiManager. +### 4.4 Rank page +Add the UIRank.ts script to the rank page. After UIRank inherits from the UIView class, it can be managed through the uiManager. ```javascript Export default class UIRank extends UIView // Get leaderboard data @@ -253,7 +256,7 @@ let ranksRes = await Http.getAllCoinsRank(PlayerModel.inst.tgInitData); this.list.refreshData(ranks); // Display in component ``` -4.5. Briefly discuss the reward. +### 4.5 Briefly discuss the reward ![P3](P3.png) ![P4](P4.png) @@ -292,10 +295,11 @@ onCopy() { } ``` -4.6. Modify the startup page by changing the startup page in the template. Mainly modify index.html and application.js. +### 4.6 Startup page +Modify the startup page by changing the startup page in the template. Mainly modify index.html and application.js. Added a background image and a progress bar. -4.7. Publish the game +### 4.7 Publish the game - [https://docs.cocos.com/creator/3.8/manual/zh/editor/publish/publish-web.html](https://docs.cocos.com/creator/3.8/manual/zh/editor/publish/publish-web.html) - [https://docs.cocos.com/creator/3.8/manual/zh/editor/publish/custom-project-build-template.html](https://docs.cocos.com/creator/3.8/manual/zh/editor/publish/custom-project-build-template.html) Refer to these two documents. Currently, it is published manually, but in the future, it can be published via command line. Don’t forget the MD5 when officially launching.