getting UNKNOWN_ENVELOPE_RECIPIENT docusign php API with template - php

I am working on the Docusign php rest API. Everything was working , But now i have to USe template with this . I wrote the script for this . But now i am getting this error .
Error Code:UNKNOWN_ENVELOPE_RECIPIENT Error Message : The recipient
you have identified is not a valid recipient of the specified
envelope.
But if i remove the ClientUserId
$viewrequest->setClientUserId('12345');
I am getting the error
Error Code:ACCOUNT_NOT_AUTHORIZED_FOR_ENVELOPE Error Message : This
account is not authorized to access the requested envelope.
Here is my function to create the docusign request.
include_once('DocuSign/bootstrap.php');
echo signatureRequestFromTemplate();
function signatureRequestFromTemplate()
{
$recipientEmail= "test#gmail.com";
$recipientName = "test";
$username = "testuser#gmail.com";
$password = "telemate";
$integrator_key = "SALE-252453454-54b3-4a86-bb25-1f21cb2edc21";
$documentFileName = __DIR__ ."/Contract.pdf";
$documentName = "datedDoc.txt";
$host = "https://demo.docusign.net/restapi";
// create configuration object and configure custom auth header
$config = new DocuSign\eSign\Configuration();
$config->setHost($host);
$config->addDefaultHeader("X-DocuSign-Authentication", "{\"Username\":\"" . $username . "\",\"Password\":\"" . $password . "\",\"IntegratorKey\":\"" . $integrator_key . "\"}");
// instantiate a new docusign api client
$apiClient = new DocuSign\eSign\ApiClient($config);
$accountId = null;
try
{
//*** STEP 1 - Login API: get first Account ID and baseURL
$authenticationApi = new DocuSign\eSign\Api\AuthenticationApi($apiClient);
$options = new \DocuSign\eSign\Api\AuthenticationApi\LoginOptions();
$loginInformation = $authenticationApi->login($options);
if(isset($loginInformation) && count($loginInformation) > 0)
{
$loginAccount = $loginInformation->getLoginAccounts()[0];
$host = $loginAccount->getBaseUrl();
$host = explode("/v2",$host);
$host = $host[0];
// UPDATE configuration object
$config->setHost($host);
// instantiate a NEW docusign api client (that has the correct baseUrl/host)
$apiClient = new DocuSign\eSign\ApiClient($config);
if(isset($loginInformation))
{
$accountId = $loginAccount->getAccountId();
if(!empty($accountId))
{
//*** STEP 2 - Signature Request from a Template
// create envelope call is available in the EnvelopesApi
$envelopeApi = new DocuSign\eSign\Api\EnvelopesApi($apiClient);
// assign recipient to template role by setting name, email, and role name. Note that the
// template role name must match the placeholder role name saved in your account template.
$templateRole = new DocuSign\eSign\Model\TemplateRole();
$templateRole->setEmail($recipientEmail);
$templateRole->setName($recipientName);
$templateRole->setRoleName("Buyer");
// instantiate a new envelope object and configure settings
$envelop_definition = new DocuSign\eSign\Model\EnvelopeDefinition();
$envelop_definition->setEmailSubject("[DocuSign PHP SDK] - Signature Request Sample");
$envelop_definition->setTemplateId("EDAA30DE-551F-46C7-A7D3-9B6CA33AD07A");
$envelop_definition->setTemplateRoles(array($templateRole));
// set envelope status to "sent" to immediately send the signature request
$envelop_definition->setStatus("sent");
// optional envelope parameters
$options = new \DocuSign\eSign\Api\EnvelopesApi\CreateEnvelopeOptions();
$options->setCdseMode(null);
$options->setMergeRolesOnDraft(null);
// create and send the envelope (aka signature request)
$envelop_summary = $envelopeApi->createEnvelope($accountId, $envelop_definition, $options);
$document=json_decode($envelop_summary);
$envloped=$document->envelopeId;
$ReturnUrl="http://www.test.com/demo2/?action=docusign_request&uid=10&envelopid=" . $envloped;
$viewrequest = new DocuSign\eSign\Model\RecipientViewRequest();
$viewrequest->setUserName($recipientName);
$viewrequest->setEmail($recipientEmail);
//$viewrequest->setRecipientId(1);
//$viewrequest->setClientUserId('12345');
$viewrequest->setAuthenticationMethod('email');
$viewrequest->setReturnUrl($ReturnUrl);
$envelopview=$envelopeApi->createRecipientView($accountId,$document->envelopeId,$viewrequest);
echo $redirecturl=$envelopview->getUrl();
if(!empty($envelop_summary))
{
//echo "$envelop_summary";
}
}
}
}
}
catch (DocuSign\eSign\ApiException $ex)
{
echo "Exception: " . $ex->getMessage() . "\n";
}
}
I test it by using listRecipients it give me this response
DocuSign\eSign\Model\Recipients Object
(
[signers:protected] => Array
(
[0] => DocuSign\eSign\Model\Signer Object
(
[signature_info:protected] =>
[default_recipient:protected] =>
[tabs:protected] =>
[sign_in_each_location:protected] => false
[offline_attributes:protected] =>
[require_signer_certificate:protected] =>
[require_sign_on_paper:protected] =>
[can_sign_offline:protected] =>
[is_bulk_recipient:protected] => false
[bulk_recipients_uri:protected] =>
[recipient_supplies_tabs:protected] =>
[excluded_documents:protected] =>
[name:protected] => test
[email:protected] => test#gmail.com
[email_recipient_post_signing_url:protected] =>
[signing_group_id:protected] =>
[signing_group_name:protected] =>
[signing_group_users:protected] =>
[recipient_id:protected] => 1
[recipient_id_guid:protected] => e074bc90-44a0-4a0f-a9a6-68dd2ae3747c
[access_code:protected] =>
[add_access_code_to_email:protected] =>
[require_id_lookup:protected] => false
[id_check_configuration_name:protected] =>
[social_authentications:protected] =>
[phone_authentication:protected] =>
[saml_authentication:protected] =>
[sms_authentication:protected] =>
[user_id:protected] => a36eb466-1b84-47a4-9e0d-733d16637444
[client_user_id:protected] =>
[embedded_recipient_start_url:protected] =>
[custom_fields:protected] =>
[routing_order:protected] => 1
[id_check_information_input:protected] =>
[recipient_attachments:protected] =>
[note:protected] =>
[role_name:protected] => Buyer
[status:protected] => sent
[signed_date_time:protected] =>
[delivered_date_time:protected] =>
[declined_date_time:protected] =>
[sent_date_time:protected] =>
[declined_reason:protected] =>
[delivery_method:protected] =>
[fax_number:protected] =>
[template_locked:protected] =>
[template_required:protected] =>
[email_notification:protected] =>
[inherit_email_notification_configuration:protected] =>
[error_details:protected] =>
[recipient_authentication_status:protected] =>
[total_tab_count:protected] =>
)
)
[agents:protected] => Array
(
)
[editors:protected] => Array
(
)
[intermediaries:protected] => Array
(
)
[carbon_copies:protected] => Array
(
)
[certified_deliveries:protected] => Array
(
)
[in_person_signers:protected] => Array
(
)
[recipient_count:protected] => 1
[current_routing_order:protected] => 1
[error_details:protected] =>
)

