パブリッシャーは主に、読者とその利用資格を管理するためにサーバーサイドの統合を使用します。パブリッシャーは、主に UpdateReaderEntitlements
を使用して、PPID のプロダクト ID 利用資格に関する Google の記録を更新します。
Google Cloud の設定
Google Cloud で定期購読のリンクを設定する作業は、主に次の 2 つに分けられます。
- 特定のプロジェクトに対して該当の API を有効にする
- その API にアクセスするためのサービス アカウントを作成する
Subscription Linking API を有効にする
サービス アカウントを使用して読者の利用資格を管理するには、Google Cloud プロジェクトで Subscription Linking API を有効にして、OAuth サービス アカウントを適切に構成する必要があります。プロジェクトの Subscription Linking API を有効にするには、メニュー -> [API とサービス] -> [ライブラリ] に移動して Subscription Linking
を検索するか、ページに直接アクセスしてください。
https://console.cloud.google.com/apis/library?project=gcp_project_id
図 1. API ライブラリに移動し、Google Cloud プロジェクトに対して API を有効にする。
サービス アカウントを作成する
サービス アカウントは、アプリケーションから Subscription Linking API へのアクセスを許可するために使用されます。
- プロジェクトのコンソールでサービス アカウントを作成します。
- サービス アカウントの認証情報を作成し、その
credentials.json
ファイルをアプリケーションがアクセスできる安全な場所に保存します。 - 作成したサービス アカウントに「定期購読リンク管理者」という IAM ロールを付与します。サービス アカウントの機能をさらに細かく管理する場合は、以下の表から適切なロールを割り当てることができます。
機能 / ロール | 定期購読リンク管理者 | 定期購読リンク閲覧者 | 定期購読リンク利用資格の閲覧者 |
---|---|---|---|
読者の利用資格の取得 | |||
読者の取得 | |||
読者の利用資格の更新 | |||
読者の削除 |
Subscription Linking API でサービス アカウントを使用する
サービス アカウントを使用して Subscription Linking API の呼び出しを認証するには、googleapis クライアント ライブラリ クライアント ライブラリ(access_token
リクエストを自動的に処理します)を使用するか、REST API でリクエストに直接署名します。REST API を使用する場合は、まず access_token
(Google Auth ライブラリまたはサービス アカウント JWT を使用)を取得し、Authorization
ヘッダーに含める必要があります。
次のクライアント ライブラリと REST API の両方の例に、getReader()
、getReaderEntitlements()
、updateReaderEntitlements()
、deleteReader()
を呼び出す方法のサンプルコードがあります。
クライアント ライブラリ
このセクションでは、Node.js で googleapis クライアント ライブラリを使用する方法について説明します。
リクエストの例
Auth.GoogleAuth
コンストラクタの keyFile
フィールドに、サービス アカウント キーのパスを設定します。組織のポリシーによりサービス アカウント キーをエクスポートできない場合は、アカウントのデフォルト認証情報(ADC)メソッドを使用できます。ADC メソッドを使用する場合は、keyFile
フィールドを指定する必要はありません。ADC が自動的に認証情報を検索します。
import {readerrevenuesubscriptionlinking_v1, Auth} from 'googleapis';
const subscriptionLinking = readerrevenuesubscriptionlinking_v1.Readerrevenuesubscriptionlinking;
class SubscriptionLinking {
constructor() {
this.auth = new Auth.GoogleAuth({
keyFile: process.env.KEY_FILE,
scopes: [
'https://www.googleapis.com/auth/readerrevenue.subscriptionlinking.manage'
],
})
}
init() {
return new subscriptionLinking(
{version: 'v1', auth: this.auth})
}
}
const subscriptionLinkingApi = new SubscriptionLinking();
const client = subscriptionLinkingApi.init();
/**
* Retrieves details for a specific reader associated with the publication.
* @async
* @param {string} ppid - The Publisher Provided ID (ppid) for the reader.
* @return {Promise<object>} A promise that resolves with the reader's details
* from the API.
*/
async function getReader(ppid) {
const publicationId = process.env.PUBLICATION_ID;
return await client.publications.readers.get({
name: `publications/${publicationId}/readers/${ppid}`,
});
};
/**
* Updates the entitlements for a specific reader.
* @async
* @param {string} ppid - The Publisher Provided ID (ppid) for the reader whose
* entitlements are being updated.
* @return {Promise<object>} A promise that resolves with the result of the
* updated entitlements object.
*/
async function updateReaderEntitlements(ppid) {
const publicationId = process.env.PUBLICATION_ID;
const requestBody = {
/*
Refer to
https://developers.google.com/news/subscribe/subscription-linking/appendix/glossary#entitlements_object
*/
entitlements : [{
product_id: `${publicationId}:basic`,
subscription_token: 'abc1234',
detail: 'This is our basic plan',
expire_time: '2025-10-21T03:05:08.200564Z'
}]
};
return await client.publications.readers.updateEntitlements({
name: `publications/${publicationId}/readers/${ppid}/entitlements`,
requestBody
});
};
/**
* Retrieves the current entitlements for a specific reader.
* @async
* @param {string} ppid - The Publisher Provided ID (ppid) for the reader.
* @return {Promise<object>} A promise that resolves with the reader's entitlements object.
*/
async function getReaderEntitlements(ppid) {
const publicationId = process.env.PUBLICATION_ID;
return await client.publications.readers.getEntitlements({
name: `publications/${publicationId}/readers/${ppid}/entitlements`
});
};
/**
* Deletes a specific Subscription Linkikng reader record associated with the publication.
* @async
* @param {string} ppid - The Publisher Provided ID (ppid) for the reader to be deleted.
* @param {boolean=} forceDelete - If true, delete the user even if their
* entitelements are not empty
* @return {Promise<object>} A promise that resolves upon successful deletion
* with an empty object ({})
*/
async function deleteReader(ppid, forceDelete = false) {
const publicationId = process.env.PUBLICATION_ID;
return await client.publications.readers.delete({
name: `publications/${publicationId}/readers/${ppid}`
force: forceDelete
});
};
REST API
REST API エンドポイントを呼び出す場合は、いずれかの方法で accessToken
を取得し、Authorization
ヘッダーに設定できます。
1. GoogleAuth
ライブラリを使用する
credentials
キーには、サービス アカウント キーまたはアカウントのデフォルト認証情報(ADC)を使用できます。ADC 方式を使用する場合は、ADC が認証情報を自動的に検索するため、credentials
フィールドを指定する必要はありません。
import { GoogleAuth } from 'google-auth-library';
import credentialJson from 'path_to_your_json_file' with { type: 'json' };
const auth = new GoogleAuth({
credentials: credential_json,
scopes: [
'https://www.googleapis.com/auth/readerrevenue.subscriptionlinking.manage'
]
});
async function getAccessToken() {
const accessToken = await auth.getAccessToken();
return accessToken;
}
2. サービス アカウントの JWT を使用して access_token
を生成する
import fetch from 'node-fetch';
import jwt from 'jsonwebtoken';
function getSignedJwt() {
/*
Either store the service account credentials string in an environmental variable
Or implement logic to fetch it.
*/
const key_file = process.env.CREDENTIALS_STRING
const issueDate = new Date();
const expireMinutes = 60;
const offsetInSeconds = issueDate.getTimezoneOffset() * 60000;
const expireDate = new Date(issueDate.getTime() + (expireMinutes * 60000));
const iat = Math.floor((issueDate.getTime() + offsetInSeconds) / 1000);
const exp = Math.floor((expireDate.getTime() + offsetInSeconds) / 1000);
const token = {
iss: key_file.client_email,
iat,
exp,
aud: 'https://oauth2.googleapis.com/token',
scope:'https://www.googleapis.com/auth/readerrevenue.subscriptionlinking.manage',
}
return jwt.sign(token, key_file.private_key, {
algorithm: 'RS256',
keyid: key_file.private_key_id,
})
}
async function getAccessToken(signedJwt) {
let body = new URLSearchParams();
body.set('grant_type', 'urn:ietf:params:oauth:grant-type:jwt-bearer');
body.set('assertion', signedJwt);
const response = await fetch('https://oauth2.googleapis.com/token', {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body
})
const accessResponse = await response.json();
return accessResponse.access_token;
}
Google Auth ライブラリを使用した REST API 呼び出しのサンプルコード
import { GoogleAuth } from 'google-auth-library';
import fetch from 'node-fetch'
import credentialJson from 'path_to_your_json_file' with { type: 'json' };
const BASE_SUBSCRIPTION_LINKING_API_URL='https://readerrevenuesubscriptionlinking.googleapis.com/v1';
const publicationId = process.env.PUBLICATION_ID
const auth = new GoogleAuth({
credentials: credentialJson,
scopes: [
'https://www.googleapis.com/auth/readerrevenue.subscriptionlinking.manage'
]
});
async function getAccessToken() {
const accessToken = await auth.getAccessToken();
return accessToken;
}
/**
* Retrieves details for a specific reader associated with the publication.
* @async
* @param {string} ppid - The Publisher Provided ID (ppid) for the reader.
* @return {object} reader json for the given ppid
*/
async function getReader(ppid) {
const endpoint = `${BASE_SUBSCRIPTION_LINKING_API_URL}/publications/${publicationId}/readers/${ppid}`;
const accessToken = await getAccessToken();
const response = await fetch(endpoint, {
method: 'GET',
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
const reader = await response.json();
return reader;
}
/**
* Updates the entitlements for a specific reader.
* @async
* @param {string} ppid - The Publisher Provided ID (ppid) for the reader.
* @return {object} the updated entitlements object in json.
*/
async function updateReaderEntitlements(ppid) {
const endpoint = `${BASE_SUBSCRIPTION_LINKING_API_URL}/publications/${publicationId}/readers/${ppid}/entitlements`;
const requestBody = {
/*
Refer to
https://developers.google.com/news/subscribe/subscription-linking/appendix/glossary#entitlements_object
*/
entitlements : [{
product_id: `${publicationId}:basic`,
subscription_token: 'abc1234',
detail: 'This is our basic plan',
expire_time: '2025-10-21T03:05:08.200564Z'
}]
};
const response = await fetch(endpoint, {
method: 'PATCH',
headers: {
Authorization: `Bearer ${accessToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(requestBody)
})
const updatedEntitlements = await response.json();
return updatedEntitlements;
}
/**
* Retrieves the current entitlements for a specific reader.
* @async
* @param {string} ppid - The Publisher Provided ID (ppid) for the reader.
* @return {object} the reader's entitlements object in json.
*/
async function getReaderEntitlements(ppid) {
const endpoint = `${BASE_SUBSCRIPTION_LINKING_API_URL}/publications/${publicationId}/readers/${ppid}/entitlements`;
const accessToken = await getAccessToken();
const response = await fetch(endpoint, {
method: 'GET',
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
const entitlements = await response.json();
return entitlements;
}
/**
* Deletes a specific Subscription Linkikng reader record associated with the publication.
* @async
* @param {string} ppid - The Publisher Provided ID (ppid) for the reader.
* @param {boolean=} forceDelete - If true, delete the user even if their
* entitelements are not empty
* @return {object} returns an empty object ({}) if the delete operation is successful
*/
async function deleteReader(ppid, forceDelete = false) {
const endpoint = `${BASE_SUBSCRIPTION_LINKING_API_URL}/publications/${publicationId}/readers/${ppid}?force=${forceDelete}`;
const response = await fetch(endpoint, {
method: 'DELETE',
headers: {
Authorization: `Bearer ${accessToken}`,
}
});
const result = await response.json();
return result;
}