how to get response in json format using twilio sdk - php

I am using Twilio's PHP SDK to send SMS. Below is the code:
<?php
// Required if your environment does not handle autoloading
require './autoload.php';
// Use the REST API Client to make requests to the Twilio REST API
use Twilio\Rest\Client;
// Your Account SID and Auth Token from twilio.com/console
$sid = 'XXXXXXXXXXXXXXXXXXXXXXXX';
$token = 'XXXXXXXXXXXXXXXXXXXX';
$client = new Client($sid, $token);
// Use the client to do fun stuff like send text messages!
$client->messages->create(
// the number you'd like to send the message to
'+XXXXXXXXXX',
array(
// A Twilio phone number you purchased at twilio.com/console
'from' => '+XXXXXXXX',
// the body of the text message you'd like to send
'body' => 'Hey Jenny! Good luck on the bar exam!'
)
);
**Response:
[Twilio.Api.V2010.MessageInstance accountSid=XXXXXXXXXXXXXXXX sid=XXXXXXXXXXXXXXX]**
How I can get the response in JSON Format?
Any help is appreciated.

I'm not sure if I have understood your intent properly, however, I've created a new GitHub repository which I hope gives you the information that you're after, if you're still interested.
The MessageInstance object which the call to $client->messages->create() returns won't return anything of value when passed to json_encode(). This is because the relevant properties are contained in a protected property, so json_encode() cannot access them.
One option to get around this is to use a class which implements JsonSerializable and returns a JSON representation of a MessageInstance object, such as JsonMessageInstance.
Have a look at the code and let me know if this does what you wanted.

The quick answer is:
$json_string = json_encode(</POST|GET>);
Use the $_POST or $_GET super globals and you get a json string format.
e.g.
/*
* Imagine this is the POST request
*
* $_POST = [
* 'foo' => 'Hello',
* 'bar' => 'World!'
* ];
*
*/
$json_string = json_encode($_POST); // You get → {"foo":"Hello","bar":"World!"}
In this way you encode the values in a JSON representation.

Related

GraphQL query connect to Dutchie API using PHP

I have a store in Dutchie.com. I want to access it's products using API key.
This has to do via Dutchie API using GraphQL integrated with PHP.
This is the Sample API Key:
public-eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJBUEktQ0xJRU5UIiwiZXhwIjozMzE4NjM5Mjc0NSwiaWF0IjoxNjI5NDgzOTQ1LCJpc3MiOiJodHRwczovL2R1dGNoY29tIiwianRpIjoiNGMtOTMyOC00MjhkLWEyYTMtOWQzMTc2ZTUwODY0IiwiZW50ZXJwcmlzZV9pZChLWExYTctNDM3OC05NWY4LTNlYzVzBiNSIsInV1aWQiOiI0M2ZlMjdkNy1iZWU2LTQxOTgtYWNhMi03N2Y5Y2I3MjI5MGIifQ.hCQWpcQ5uhKnZOSVQDA5SCMkx5kopC7H3upeU-1jMpg
This is the GraphQL Ping mutation.
mutation Ping {
ping {
id,
time
}
}
Dutchie End Point: https://plus.dutchie.com/plus/2021-07/graphql
http header parameter
{
"Authorization":"Bearer API KEY HERE"
}
Ping output
Basically I want to run GraphQL query in my PHP page. I'll add into my WordPress page later.
I have tried php-graphql-client php library.
Can someone help me to do this using above library or another one really appreciate. I wasted too much time for this as I have only few knowledge of GraphQL.
This is the code what I have tried.
$client = new Client(
'https://plus.dutchie.com/plus/2021-07/graphql',
['Authorization => Bearer API Key here']
);
// Create the GraphQL mutation
$gql = (new Mutation('Ping'))
->setSelectionSet(
[
'id',
'time',
]
);
// Run query to get results
try {
$results = $client->runQuery($gql);
}
catch (QueryError $exception) {
// Catch query error and desplay error details
print_r($exception->getErrorDetails());
exit;
}
// Display original response from endpoint
var_dump($results->getResponseObject());
// Display part of the returned results of the object
var_dump($results->getData()->pokemon);
// Reformat the results to an array and get the results of part of the array
$results->reformatResults(true);
print_r($results->getData()['data']);
Error what I got.
https://github.com/guzzle/psr7/blob/master/src/MessageTrait.php
Instead of:
$client = new Client(
'https://plus.dutchie.com/plus/2021-07/graphql',
['Authorization => Bearer API Key here']
);
Try
$client = new Client(
'https://plus.dutchie.com/plus/2021-07/graphql',
['Authorization' => 'Bearer API Key here']
);