I have solved this Errror . Actually i need to add ClientId in template setting also . I just added $templateRole->setClientUserId('12345');
$templateRole = new DocuSign\eSign\Model\TemplateRole();
$templateRole->setEmail($recipientEmail);
$templateRole->setName($recipientName);
$templateRole->setRoleName("Buyer");
$templateRole->setClientUserId('12345'); // added this

Related

pay the money on click 'pay' button in admin panal from company's paypal account to payal account of client using adaptive payments in php

I want to transfer/pay money on click 'pay' button in admin panal from company's paypal account to payal account of client using adaptive payments in php.
I tried lot of more for this but every time fail. please help..
I also follow this
How to transfer money from one PayPal account to another PayPal account?
Note:- I run it on localhost and using pay sandbox accounts
I currently use below code and use sdk adaptivepayments-sdk-php
my configration.php file is
<?php
class Configuration {
public static function getConfig() {
$config = array(
"mode" => "sandbox"
);
return $config;
}
public static function getAcctAndConfig() {
$config = array(
// Signature Credential
"acct1.UserName" => "*************.************.com",
"acct1.Password" => "**********************",
"acct1.Signature" => "***************************************",
"acct1.AppId" => "APP-**********************"
);
return array_merge($config, self::getConfig());
;
}
}
and my process.php file's cose is
<?php
session_start();
require_once('../PPBootStrap.php');
require_once('../Common/Constants.php');
define("DEFAULT_SELECT", "- Select -");
$returnUrl = "http://localhost/paypal/adaptive/parallel/success.php";
$cancelUrl = "http://localhost/paypal/adaptive/parallel/index.php";
$memo = "Adaptive Payment";
$actionType = "PAY";
$currencyCode = "USD";
$senderEmail ="info#birddog.com";
$receiverEmail = array("manojrana#gmail.com");
$receiverAmount = array("300.00");
$primaryReceiver = array("false");
$_SESSION['facilty_provider'] = array("AirGo Airline's Test Store");
if (isset($receiverEmail)) {
$receiver = array();
for ($i = 0; $i < count($receiverEmail); $i++) {
$receiver[$i] = new Receiver();
$receiver[$i]->email = $receiverEmail[$i];
$receiver[$i]->amount = $receiverAmount[$i];
$receiver[$i]->primary = $primaryReceiver[$i];
}
$receiverList = new ReceiverList($receiver);
}
$payRequest = new PayRequest(new RequestEnvelope("en_US"), $actionType, $cancelUrl, $currencyCode, $receiverList, $returnUrl);
// Add optional params
if ($memo != "") {
$payRequest->memo = $memo;
}
$service = new AdaptivePaymentsService(Configuration::getAcctAndConfig());
try {
**$response = $service->Pay($payRequest);**
$ack = strtoupper($response->responseEnvelope->ack);
if ($ack == "SUCCESS") {
$_SESSION['pay_key'] = $payKey = $response->payKey;
$payKey = $response->payKey;
$payPalURL = PAYPAL_REDIRECT_URL . '_ap-payment&paykey=' . $payKey;
header('Location: ' . $payPalURL);
}
} catch (Exception $ex) {
require_once '../Common/Error.php';
exit;
}
and i got blank screen as output because of $response = $service->Pay($payRequest); return as below when i try to print this
PayResponse Object
(
[responseEnvelope] => ResponseEnvelope Object
(
[timestamp] => 2017-10-11T22:20:35.114-07:00
[ack] => Failure
[correlationId] => aebfb26213bbe
[build] => 39000598
)
[payKey] =>
[paymentExecStatus] =>
[payErrorList] =>
[paymentInfoList] =>
[sender] =>
[defaultFundingPlan] =>
[warningDataList] =>
[error] => Array
(
[0] => ErrorData Object
(
[errorId] => 520003
[domain] => PLATFORM
[subdomain] => Application
[severity] => Error
[category] => Application
[message] => Authentication failed. API credentials are incorrect.
[exceptionId] =>
[parameter] =>
)
)
)
Please help me

