跳转到内容

支付

游戏内玩家支付的逻辑涉及玩家使用Lobah APP货币购买游戏内物品。

1. 配置商品

进入Lobah开发者中心 Operations -> Products 页面, 点击 Add New Product, 并填写以下信息:

  • 商品名称:产品的名称
  • 商品标识:产品的唯一标识符。用于在游戏中识别产品;请确保它是唯一的。
  • 商品价格:产品的价格,以Lobah货币“金币(Coins)”计价。“金币(Coins)”与美元的兑换比例为 100:1.

2. 获取App ID和App Key

进入Lobah开发者中心 Deployment -> Configuration 页面获取App ID和App Key。

3. 服务端API验证与支付

Lobah服务端API的接入点是: https://game-gateway.lobah.net

使用服务端API的第一步是执行签名算法,然后调用购买接口进行支付。更多详情请参阅 下一章中 全部API参考 部分。

以下是一个用于签名和进行支付的Java代码片段示例,仅供参考:

java
package net.lobah;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;

public class Demo {

    private static final String appKey = "";       // Configuration -> appKey
    private static final String accessToken = "";  // params.token 
    private static final String appId = "";        // params.gameId 
    private static final String sessionId = "";    // params.sessionId 
    private static final String uid = "";          // params.uid
    private static final String productId = "";    // Product Identification
    
    private static final String method = "POST";
    private static final String host = "https://game-gateway.lobah.net";
    
    public static void main(String[] args) throws Exception {
        test();
        getProfile();
        purchase();
    }

    public static void test() throws Exception {
        String path = "/1.0/open-gateway/game/test";
        String postBody = "";
        httpPost(path, postBody);
    }

    public static void purchase() throws Exception {
        String referenceId = UUID.randomUUID().toString().replace("-", "").substring(0, 12);
        String path = "/1.0/open-gateway/game/purchase";
        String postBody = "{ \"app_id\": " + appId + ", " + " \"product_id\": \"" + productId + "\", \"reference_id\": \"" + referenceId + "\", \"session_id\": " + sessionId + ", \"uid\": " + uid + " }";
        httpPost(path, postBody);
    }

    public static void getProfile() throws Exception {
        String path = "/1.0/open-gateway/game/get-profile";
        String postBody = "{\"app_id\": " + appId + ", \"token\": \"" + accessToken + "\", \"uid\": " + uid + " }";
        httpPost(path, postBody);
    }

    public static void httpPost(String requestPath, String postBody) throws IOException, NoSuchAlgorithmException, InvalidKeyException {
        Map<String, String> reqParamsMap = new TreeMap<>();
        reqParamsMap.put("access_token", accessToken);
        reqParamsMap.put("app_id", appId);
        reqParamsMap.put("nonce", UUID.randomUUID().toString().replace("-", "").substring(0, 8));
        reqParamsMap.put("ts", String.valueOf(Instant.now().getEpochSecond()));
        reqParamsMap.put("uid", uid);
        reqParamsMap.put("zone", "SA");

        String reqParam = encodeURL(reqParamsMap);
        String encodeStr = method + requestPath + reqParam + postBody;
        String urlEncodedData = URLEncoder.encode(encodeStr, "UTF-8");
        String digest = genDigest(urlEncodedData, appKey, "HmacMD5");
        System.out.println("Encode String: " + encodeStr);
        System.out.println("Encode Data: " + urlEncodedData);
        System.out.println("Digest: " + digest);
        httpPostWithSig(host + requestPath + "?" +  reqParam + "&sig=" + digest, postBody);
    }

    private static void httpPostWithSig(String requestUrl, String requestBody) throws IOException {
        System.out.println("Request Url: " + requestUrl);
        URL url = new URL(requestUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod(method);
        connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
        connection.setRequestProperty("Content-Type", "application/json; utf-8");
        connection.setRequestProperty("Accept", "application/json");
        connection.setDoOutput(true);

        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = requestBody.getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }

        int responseCode = connection.getResponseCode();
        System.out.println("Response Code: " + responseCode);

        try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
            StringBuilder response = new StringBuilder();
            String responseLine;
            while ((responseLine = br.readLine()) != null) {
                response.append(responseLine.trim());
            }
            System.out.println("Response Body: " + response);
        }
        connection.disconnect();
    }

    private static String genDigest(String msg, String keyString, String algo) throws NoSuchAlgorithmException, InvalidKeyException {
        SecretKeySpec key = new SecretKeySpec((keyString).getBytes(StandardCharsets.UTF_8), algo);
        Mac mac = Mac.getInstance(algo);
        mac.init(key);
        byte[] bytes = mac.doFinal(msg.getBytes(StandardCharsets.US_ASCII));
        StringBuilder hash = new StringBuilder();
        for (byte aByte : bytes) {
            String hex = Integer.toHexString(0xFF & aByte);
            if (hex.length() == 1) {
                hash.append('0');
            }
            hash.append(hex);
        }
        return hash.toString();
    }

    private static String encodeURL(Map<String, String> parameters) {
        StringBuilder result = new StringBuilder(2048);
        for (String encodedName : parameters.keySet()) {
            String encodedValue = parameters.get(encodedName);
            if (result.length() > 0) {
                result.append('&');
            }
            result.append(encodedName);
            if (encodedValue != null) {
                result.append("=");
                result.append(encodedValue);
            }
        }
        return result.toString();
    }
}

Swiper and Play