Use token from "sign in with apple" to query apple music api

Context
I am trying to make webservice that fetches the name and email from an users Apple account and place a Song or Artist in his library.
For adding a Song to the library I found this apple-music-api. library. To make requests on behalf of a user you need to request a user token with Apple MusicKit JS library.
For fetching the name and email of the user I use this oauth2 client that uses the signin with Apple functionality.
Problem
A Using the apple music kit... I can not query any user profile data. At least I cannot seem to find an example nor any documentation of this. Is there a possibility to get the user email and name using this route?
B Using the Sign in with Apple oauth flow I receive an access token which contains the name and email. But I cannot use the token to query the apple music api. It seems their scopes are limited to the name and email...and no scope for the music api or related seems to exist. Is there a possibility to get an user token that can be used on the music api?
C Are there any other possibilities to accomplish this without requiring the user to sign in twice on apple (once for the email and once for pushing the Song to his library)
What I tried for option B
// $leeway is needed for clock skew
Firebase\JWT\JWT::$leeway = 60;
$provider = new League\OAuth2\Client\Provider\Apple([
'clientId' => 'com.myapp.www',
'teamId' => 'team.id', // 1A234BFK46 https://developer.apple.com/account/#/membership/ (Team ID)
'keyFileId' => 'key.id', // 1ABC6523AA https://developer.apple.com/account/resources/authkeys/list (Key ID)
'keyFilePath' => dirname(__FILE__) . '/AuthKey_key.id.p8', // __DIR__ . '/AuthKey_1ABC6523AA.p8' -> Download key above
'redirectUri' => PLUGIN_URL . 'callback-apple-music.php',
]);
if (isset($_POST['code'])) {
if (empty($_POST['state']) || !isset($_COOKIE['apple-oauth2state']) || ($_POST['state'] !== $_SESSION['apple-oauth2state'])) {
unset($_COOKIE['apple-oauth2state']);
exit('Invalid state');
} else {
try {
// Try to get an access token (using the authorization code grant) via signin_with_apple
/** #var AppleAccessToken $token */
$token = $provider->getAccessToken('authorization_code', [
'code' => $_POST['code']
]);
$access_token = $token->getToken();
// create an client for api.music.apple
$tokenGenerator = new PouleR\AppleMusicAPI\AppleMusicAPITokenGenerator();
$jwtToken = $tokenGenerator->generateDeveloperToken(
'team.id',
'key.id',
dirname(__FILE__) .'/AuthKey_key.id.p8'
);
// create a developer token again
$curl = new \Symfony\Component\HttpClient\CurlHttpClient();
$client = new PouleR\AppleMusicAPI\APIClient($curl);
$client->setDeveloperToken($jwtToken);
$api = new PouleR\AppleMusicAPI\AppleMusicAPI($client);
$api->setMusicUserToken($access_token);
// This endpoint needs authorisation
$result = $api->getAllLibraryPlaylists(); //https://api.music.apple.com/v1/me/library/playlists?offset=0&limit=25
echo '<pre>';
print_r($result);
echo '</pre>';
// wp_redirect($redirect_url);
exit;
} catch (Exception $e) {
echo '<pre>';
print_r($e);
echo '</pre>';
}
}
}
The problem with the question is that these are three questions - and not telling which client.
Most commonly "login with" is only good for creating local accounts without much typing.
And it is quite likely intentional, that the oAuth2 scope is extremely limited for this purpose.
And I've looked it up ...one needs a "Music User Token":
https://developer.apple.com/documentation/applemusicapi/getting_keys_and_creating_tokens
And this token needs to be passed as HTTP header: 'Music-User-Token: [music user token]'.
Which means, that the user token may either originate from an iOS device (you'd need to expose eg. a REST API, so that it can be posted and then used by PHP as HTTP header, on the server-side): https://developer.apple.com/documentation/storekit/skcloudservicecontroller/2909079-requestusertoken (this only requires a login to your own API).
When running Apple MusicKit JS on the cient-side (browser), two logins may not be evitable:
https://developer.apple.com/documentation/musickitjs/musickit/musickitinstance/2992701-authorize
It makes no sense to use both of these flows within the same method(which also ignores the principle of single responsibility).

How to send multiple images via Twilio Programmable MMS? (PHP)

I am facing a problem when I try to send multiple images in a single MMS. Even their documentation is not clear.
I couldn't find an example online showing the same.
According to their documentation about MMS
Up to 10 images that together total no more than 5mb can be sent at one time.
MMS is also only available in the US and Canada.
You can pass the images by using an array like so.
URL method: (urls have to be publicly accessible)
<?php
// Update the path below to your autoload.php,
// see https://getcomposer.org/doc/01-basic-usage.md
require_once '/path/to/vendor/autoload.php';
use Twilio\Rest\Client;
// Find your Account Sid and Auth Token at twilio.com/console
$sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$token = "your_auth_token";
$twilio = new Client($sid, $token);
$mediaUrls = array("https://demo.twilio.com/owl.png", "url2", "url3", "url4");
$message = $twilio->messages
->create("+12316851234", // to
array(
"body" => "Hello there!",
"from" => "+15555555555",
"mediaUrl" => $mediaUrls
)
);
print($message->sid);
Documentation:
https://www.twilio.com/docs/sms/api/media-resource
https://www.twilio.com/docs/sms/send-messages?code-sample=code-send-an-mms-message&code-language=PHP&code-sdk-version=5.x
More information about this here https://www.twilio.com/docs/sms/tutorials/how-to-send-sms-messages-php

DocuSign - Can't set "sent" on createEnvelope

I am using Docusign PHP Client and trying to create and envelope and send it as email. With the current SDK, I was getting an error:
INVALID_REQUEST_BODY The request body is missing or improperly formatted. Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'API_REST.Models.v2.document[]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.\r\n ◀
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive t ▶
Path 'documents.documentBase64', line 1, position 31.
So I had to edit EnvelopeApi.php (line 2876) json_encode($httpBody) to make it work.
Now that it's working, I receive a response like this, however I can't change status created to sent is my problem.
EnvelopeSummary {#460 ▼
#container: array:4 [▼
"envelope_id" => "6b9ef863-2ee0-4ea6-9f7e-20b7d4f59b22"
"status" => "created"
"status_date_time" => "2018-10-03T12:30:22.8600000Z"
"uri" => "/envelopes/6b9ef863-2ee0-4ea6-9f7e-20b7d4f59b22"
]
}
My full code:
First, I authenticated and fetched my $accountId
And then creating Envelope:
$path = public_path('test.pdf');
$b64Doc = base64_encode(file_get_contents($path));
$document = new Document();
$document->setName("TEST.pdf");
$document->setFileExtension("pdf");
$document->setDocumentId(1);
$document->setDocumentBase64($b64Doc);
$sign_here = new SignHere();
$sign_here->setXPosition(25);
$sign_here->setYPosition(50);
$sign_here->setDocumentId(1);
$sign_here->setPageNumber(1);
$sign_here->setRecipientId(1);
$tabs = new Tabs();
$tabs->setSignHereTabs($sign_here);
$signers = new Signer();
$signers->setName('Test User');
$signers->setEmail('test#mailinator.com');
$signers->setRoleName('Signer');
$signers->setRecipientId(1);
$signers->setRoutingOrder(1);
$signers->setTabs($tabs);
$recipients = new Recipients();
$recipients->setSigners($signers);
$envelope_definition = new EnvelopeDefinition();
$envelope_definition->setEmailSubject('Signature Request');
$envelope_definition->setStatus("sent"); // ***
$envelope_definition->setDocuments($document);
$envelope_definition->setRecipients($recipients);
$options = new CreateEnvelopeOptions();
$options->setCdseMode(null);
$options->setMergeRolesOnDraft(null);
try {
$envelopeSummary = $envelopeApi->createEnvelope($accountId, $envelope_definition, $options);
dd($envelopeSummary);
// Also tried this:
// $envelopeApi->update($accountId, $envelopeSummary->getEnvelopeId(), json_encode(['status' => 'sent']);
} catch (ApiException $e){
dd($e->getResponseBody()->errorCode . " " . $e->getResponseBody()->message);
}
$envelope_definition->setStatus("sent"); this should trigger the email, right? But it doesn't for some reason. Also I can't see this created envelope in my Sandbox either.
You are not setting signers correctly. It must be an array of signer objects.
Here is some untested code:
# This code creates a signer, not signers
$signer = new Signer();
$signer->setName('Test User');
$signer->setEmail('test#mailinator.com');
$signer->setRoleName('Signer');
$signer->setRecipientId(1);
$signer->setRoutingOrder(1);
$signer->setTabs($tabs);
$recipients = new Recipients();
# setSigners wants an array of signer objects.
# in this case, we make an array with one element
$recipients->setSigners(array($signer));
Also, you are not creating the tabs right either. Again, it needs to be an array of the tab type.
See this example for additional ideas.
Yes, setting status to sent should make DocuSign send the envelope upon creation. The fact that the response contains "status" => "created" seems to indicate that your setting of the property ($envelope_definition->setStatus("sent");) is not actually being included as part of the request that's being issued to DocuSign.
I've compared your code with the code examples provided in GitHub for the PHP SDK, specifically, with the signatureRequestOnDocument function on that page. The only obvious difference I can see between your code and that example code is in the syntax for creating objects. For example, creating the envelope:
Your code: $envelope_definition = new EnvelopeDefinition();
PHP SDK example code: $envelop_definition = new DocuSign\eSign\Model\EnvelopeDefinition();
I don't know much about PHP, let alone about the DocuSign PHP SDK, but I'd suggest that you try to closely mimic the code examples that are part of the SDK repo on GitHub, to see if you get a different result that way.
My code work like this :
$signersArray = array();
$signer = new Signer();
$signer->set...
$signersArray[] = $signer;
$recipients->setSigners($signersArray);
If it's not working try to dump the data send from the SDK to the API and double check that the status is correct :
Go to Docusign/esign-client/src/ApiClient.php and var_dump($postData) at line 159

send Notification to device using by tag value using pushwoosh

So i am developing an application which requires push notifications and i'm using pushwoosh. but currently i'm stuck on how to send targeted notifications to a device by a tag value.
I am using [http://gomoob.github.io/php-pushwoosh/]
Any help will be appreciated. thanks
$filter = '';
$request = CreateTargetedMessageRequest::create()
->setContent($options['body'])
->setData(
[
'custom' => 'json data'
]
)
->setDevicesFilter($filter);
$pushwoosh->createTargetedMessage($request);
what i want is the value for the filter
I ended up solving it myself. I used the setCondition() method to specify the tag name and value for what i wanted.
$request = CreateMessageRequest::create()
->addNotification(Notification::create()
->setContent($options['body'])
->setConditions([
IntCondition::create('userId')->eq($user_id)
]));
// Call the REST Web Service
$response = $pushwoosh->createMessage($request);

Categories