Paypal PHP SDK returning 10002 Security header is not valid

Iam new to paypal php SDK this is the code iam using
$RPProfileDetails = new RecurringPaymentsProfileDetailsType();
$RPProfileDetails->SubscriberName = 'Test Customer';
$RPProfileDetails->BillingStartDate = '29/5/2016';
$activationDetails = new ActivationDetailsType();
$activationDetails->InitialAmount = new BasicAmountType($currencyCode, 10);
$activationDetails->FailedInitialAmountAction = 'ContinueOnFailure';//$_REQUEST['failedInitialAmountAction'];
$paymentBillingPeriod = new BillingPeriodDetailsType();
$paymentBillingPeriod->BillingFrequency = 365;//$_REQUEST['billingFrequency'];
$paymentBillingPeriod->BillingPeriod = 'Day';//$_REQUEST['billingPeriod'];
$paymentBillingPeriod->TotalBillingCycles = 365;//$_REQUEST['totalBillingCycles'];
$paymentBillingPeriod->Amount = new BasicAmountType($currencyCode, 10);//$_REQUEST['paymentAmount']
$scheduleDetails = new ScheduleDetailsType();
$scheduleDetails->Description = 'Artist Access amount';//$_REQUEST['profileDescription'];
$scheduleDetails->PaymentPeriod = $paymentBillingPeriod;
$createRPProfileRequestDetail = new CreateRecurringPaymentsProfileRequestDetailsType();
$_REQUEST['token'] ='';
if(trim($_REQUEST['token']) != "") {
$createRPProfileRequestDetail->Token = $_REQUEST['token'];
} else {
$creditCard = new CreditCardDetailsType();
$creditCard->CreditCardNumber = '41111111111111111';//$_REQUEST['creditCardNumber'];
$creditCard->CreditCardType = 'Visa';//$_REQUEST['creditCardType'];
$creditCard->CVV2 = '111';//$_REQUEST['cvv'];
$creditCard->ExpMonth = '9';//$_REQUEST['expMonth'];
$creditCard->ExpYear = '2022';//$_REQUEST['expYear'];
$createRPProfileRequestDetail->CreditCard = $creditCard;
}
$createRPProfileRequestDetail->ScheduleDetails = $scheduleDetails;
$createRPProfileRequestDetail->RecurringPaymentsProfileDetails = $RPProfileDetails;
$createRPProfileRequest = new CreateRecurringPaymentsProfileRequestType();
$createRPProfileRequest->CreateRecurringPaymentsProfileRequestDetails = $createRPProfileRequestDetail;
$createRPProfileReq = new CreateRecurringPaymentsProfileReq();
$createRPProfileReq->CreateRecurringPaymentsProfileRequest = $createRPProfileRequest;
$config = array(
// values: 'sandbox' for testing
// 'live' for production
"mode" => "sandbox",
'log.LogEnabled' => true,
'log.FileName' => '../PayPal.log',
'log.LogLevel' => 'FINE',
// These values are defaulted in SDK. If you want to override default values, uncomment it and add your value.
// "http.ConnectionTimeOut" => "5000",
// "http.Retry" => "2",
// Signature Credential
"acct1.UserName" => "asp.mobileappz_api1.gmail.com",
"acct1.Password" => "TR2R87Q3W7XT7UJQ",
"acct1.Signature" => "AFcWxV21C7fd0v3bYYYRCpSSRl31Abq4txmPS2AOjtNVgh-ZRkhGwY3D",
// Subject is optional and is required only in case of third party authorization
// "acct1.Subject" => "",
// Sample Certificate Credential
// "acct1.UserName" => "certuser_biz_api1.paypal.com",
// "acct1.Password" => "D6JNKKULHN3G5B8A",
// Certificate path relative to config folder or absolute path in file system
// "acct1.CertPath" => "cert_key.pem",
// Subject is optional and is required only in case of third party authorization
// "acct1.Subject" => "",
);
$paypalService = new PayPalAPIInterfaceServiceService($config);
try {
/* wrap API method calls on the service object with a try catch */
$createRPProfileResponse = $paypalService->CreateRecurringPaymentsProfile($createRPProfileReq);
} catch (Exception $ex) {
echo '<pre>';
PRINT_r($ex);
//include_once("../Error.php");
exit;
}
if(isset($createRPProfileResponse)) {
echo "<table>";
echo "<tr><td>Ack :</td><td><div id='Ack'>$createRPProfileResponse->Ack</div> </td></tr>";
echo "<tr><td>ProfileID :</td><td><div id='ProfileID'>".$createRPProfileResponse->CreateRecurringPaymentsProfileResponseDetails->ProfileID ."</div> </td></tr>";
echo "</table>";
echo "<pre>";
print_r($createRPProfileResponse);
echo "</pre>";
}
}
Ack :
Failure
ProfileID :
PayPal\PayPalAPI\CreateRecurringPaymentsProfileResponseType Object
(
[CreateRecurringPaymentsProfileResponseDetails] => PayPal\EBLBaseComponents\CreateRecurringPaymentsProfileResponseDetailsType Object
(
[ProfileID] =>
[ProfileStatus] =>
[TransactionID] =>
[DCCProcessorResponse] =>
[DCCReturnCode] =>
)
[Timestamp] => 2016-06-07T03:29:31Z
[Ack] => Failure
[CorrelationID] => 9c2a8533bb7f5
[Errors] => Array
(
[0] => PayPal\EBLBaseComponents\ErrorType Object
(
[ShortMessage] => Security error
[LongMessage] => Security header is not valid
[ErrorCode] => 10002
[SeverityCode] => Error
[ErrorParameters] =>
)
)
[Version] => 106.0
[Build] => 22204133
)
I have crossed check its not because of wrong credentails i have setup an sandbox account on developer.paypal.com the url is that sdk create is also of sand box, but show how its not working please help. i have absolutely no clue. also this is an standard example from paypal sdk itself. please suggest where iam wrong.
10002 refers to incorrect API credentials,
you are using live PayPal account credentials and the code is set for sandbox
"mode" => "sandbox",
Change this to Live environment and try again.

