Reputation: 376
I am trying to create a pub/sub notification using PHP. I have a project and a service account. My code looks like:
use Google\Cloud\Core\Iam\PolicyBuilder;
use Google\Cloud\PubSub\PubSubClient;
use Google\Cloud\Storage\StorageClient;
self::$storage_client = new StorageClient(
[
'projectId' => "MY PROJECT ID",
'keyFile' => json_decode(file_get_contents("PATH TO MY KEYFILE", true)
]
);
$pubSub = new PubSubClient(
[ 'projectId' => "MY PROJECT ID"
);
$serviceAccountEmail = self::$storage_client->getServiceAccount();
$topicName = 'projects/MY PROJECT ID/topics/thumbnail-service-1';
$topic = $pubSub->topic( $topicName );
$iam = $topic->iam();
// --> Error happens here:
$updatedPolicy = (new PolicyBuilder( $iam->policy() ))
->addBinding('roles/pubsub.publisher', [ "serviceAccount:$serviceAccountEmail" ])
->result();
$iam->setPolicy( $updatedPolicy );
$notification = $bucket->createNotification( $topicName,
['event_types' => [
'OBJECT_FINALIZE',
'OBJECT_DELETE',
]
]
);
I think I"m trying to create the topic named, but I get this error:
exception 'Exception' with message 'exception 'Google\Cloud\Core\Exception\NotFoundException' with message '{
"error": {
"code": 404,
"message": "Resource not found (resource=thumbnail-service-1).",
"status": "NOT_FOUND"
}
}
It shouldn't be trying to find the topic, I want to create it. What am I missing?
Upvotes: 0
Views: 387
Reputation: 81464
You are not authorizing the PubSub client:
Change this section of your code:
$pubSub = new PubSubClient(
[ 'projectId' => "MY PROJECT ID" ]
);
To:
$pubSub = new PubSubClient(
[ 'projectId' => "MY PROJECT ID",
'keyFile' => json_decode(file_get_contents("PATH TO MY KEYFILE", true) ]
);
Your code is missing closing array brackets ]
. I assume that this is a copy-paste typo as PHP would print an error in this case.
Note: I prefer to use KeyFilePath
instead of KeyFile
. The code is easier to read.
$pubSub = new PubSubClient([
'projectId' => "MY PROJECT ID",
'keyFilePath' => "/path/to/service-account.json"
]);
Next, verify that the Topic Name actually exists.
Upvotes: 1
Reputation: 17271
The code you have presented isn't trying to create the Pub/Sub topic, it is trying to get an existing topic. If you want to create a topic, you need to call createTopic
:
use Google\Cloud\PubSub\PubSubClient;
$pubsub = new PubSubClient(['projectId' => $projectId]);
$topic = $pubsub->createTopic($topicName);
Once the topic is created, you should be able to call createNotification
with the topic name.
Upvotes: 1