I'm tring to login with Blizzard ID in my site.
I think my code is work. User profile request failed.
I don't understand Blizzard's user profile Data structure.
Can you help me to get user's Id, Email and Battle Tag?
Here's my code
<?php
class Hybrid_Providers_Kakao extends Hybrid_Provider_Model_OAuth2
{
/**
* initialization
*/
function initialize()
{
parent::initialize();
// Provider API end-points
$this->api->api_base_url = "https://kr.api.battle.net/";
$this->api->authorize_url = "https://kr.battle.net/oauth/authorize";
$this->api->token_url = "https://kr.battle.net/oauth/token";
// redirect uri mismatches when authenticating with Battle.
if (isset($this->config['redirect_uri']) && !empty($this->config['redirect_uri'])) {
$this->api->redirect_uri = $this->config['redirect_uri'];
}
}
/**
* finish login step
*/
function loginFinish()
{
$error = (array_key_exists('error', $_REQUEST)) ? $_REQUEST['error'] : "";
// check for errors
if ( $error ){
throw new Exception( "Authentication failed! {$this->providerId} returned an error: $error", 5 );
}
// try to authenicate user
$code = (array_key_exists('code', $_REQUEST)) ? $_REQUEST['code'] : "";
try{
$this->authenticate( $code );
}
catch( Exception $e ){
throw new Exception( "User profile request failed! {$this->providerId} returned an error: $e", 6 );
}
// check if authenticated
if ( ! $this->api->access_token ){
throw new Exception( "Authentication failed! {$this->providerId} returned an invalid access token.", 5 );
}
// store tokens
$this->token("access_token", $this->api->access_token);
$this->token("refresh_token", $this->api->refresh_token);
$this->token("expires_in", $this->api->access_token_expires_in);
$this->token("expires_at", $this->api->access_token_expires_at);
// set user connected locally
$this->setUserConnected();
}
/**
* load the user profile
*/
function getUserProfile()
{
$this->api->decode_json = false;
$this->api->curl_header = array( 'Authorization: Bearer ' . $this->api->access_token );
$data = $this->api->api("account/profile", "POST");
if ( ! isset( $data->id ) ) {
throw new Exception("User profile request failed! {$this->providerId} returned an invalid response.", 6);
}
# store the user profile.
$this->user->profile->identifier = # $data->id;
$this->user->profile->displayName = # $data->battletag;
return $this->user->profile;
}
private function authenticate($code)
{
$params = array(
"response_type" => $code,
"grant_type" => "authorization_code",
"client_id" => $this->api->client_id,
"redirect_uri" => $this->api->redirect_uri,
"state" => $token,
"scope" => "sc2.profile",
);
if( $this->api->client_secret && ($this->api->client_secret !== $this->api->client_id) ){
$params['client_secret'] = $this->api->client_secret;
}
$response = $this->request($this->api->token_url, $params, $this->api->curl_authenticate_method);
$response = $this->parseRequestResult($response);
if ( ! $response || ! isset($response->access_token) ) {
throw new Exception("The Authorization Service has return: " . $response->error);
}
if ( isset($response->access_token) ) $this->api->access_token = $response->access_token;
if ( isset($response->refresh_token) ) $this->api->refresh_token = $response->refresh_token;
if ( isset($response->expires_in) ) $this->api->access_token_expires_in = $response->expires_in;
// calculate when the access token expire
if ( isset($response->expires_in) ) {
$this->api->access_token_expires_at = time() + $response->expires_in;
}
return $response;
}
private function request($url, $params=false, $type="GET")
{
if(Class_exists('Hybrid_Logger')){
Hybrid_Logger::info("Enter OAuth2Client::request( $url )");
Hybrid_Logger::debug("OAuth2Client::request(). dump request params: ", serialize( $params ));
}
$this->http_info = array();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL , $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT , $this->api->curl_time_out);
curl_setopt($ch, CURLOPT_USERAGENT , $this->api->curl_useragent);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->api->curl_connect_time_out);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->api->curl_ssl_verifypeer);
curl_setopt($ch, CURLOPT_HTTPHEADER , $this->api->curl_header);
if ( $this->api->curl_proxy ) {
curl_setopt( $ch, CURLOPT_PROXY, $this->curl_proxy);
}
if ( $type == "POST" ) {
curl_setopt($ch, CURLOPT_POST, 1);
if ($params) curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query($params) );
}
$response = curl_exec($ch);
if(Class_exists('Hybrid_Logger')){
Hybrid_Logger::debug( "OAuth2Client::request(). dump request info: ", serialize(curl_getinfo($ch)) );
Hybrid_Logger::debug( "OAuth2Client::request(). dump request result: ", serialize($response ));
}
$this->http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$this->http_info = array_merge($this->http_info, curl_getinfo($ch));
curl_close ($ch);
return $response;
}
private function parseRequestResult($result)
{
if ( json_decode($result) ) return json_decode($result);
parse_str( $result, $ouput );
$result = new StdClass();
foreach( $ouput as $k => $v )
$result->$k = $v;
return $result;
}
}
I think this code can't read user id
$this->user->profile->identifier = # $data->id;
$this->user->profile->displayName = # $data->battletag;
on this part.
It's not pure HybridAuth.
Related
after user fill form of his or her information it create some sessions that i need kill all sessions in callback page but it dont work by destroy sessions or unset sessions.
after fill information page we have 3 pages as bellow.
payment.php
<?php session_start();
require_once('variables.php');
require_once('../includes/config.php');
$stmt = $db->prepare('SELECT * FROM order_main WHERE name = :name and phone=:phone');
if($stmt->execute(array(':name' => $_SESSION['post-data']['name'], ':phone' => $_SESSION['post-data']
['phone'] ) ));
while($row = $stmt->fetch()){
//if($code == $row['code']){
//if(!empty($_POST['code'])){
$_SESSION['order_id'] = $row['order_id'];
//}
// }
}
$order_id = $_SESSION['order_id'];
$amount = $_SESSION['total'];
echo $_SESSION['order_id'];
$_SESSION['order_id']=3;
echo $_SESSION['post-data']['name'];
echo $_SESSION['post-data']['order_desc'];
$name = $_SESSION['post-data']['name'];
$phone = $_SESSION['post-data']['phone'];
$order_desc = $_SESSION['post-data']['order_desc'];
$params = array(
'order_id' => $order_id ,
'amount' => 10000,
'phone' => $phone,
'name' => $name,
'desc' => $order_desc,
'callback' => URL_CALLBACK,
);
idpay_payment_create($params);
/**
* #param array $params
* #return bool
*/
function idpay_payment_create($params) {
$header = array(
'Content-Type: application/json',
'X-API-KEY:' . APIKEY,
'X-SANDBOX:' . SANDBOX,
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, URL_PAYMENT);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
$result = json_decode($result);
if (empty($result) || empty($result->link)) {
print 'Exception message:';
print '<pre>';
print_r($result);
print '</pre>';
return FALSE;
}
//.Redirect to payment form
header('Location:' . $result->link);
}
variables.php
<?php session_start();
define('URL_CALLBACK', 'http://www.siteaddress.org/blog/php-simple-master/callback.php');
define('URL_PAYMENT', 'https://api.idpay.ir/v1.1/payment');
define('URL_INQUIRY', 'https://api.idpay.ir/v1.1/payment/inquiry');
define('URL_VERIFY', 'https://api.idpay.ir/v1.1/payment/verify');
define('APIKEY', 'xxxxx...');
define('SANDBOX', 1);
callback.php(i want destroy some or all sessions here but cant)
<?php session_start();
require_once('variables.php');
require_once('config.php');
?>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$response = $_POST;
}
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$response = $_GET;
}
if (empty($response['status']) ||
empty($response['id']) ||
empty($response['track_id']) ||
empty($response['order_id'])) {
return FALSE;
}
if ($response['status'] != 10) {
print idpay_payment_get_message($response['status']);
}
// if $response['id'] was not in the database return FALSE
$inquiry = idpay_payment_get_inquiry($response);
if ($inquiry) {
$verify = idpay_payment_verify($response);
}
/**
* #param array $response
* #return bool
*/
function idpay_payment_get_inquiry($response) {
$header = array(
'Content-Type: application/json',
'X-API-KEY:' . APIKEY,
'X-SANDBOX:' . SANDBOX,
);
$params = array(
'id' => $response['id'],
'order_id' => $response['order_id'],
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, URL_INQUIRY);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
$result = json_decode($result);
if (empty($result) ||
empty($result->status)) {
print 'Exception message:';
print '<pre>';
print_r($result);
print '</pre>';
return FALSE;
}
if ($result->status == 10) {
return TRUE;
}
print idpay_payment_get_message($result->status);
return FALSE;
}
/**
* #param array $response
* #return bool
*/
function idpay_payment_verify($response) {
$header = array(
'Content-Type: application/json',
'X-API-KEY:' . APIKEY,
'X-SANDBOX:' . SANDBOX,
);
$params = array(
'id' => $response['id'],
'order_id' => $response['order_id'],
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, URL_VERIFY);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
$result = json_decode($result);
if (empty($result) ||
empty($result->status)) {
print 'Exception message:';
print '<pre>';
print_r($result);
print '</pre>';
return FALSE;
}
print idpay_payment_get_message($result->status);
//print '<pre>';
//print_r($result);
//print '</pre>';
$stmt = $db->prepare('UPDATE order_main SET track_id = :track_id, id = :id, order_date=:date
WHERE order_id = :order_id ') ;
$stmt->execute(array(
':track_id' => $_GET['track_id'],
':id' => $_GET['id'],
':date' => $_GET['date'],
':order_id' => $_GET['order_id']
));
}
/**
* #param int $status
* #return string
*/
function idpay_payment_get_message($status) {
switch ($status) {
case 1:
return 'پرداخت انجام نشده است';
case 2:
return 'پرداخت ناموفق بوده است';
case 3:
return 'خطا رخ داده است';
case 10:
return 'در انتظار تایید پرداخت';
case 100:
return 'پرداخت تایید شده است لطفا منتظر بمانید';
case 101:
return 'پرداخت قبلاً تایید شده است';
default:
return 'Error handeling';
}
}
unset ($_SESSION['post-data']['name']);
unset ($_SESSION['post-data']['phone']);
if($_GET['order_desc']){
unset ($_SESSION['post-data']['order_desc']);
}
unset ($_SESSION['order_id']);
unset ($_SESSION['shopping_cart']);
session_start();
session_destroy();
session_commit();
just add session_destroy($_SESSION["your_session]); at the end of your code and same for session_commit
I am trying to create a record in zohocrm. i am using API version2 code.
i recieve this following error which i stated below. I tried stackoverflow for solutions but can't find relevant solution. I tried this Stackoverflow answer Zoho API V2 Update Record. It doesn't work for me. Help me with some solution. i use php version
7.1
Here's the Code i used:
public function createRecord($module, $module_fields)
{
global $HelperObj;
$WPCapture_includes_helper_Obj = new WPCapture_includes_helper_PRO();
$activateplugin = $WPCapture_includes_helper_Obj->ActivatedPlugin;
$moduleslug = $this->ModuleSlug = rtrim(strtolower($module), "s");
$zohoapi = new SmackZohoApi();
$module_field['data'] = array($module_fields);
$module_field['Owner']['id'] = $module_fields['SMOWNERID'];
$fields_to_skip = ['Digital_Interaction_s', 'Solution'];
foreach ($module_fields as $fieldname => $fieldvalue) {
if (!in_array($fieldname, $fields_to_skip)) {
continue;
}
$module_fields[$fieldname] = array();
if (is_string($fieldvalue)) {
array_push($module_fields[$fieldname], $fieldvalue);
} else if (is_array($fieldvalue)) {
array_push($module_fields[$fieldname], $fieldvalue);
}
}
//$fields = json_encode($module_fields);
$attachments = $module_fields['attachments'];
$body_json = array();
$body_json["data"] = array();
array_push($body_json["data"], $module_fields);
$record = $zohoapi->Zoho_CreateRecord($module, $body_json, $attachments);
if ($record['code'] == 'INVALID_TOKEN' || $record['code'] == 'AUTHENTICATION_FAILURE') {
$get_access_token = $zohoapi->refresh_token();
if (isset($get_access_token['error'])) {
if ($get_access_token['error'] == 'access_denied') {
$data['result'] = "failure";
$data['failure'] = 1;
$data['reason'] = "Access Denied to get the refresh token";
return $data;
}
}
$exist_config = get_option("wp_wpzohopro_settings");
$config['access_token'] = $get_access_token['access_token'];
$config['api_domain'] = $get_access_token['api_domain'];
$config['key'] = $exist_config['key'];
$config['secret'] = $exist_config['secret'];
$config['callback'] = $exist_config['callback'];
$config['refresh_token'] = $exist_config['refresh_token'];
update_option("wp_wpzohopro_settings", $config);
$this->createRecord($module, $module_fields);
} elseif ($record['data'][0]['code'] == 'SUCCESS') {
$data['result'] = "success";
$data['failure'] = 0;
} else {
$data['result'] = "failure";
$data['failure'] = 1;
$data['reason'] = "failed adding entry";
}
return $data;
}
API Call Code:
public function Zoho_CreateRecord($module = "Lead",$data_array,$extraParams) {
try{
$apiUrl = "https://www.zohoapis.com/crm/v2/$module";
$fields = json_encode($data_array);
$headers = array(
'Content-Type: application/json',
'Content-Length: ' . strlen($fields),
sprintf('Authorization: Zoho-oauthtoken %s', $this->access_token),
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
$result = curl_exec($ch);
curl_close($ch);
$result_array = json_decode($result,true);
if($extraParams != "")
{
foreach($extraParams as $field => $path){
$this->insertattachment($result_array,$path,$module);
}
}
}catch(\Exception $exception){
// TODO - handle the error in log
}
return $result_array;
}
error i got:
Array
(
[data] => Array
(
[0] => Array
(
[code] => INVALID_DATA
[details] => Array
(
[expected_data_type] => jsonarray
[api_name] => Solution_Interest
)
[message] => invalid data
[status] => error
)
)
)
By the details which you gave ,
(1)you said you wish to create "Contacts" , but the url you are using to create contact doesn't seems to create "Contacts" either by
**converting leads to account and contact , or
**directly creating contact
(2)you mentioned module name as "Lead" , try changing it to "Leads".
(3)variables $data_array & $extraParams , doesn't seems to hold any value , they seems to be null.
(4)Here is a help doc. for you
Create Contact
If that still doesn't solve your problem ,you could ask your queries at zoho crm community , people will definitely solve your queries Ask here
I am trying to use serverPilot API from my website. I have created simple functions like below for sample usage but its giving me error like below
Fatal error: Uncaught Error: Call to undefined function app_create()
I am new in PHP and don't know proper method to declare and use functions. Let me know what I am missing in this? My full PHP code is like below
<?php
if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['createApp'])){
$name = "sampleName";
$name = "hello";
$runtime ="php5.5";
$password = "Test#123";
$domains = array("www.example.com","example2.com");
app_create( $name, $sysuserid, $runtime, $domains = array());
}
else if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['createDb'])){
$id = 1;
$name = "hello";
$username ="testuser";
$password = "Test#123";
database_create( $id, $name, $username, $password );
}
else if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['createUser'])){
$id = 1;
$name = "hello";
$password = "Test#123";
sysuser_create( $id, $name, $password = NULL )();
}
class ServerPilot {
// variables
public $apiID = "";
public $apiKey = "";
public $decode;
// constants
const SP_API_ENDPOINT = 'https://api.serverpilot.io/v1/';
const SP_USERAGENT = 'ServerPilot-PHP/1.0';
const SP_HTTP_METHOD_POST = 'post';
const SP_HTTP_METHOD_GET = 'get';
const SP_HTTP_METHOD_DELETE = 'delete';
// error constants
const SP_MISSING_CONFIG = 'Missing config data';
const SP_MISSING_API = 'You must provide API credentials';
const SP_CURL_ERROR = 'Curl error code returned ';
public function __construct( $config = array() ) {
if( empty($config) ) throw new Exception(ServerPilot::SP_MISSING_CONFIG);
if( !isset($config['id']) || !isset($config['key']) ) throw new Exception(ServerPilot::SP_MISSING_API);
$this->apiID = $config['id'];
$this->apiKey = $config['key'];
$this->decode = ( isset($config['decode']) ) ? $config['decode'] : true;
}
public function sysuser_create( $id, $name, $password = NULL ) {
$params = array(
'serverid' => $id,
'name' => $name);
if( $password )
$params['password'] = $password;
return $this->_send_request( 'sysusers', $params, ServerPilot::SP_HTTP_METHOD_POST );
}
public function app_create( $name, $sysuserid, $runtime, $domains = array() ) {
$params = array(
'name' => $name,
'sysuserid' => $sysuserid,
'runtime' => $runtime);
if( $domains )
$params['domains'] = $domains;
return $this->_send_request( 'apps', $params, ServerPilot::SP_HTTP_METHOD_POST );
}
public function database_create( $id, $name, $username, $password ) {
$user = new stdClass();
$user->name = $username;
$user->password = $password;
$params = array(
'appid' => $id,
'name' => $name,
'user' => $user);
return $this->_send_request( 'dbs', $params, ServerPilot::SP_HTTP_METHOD_POST );
}
private function _send_request( $url_segs, $params = array(), $http_method = 'get' )
{
// Initialize and configure the request
$req = curl_init( ServerPilot::SP_API_ENDPOINT.$url_segs );
curl_setopt( $req, CURLOPT_USERAGENT, ServerPilot::SP_USERAGENT );
curl_setopt( $req, CURLOPT_HTTPAUTH, CURLAUTH_BASIC );
curl_setopt( $req, CURLOPT_USERPWD, $this->apiID.':'.$this->apiKey );
curl_setopt( $req, CURLOPT_RETURNTRANSFER, TRUE );
// Are we using POST or DELETE? Adjust the request accordingly
if( $http_method == ServerPilot::SP_HTTP_METHOD_POST ) {
curl_setopt( $req, CURLOPT_HTTPHEADER, array('Content-Type: application/json') );
curl_setopt( $req, CURLOPT_POST, TRUE );
curl_setopt( $req, CURLOPT_POSTFIELDS, json_encode($params) );
}
if( $http_method == ServerPilot::SP_HTTP_METHOD_DELETE ) {
curl_setopt( $req, CURLOPT_CUSTOMREQUEST, "DELETE" );
}
// Get the response, clean the request and return the data
$response = curl_exec( $req );
$http_status = curl_getinfo( $req, CURLINFO_HTTP_CODE );
curl_close( $req );
// Everything when fine
if( $http_status == 200 )
{
// Decode JSON by default
if( $this->decode )
return json_decode( $response );
else
return $response;
}
// Some error occurred
$data = json_decode( $response );
// The error was provided by serverpilot
if( property_exists( $data, 'error' ) && property_exists( $data->error, 'message' ) )
throw new ServerPilotException($data->error->message, $http_status);
// No error as provided, pick a default
switch( $http_status )
{
case 400:
throw new ServerPilotException('We couldn\'t understand your request. Typically missing a parameter or header.', $http_status);
break;
case 401:
throw new ServerPilotException('Either no authentication credentials were provided or they are invalid.', $http_status);
break;
case 402:
throw new ServerPilotException('Method is restricted to users on the Coach or Business plan.', $http_status);
break;
case 403:
throw new ServerPilotException('Forbidden.', $http_status);
break;
case 404:
throw new ServerPilotException('You requested a resource that does not exist.', $http_status);
break;
case 409:
throw new ServerPilotException('Typically when trying creating a resource that already exists.', $http_status);
break;
case 500:
throw new ServerPilotException('Something unexpected happened on ServerPilot\'s end.', $http_status);
break;
default:
throw new ServerPilotException('Unknown error.', $http_status);
break;
}
}
}
?>
<html>
<body>
<form action="server.php" method="post">
<input type="submit" name="createApp" value="Create APP" />
</form>
</br>
<form action="server.php" method="post">
<input type="submit" name="createDb" value="Create DB" />
</form>
</br>
<form action="server.php" method="post">
<input type="submit" name="createUser" value="Create USER" />
</form>
</body>
</html>
Its giving error in all three functions same. Letme know if someone can help me for come out from this issue, I am trying from last two hours and its not working.
Thanks
You can not access class function directly like this.You need to create class object first and then call the function with object variable.
It's better to save class code in a separate file and include it in the above give file at the top to avoid errors.
E.g:
// $config as array, You need it to set in construct method.check construct method.
$config = [
"id" => ENTER_ID,
"key" => ENTER_KEY,
"decode" => true, //Optional you can leave this ,default is true anyway.
];
$ServerPilot_Obj = New ServerPilot($config);
$ServerPilot_Obj->app_create( $name, $sysuserid, $runtime, $domains = array());
I'm just try to find is there is any TIMEOUT or MAX EXECUTION TIME for execute Symfony2 tasks. Why? Any time I execute the task pdone:sync it stop with this log:
Symfony > pdone:sync
[Symfony\Component\Debug\Exception\ContextErrorException]
Notice: Undefined offset: 2000
pdone:sync
The command terminated with an error status (1)
This is my code which is called from task as a service and second SOQL query returns exactly 6911 items so it should insert 6911 and not stop at 2000, why? what is happening there? Any advice or help or ideas?
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\DependencyInjection\ContainerInterface as Container;
use PDI\PDOneBundle\Entity;
use Doctrine\ORM\EntityManager;
use Symfony\Component\HttpFoundation\RequestStack;
class SyncController extends Controller
{
private $_em;
private $_container;
private $_rs;
public function __construct(Container $container, EntityManager $em, RequestStack $rs)
{
$this->_container = $container;
$this->_em = $em;
$this->_rs = $rs;
}
public function syncVeevaData()
{
$em = $this->_em;
$request = $this->_rs->getCurrentRequest();
$container = $this->_container;
// Will need this in the whole function so lets declare it here
$now = new \DateTime();
$expireTime = clone $now;
$expireTime = $expireTime->modify('+1 week');
// Request veeva token and instance URL
$token_url = $container->getParameter('login_uri')."/services/oauth2/token";
$params = "grant_type=".$container->getParameter('grant_type')
."&client_id=".$container->getParameter('client_id')
."&username=".$container->getParameter('veeva_username')
."&password=".$container->getParameter('veeva_password')
."&client_secret=".$container->getParameter('client_secret')
."&redirect_uri=".urlencode($container->getParameter('redirect_uri'));
$curl = curl_init($token_url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($status != 200) {
$respObj['error'] = "Error: call to token URL $token_url failed with status $status, response $json_response, curl_error ".curl_error(
$curl
).", curl_errno ".curl_errno($curl);
return $respObj;
}
curl_close($curl);
$response = json_decode($json_response, true);
$veevaToken = $respObj['access_token'] = $response['access_token'];
$instanceUrl = $respObj['instance_url'] = $response['instance_url'];
if (!isset($veevaToken) || $veevaToken == "") {
$respObj['error'] = "Error - access token missing from response!";
return $respObj;
}
if (!isset($instanceUrl) || $instanceUrl == "") {
$respObj['error'] = "Error - instance URL missing from response!";
return $respObj;
}
// Request reps and sync against DB
$soqlQuery1 = "SELECT Id,FirstName,LastName,Username,Email,LastModifiedDate FROM User";
$soqlUrl1 = $instanceUrl.'/services/data/v28.0/query/?q='.urlencode($soqlQuery1);
$curl = curl_init($soqlUrl1);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Authorization: OAuth $veevaToken"));
$jsonResponse = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($status != 200) {
$respObj['error'] = "Error: call to token URL $token_url failed with status $status, response $json_response, curl_error ".curl_error(
$curl
).", curl_errno ".curl_errno($curl);
return $respObj;
}
curl_close($curl);
$soqlObj1 = json_decode($jsonResponse, true);
for ($i = 0; $i < $soqlObj1['totalSize']; $i++) {
$entReps = $em->getRepository('PDOneBundle:Representative')->findOneBy(
array(
'veeva_rep_id' => $soqlObj1['records'][$i]['Id'],
)
);
if (!$entReps) {
// if there is no reps, then we add
$newReps = new Entity\Representative();
// we set the values from veeva
$newReps->setVeevaRepId($soqlObj1['records'][$i]['Id']);
$newReps->setEmail($soqlObj1['records'][$i]['Email']);
$newReps->setFirst($soqlObj1['records'][$i]['FirstName']);
$newReps->setLast($soqlObj1['records'][$i]['LastName']);
$newReps->setUsername($soqlObj1['records'][$i]['Username']);
$newReps->setLastLoginAt($now);
$newReps->setLastSyncAt($now);
$newReps->setDisplayName(
$soqlObj1['records'][$i]['FirstName'].' '.$soqlObj1['records'][$i]['LastName']
);
$newReps->setRepType("VEEVA");
$em->persist($newReps);
$em->flush();
// Put new reps into $newRepsArr
$repsArr[$newReps->getId()] = $newReps->getVeevaRepId();
} else {
$lastModifiedDate = new \DateTime(
$soqlObj1['records'][$i]['LastModifiedDate']
);
if ($lastModifiedDate > $entReps->getLastSyncAt()) {
// obtained a reps, we update its data
$entReps->setEmail($soqlObj1['records'][$i]['Email']);
$entReps->setFirst($soqlObj1['records'][$i]['FirstName']);
$entReps->setLast($soqlObj1['records'][$i]['LastName']);
$entReps->setUsername($soqlObj1['records'][$i]['Username']);
$entReps->setLastLoginAt($now);
$entReps->setLastSyncAt($now);
$entReps->setDisplayName(
$soqlObj1['records'][$i]['FirstName'].' '.$soqlObj1['records'][$i]['LastName']
);
$entReps->setRepType("VEEVA");
// Put updated reps into $updRepsArr
$repsArr[$entReps->getId()] = $entReps->getVeevaRepId();
}
}
}
$em->flush();
// Get territories and sync against DB
$soqlQuery2 = "SELECT Id,Name,LastModifiedDate FROM Territory";
$soqlUrl2 = $instanceUrl.'/services/data/v28.0/query/?q='.urlencode($soqlQuery2);
$curl = curl_init($soqlUrl2);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Authorization: OAuth $veevaToken"));
$jsonResponse = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($status != 200) {
$respObj['error'] = "Error: call to token URL $token_url failed with status $status, response $json_response, curl_error ".curl_error(
$curl
).", curl_errno ".curl_errno($curl);
return $respObj;
}
curl_close($curl);
$soqlObj2 = json_decode($jsonResponse, true);
for ($i = 0; $i < $soqlObj2['totalSize']; $i++) {
$entTerritory = $em->getRepository('PDOneBundle:Territory')->findOneBy(
array(
'veeva_territory_id' => $soqlObj2['records'][$i]['Id']
)
);
if (!$entTerritory) {
// if there is no territory, then we add
$newTerritory = new Entity\Territory();
// we set the values from veeva
if ($soqlObj2['records'][$i]['Id'] !== null || $soqlObj2['records'][$i]['Id'] !== "") {
$newTerritory->setVeevaTerritoryId($soqlObj2['records'][$i]['Id']);
$newTerritory->setName($soqlObj2['records'][$i]['Name']);
$em->persist($newTerritory);
$em->flush();
}
$terrArr[] = $newTerritory->getId();
$terrFailArr[] = $soqlObj2['records'][$i]['Name'];
} else {
$lastModifiedDate = new \DateTime(
$soqlObj2['records'][$i]['LastModifiedDate']
);
if ($lastModifiedDate > $entTerritory->getUpdatedAt()) {
// obtained a territory, we update its data
$entTerritory->setName($soqlObj2['records'][0]['Name']);
}
$terrArr[] = $entTerritory->getId();
}
}
$em->flush();
return $respObj;
}
}
I am new to php. The script succeeds if i send manually changing the start and end values each time. But, it fails when trying to send via a while loop and displays this error:
Request Entity Too Large. Error 413
GCMSendMessage:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
include("GCMPushMessage.php");
$new_array= array();
$i = 0; // counter
$mysqli = mysqli_connect("localhost", "root", "xxx", "xxx");
while ($i < n) //n is the (total registration id's)/1000
{
$new_array[] = null;
$start = ($i * 1000);
$end = $start + 1000; //GCM Limit of 1000 users per notification
$queryregid = "SELECT gcm_regid FROM `gcm_users` WHERE id >$start AND id <=$end";
$result_select = $mysqli->query($queryregid);
if ($result_select->num_rows > 0) {
// output data of each row
while ($row = $result_select->fetch_assoc()) {
$new_array[] = $row["gcm_regid"]; // Inside while loop
}
} else {
echo "0 results";
}
$apiKey = "xxx";
$param1 = "XXX";
$param2 = "AAA";
$param3 = '0';
$gcpm = new GCMPushMessage($apiKey);
$gcpm->setDevices($new_array);
$response = $gcpm->send($message, array(
'param1' => $param1,
'param2' => $param2,
'param3' => $param3
));
$i = $i + 1; // counter increment
}
print "Response=$response";
?>
GCMPushMessage.php:
<?php
/*
Class to send push notifications using Google Cloud Messaging for Android
Example usage
-----------------------
$an = new GCMPushMessage($apiKey);
$an->setDevices($devices);
$response = $an->send($message);
-----------------------
$apiKey Your GCM api key
$devices An array or string of registered device tokens
$message The mesasge you want to push out
#author Matt Grundy
Adapted from the code available at:
http://stackoverflow.com/questions/11242743/gcm-with-php-google-cloud-messaging
*/
class GCMPushMessage {
var $url = 'https://android.googleapis.com/gcm/send';
var $serverApiKey = "";
var $devices = array();
/*
Constructor
#param $apiKeyIn the server API key
*/
function GCMPushMessage($apiKeyIn){
$this->serverApiKey = $apiKeyIn;
}
/*
Set the devices to send to
#param $deviceIds array of device tokens to send to
*/
function setDevices($deviceIds){
if(is_array($deviceIds)){
$this->devices = $deviceIds;
} else {
$this->devices = array($deviceIds);
}
}
/*
Send the message to the device
#param $message The message to send
#param $data Array of data to accompany the message
*/
function send($message, $data = false){
if(!is_array($this->devices) || count($this->devices) == 0){
$this->error("No devices set");
}
if(strlen($this->serverApiKey) < 8){
$this->error("Server API Key not set");
}
$fields = array(
'registration_ids' => $this->devices,
'data' => array( "message" => $message ),
);
if(is_array($data)){
foreach ($data as $key => $value) {
$fields['data'][$key] = $value;
}
}
$headers = array(
'Authorization: key=' . $this->serverApiKey,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt( $ch, CURLOPT_URL, $this->url );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
// Avoids problem with https certificate
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false);
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
return $result;
}
function error($msg){
echo "Android send notification failed with error:";
echo "\t" . $msg;
exit(1);
}
}
?>