Fitbit API response handling in PHP

I am using a PHP library (https://github.com/djchen/oauth2-fitbit) to retreive a users Fitbit data via Oauth2. I am getting the data correctly but I am not sure how to grab a specific item from the multidimensional array response.
I am using code below but doesnt work
$response = $provider->getResponse($request);
var_dump($response['encodedId'][0]);
Full PHP code
$provider = new djchen\OAuth2\Client\Provider\Fitbit([
'clientId' => 'xxx',
'clientSecret' => 'xxx',
'redirectUri' => 'http://xxx-env.us-east-1.elasticbeanstalk.com/a/fitbitapi'
]);
// start the session
session_start();
// If we don't have an authorization code then get one
if (!isset($_GET['code'])) {
// Fetch the authorization URL from the provider; this returns the
// urlAuthorize option and generates and applies any necessary parameters
// (e.g. state).
$authorizationUrl = $provider->getAuthorizationUrl();
// Get the state generated for you and store it to the session.
$_SESSION['oauth2state'] = $provider->getState();
// Redirect the user to the authorization URL.
header('Location: ' . $authorizationUrl);
exit;
// Check given state against previously stored one to mitigate CSRF attack
} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {
unset($_SESSION['oauth2state']);
exit('Invalid state');
} else {
try {
// Try to get an access token using the authorization code grant.
$accessToken = $provider->getAccessToken('authorization_code', [
'code' => $_GET['code']
]);
// We have an access token, which we may use in authenticated
// requests against the service provider's API.
echo $accessToken->getToken() . "\n";
echo $accessToken->getRefreshToken() . "\n";
echo $accessToken->getExpires() . "\n";
echo ($accessToken->hasExpired() ? 'expired' : 'not expired') . "\n";
// Using the access token, we may look up details about the
// resource owner.
$resourceOwner = $provider->getResourceOwner($accessToken);
var_export($resourceOwner->toArray());
// The provider provides a way to get an authenticated API request for
// the service, using the access token; it returns an object conforming
// to Psr\Http\Message\RequestInterface.
$request = $provider->getAuthenticatedRequest(
'GET',
'https://api.fitbit.com/1/user/-/profile.json',
$accessToken
);
// Make the authenticated API request and get the response.
$response = $provider->getResponse($request);
var_dump($response['encodedId'][0]);
Response data
eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0NjAzNzgxOTYsInNjb3BlcyI6InJ3ZWkgcnBybyByaHIgcmxvYyByc2xlIHJzZXQgcmFjdCByc29jIiwic3ViIjoiNEg4NU5WIiwiYXVkIjoiMjI3UUNXIiwiaXNzIjoiRml0Yml0IiwidHlwIjoiYWNjZXNzX3Rva2VuIiwiaWF0IjoxNDYwMzc0NTk2fQ.NN9OOx--3YLvwai0hl0ZRJ4MNWXlaMwcEJ_xxxxxb2382a930144c3a76e69567dcbf0d9834c574919fff8c268b378e635735f1bbf 1460378196 not expired array ( 'encodedId' => '4545NV', 'displayName'
=> 'dan', )...
I am using the same PHP library for FitBit API integration. The response you have pasted with the question is the data that is coming because of the following part of your code:
// requests against the service provider's API.
echo $accessToken->getToken() . "\n";
echo $accessToken->getRefreshToken() . "\n";
echo $accessToken->getExpires() . "\n";
echo ($accessToken->hasExpired() ? 'expired' : 'not expired') . "\n";
// Using the access token, we may look up details about the
// resource owner.
$resourceOwner = $provider->getResourceOwner($accessToken);
var_export($resourceOwner->toArray());
When you try to get the user profile from FitBit, you make the below request :
$request = $provider->getAuthenticatedRequest(
'GET',
'https://api.fitbit.com/1/user/-/profile.json',
$accessToken
);
// Make the authenticated API request and get the response.
$response = $provider->getResponse($request);
The $response comes in the below format and you can see there that "encodeId" is not the direct key there. Below is the example of var_dump($response); -
Array(
[user] => Array
(
[age] => 27
[avatar] => https://static0.fitbit.com/images/profile/defaultProfile_100_male.gif
[avatar150] => https://static0.fitbit.com/images/profile/defaultProfile_150_male.gif
[averageDailySteps] => 3165
[corporate] =>
[dateOfBirth] => 1991-04-02
[displayName] => Avtar
[distanceUnit] => METRIC
[encodedId] => 478ZBH
[features] => Array
(
[exerciseGoal] => 1
)
[foodsLocale] => en_GB
[fullName] => Avtar Gaur
[gender] => MALE
[glucoseUnit] => METRIC
[height] => 181
[heightUnit] => METRIC
[locale] => en_IN
[memberSince] => 2016-01-17
[offsetFromUTCMillis] => 19800000
[startDayOfWeek] => MONDAY
[strideLengthRunning] => 94.2
[strideLengthRunningType] => default
[strideLengthWalking] => 75.1
[strideLengthWalkingType] => default
[timezone] => Asia/Colombo
[topBadges] => Array
(
[0] => Array
(
)
[1] => Array
(
)
[2] => Array
(
)
)
[waterUnit] => METRIC
[waterUnitName] => ml
[weight] => 80
[weightUnit] => METRIC
)
)
In order to access anything in there you need to access it in this manner -
$encodedId = $response['user']['encodedId];
I hope this was helpful to you. You can ask more questions related to fitbit API as I have got it all working, including the Fitbit Subscriver API and Notifications.

Twitter Codebird Error

I am trying to use codebird to tweet using PHP. Initially I was unable to get Access Token but after I defined CallbackURL in settings that issue seems to be resolved. Now it is returning oauth token:
Codebird\Codebird Object ( [_oauth_token:protected] => codehere [_oauth_token_secret:protected] => codehere [_return_format:protected] => 0 [_supported_media_files:protected] => Array ( [0] => 1 [1] => 2 [2] => 3 ) [_version:protected] => 3.0.0-dev [_use_curl:protected] => 1 [_timeout:protected] => 10000 [_connectionTimeout:protected] => 3000 )
But when i try to tweet i get following error:
stdClass Object ( [errors] => Array ( [0] => stdClass Object ( [code]
=> 89 [message] => Invalid or expired token. ) ) [httpstatus] => 401 [rate] => )
Following is my code
Codebird\Codebird::setConsumerKey('copy+paste from twitter', 'copy+paste from twitter'); // I changed it to my settings
$cb = \Codebird\Codebird::getInstance();
if (! isset($_SESSION['oauth_token'])) {
// get the request token
$reply = $cb->oauth_requestToken(array(
'oauth_callback' => 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']
));
// store the token
$cb->setToken($reply->oauth_token, $reply->oauth_token_secret);
$_SESSION['oauth_token'] = $reply->oauth_token;
$_SESSION['oauth_token_secret'] = $reply->oauth_token_secret;
$_SESSION['oauth_verify'] = true;
// redirect to auth website
$auth_url = $cb->oauth_authorize();
header('Location: ' . $auth_url);
die();
} elseif (isset($_GET['oauth_verifier']) && isset($_SESSION['oauth_verify'])) {
// verify the token
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
unset($_SESSION['oauth_verify']);
// get the access token
$reply = $cb->oauth_accessToken(array(
'oauth_verifier' => $_GET['oauth_verifier']
));
// store the token (which is different from the request token!)
$_SESSION['oauth_token'] = $reply->oauth_token;
$_SESSION['oauth_token_secret'] = $reply->oauth_token_secret;
// send to same URL, without oauth GET parameters
header('Location: ' . basename(__FILE__));
die();
}
// assign access token on each page load
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
print_r($cb);
$params = array(
'status' => 'Auto Post on Twitter with PHP http://goo.gl/OZHaQD #php #twitter'
);
$reply = $cb->statuses_update($params);
print_r($reply);
Thanks in advance for the assistance.
Is your callback address the one registered with Twitter in the app definition?
Do you have "read and write" access in the app definition?
Have you exceeded the rate limit for posting?
I'd check those things first, as I don't see anything obviously missing from your code snippet.

Create user using Moodle webservice

I have tried to create a new user on the Moodle by web service api.
I tried with a example that i found on the github and with another php code
In the both i receive the same response:
"Missing required key in single structure: users"
the response:
{
"exception":"invalid_parameter_exception",
"errorcode":"invalidparameter",
"message":"Invalid parameter value detected",
"debuginfo":"Missing required key in single structure: users"
}
I try to change the object by a array, but the error continues.
my code:
$functionname = 'core_user_create_users';
$user1 = new stdClass();
$user1->id = 1;
$user1->username = 'testusername1';
$user1->password = 'testpassword1';
$user1->firstname = 'testfirstname1';
$user1->lastname = 'testlastname1';
$user1->email = 'testemail1#moodle.com';
$user1->auth = 'manual';
$user1->idnumber = 'testidnumber1';
$user1->description = 'Hello World!';
$user1->city = 'testcity1';
$user1->country = 'BR';
$token = 'mytoken';
$domainname = 'localhost/moodle';
$functionname = 'core_user_create_users';
$restformat = 'json';
$serverurl = $domainname . '/webservice/rest/server.php'. '?wstoken=' . $token . '&wsfunction='.$functionname.'&moodlewsrestformat=' . $restformat;
$users = array($user1);
$params = array('users' => $users);
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => 'Content-Type: text/plain',
'content' => $params
)
));
$contents = file_get_contents($serverurl, null, $context);
//print_r($contents);
$resposta = json_decode($contents);
I have a valid token and the user is allowed to use the core_user_create_users function
get same problem with required key 'users'
solve problem with this =>
$serverurl = $domainname . '/webservice/rest/server.php'. '?wstoken=' . $token . '&wsfunction='.$functionname;
//require_once('../curl.php');
$curl = new curl;
$params = "&users[0][username]=loginnn&users[0][password]=4815162342Qq*&users[0][firstname]=allala&users[0][lastname]=trest&users[0][email]=ty#mail.ru";
//if rest format == 'xml', then we do not add the param for backward compatibility with Moodle < 2.2
$restformat = ($restformat == 'json')?'&moodlewsrestformat=' . $restformat:'';
$resp = $curl->post($serverurl . $restformat, $params);
I think You must high the debugging level in your moodle system, I hope you will get more useful information regarding this error, debugging will help you to reach the exact problem. go through following path:
Home ► Site administration ► Development ► Debugging
choose Developer level from the debug messages and save the changes
I have a similar problem once, in my experience is a problema with $user1->password = 'testpassword1'; Moodle needs a password with one uppercase letter and at least one simbol like / . , - _ etc.
try a new password maybe it works...
Do not pass the ID into the user array, as it doesn't accept it as a parameter. For more details, please read the WebService API documentation for creating a user in Moodle.
came across the same need today and I used your post to get the code from GitHUB so I guess I'd tell you how I fixed the error:
change your code to the following:
$users = array((array)$user1);
$params = array('users' => (array)$users);
The code from GitHUB $user1 is an object. Moodle required an Array.
Below is copied from Moodle's documentation.
[users] =>
Array
(
[0] =>
Array
(
[username] => string
[password] => string
[firstname] => string
[lastname] => string
[email] => string
[auth] => string
[idnumber] => string
[lang] => string
[calendartype] => string
[theme] => string
[timezone] => string
[mailformat] => int
[description] => string
[city] => string
[country] => string
[firstnamephonetic] => string
[lastnamephonetic] => string
[middlename] => string
[alternatename] => string
[preferences] =>
Array
(
[0] =>
Array
(
[type] => string
[value] => string
)
)
[customfields] =>
Array
(
[0] =>
Array
(
[type] => string
[value] => string
)
)
)
)
In our case, we added Https support, but we were still calling the Http version of the Moodle url. Changing to Https solved the problem.
This is tested and working on Moodle 3.1.2 - I find this a much cleaner and easier to understand solution, using a proper array (as Moodle expects) native cURL and http_build_query...
Make sure the password you are providing to Moodle meets your security requirements.
$moodledata['users'][] = array(
'username' => 'testuser123',
'password' => 'TestPass1!',
'firstname' => 'Firstname',
'lastname' => 'Lastname',
'email' => 'test#test.com',
);
//open connection
$token = 'your-token-goes-here';
$domainname = 'https://yourmoodlesite.tld';
$functionname = 'core_user_create_users';
$url = $domainname . '/webservice/rest/server.php?wstoken=' . $token . '&wsfunction='.$functionname."&moodlewsrestformat=json";
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($moodledata));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//execute post, and get our JSON as defined above with moodlewsrestformat=json
$result = curl_exec($ch);
//if you want it in an array
//$result = json_decode($result, true);

Categories