bbPress RTX integration - php

Im currently working on a RTX/Janrain integration with bbPress, but im stuck with a SQL query which doesnt give me any results even though I've been trying with wildcards and an e-mail adress i know is registered.
Sign In
$rpxApiKey = 'xxxxx';
if(isset($_POST['token'])) { /*
STEP 1: Extract token POST parameter
*/ $token = $_POST['token'];
/* STEP 2: Use the token to make the
auth_info API call */ $post_data =
array('token' => $_POST['token'],
'apiKey' => $rpxApiKey,
'format' => 'json');
$curl = curl_init();
curl_setopt($curl,
CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_URL,
'https://rpxnow.com/api/v2/auth_info');
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($curl, CURLOPT_HEADER,
false); curl_setopt($curl,
CURLOPT_SSL_VERIFYPEER, false);
$raw_json = curl_exec($curl);
curl_close($curl);
/* STEP 3: Parse the JSON auth_info
response */ $auth_info =
json_decode($raw_json, true);
if ($auth_info['stat'] == 'ok') {
/* STEP 3 Continued: Extract the 'identifier' from the response */
$profile = $auth_info['profile'];
$identifier = $profile['identifier'];
$profile['identifier'];
if (isset($profile['photo'])) {
$photo_url = $profile['photo'];
}
if (isset($profile['displayName'])) {
$name = $profile['displayName'];
}
if (isset($profile['email'])) {
$email = $profile['email'];
}
/* Step 5, Check if user existis in database, if so login, if
not create new user then login*/
global $bbdb; $querystr = "
SELECT * FROM $bbdb->bb_users
WHERE user_email = $email LIMIT
1"; $rtx_user_id =
$bbdb->get_results($querystr, OBJECT);
print_r($rtx_user_id);
if ($rtx_user_id) {
echo "Great success";
wp_set_auth_cookie( (int) $rtx_user_id, 0 ); // 0 = don't
remember, short login, todo: use form
value do_action('bb_user_login',
(int) $rtx_user_id ); } if
(!$rtx_user_id) { echo "Not great
success";}
/* STEP 6: Use the identifier as the unique key to sign the user into
your system.
This will depend on your website implementation, and you should
add your own
code here.
*/
/* an error occurred */ }
else { // gracefully handle the
error. Hook this into your native
error handling system. echo 'An
error occured: ' .
$auth_info['err']['msg']; } } } ?>
The problem accrues in Step 5 which is to check if the user exists.
Thanks in advance,
Marten

As we talked on twitter, the query line should be
$querystr = "SELECT * FROM $bbdb->users WHERE user_email = '$email' LIMIT 1";

Related

CURL Post Request to API Looping Through Database

I've been trying to select values (students data) from mysql database table and looping through database to send to an API using PHP CURL Post request but it's not working.
This is the API body:
{
"students":[
{
"admissionNumber": "2010",
"class":"js one"
},
{
"admissionNumber": "2020",
"class":"ss one"
}
],
"appDomain":"www.schooldomain.com"
}
Parameters I want to send are "admissionNumber" and "class" parameters while "appDomain" is same for all. Here's my code:
if(isset($_POST['submit'])){
$body = "success";
$info = "yes";
class SendDATA
{
private $url = 'https://url-of-the-endpoint';
private $username = '';
private $appDomain = 'http://schooldomain.com/';
// public function to commit the send
public function send($admNo,$class)
{
$url_array= array('admissionNumber'=>$admNo,'class'=>$class,'appDomain'=>$this-> appDomain);
$url_string = $data = http_build_query($url_array);
// using the curl library to make the request
$curlHandle = curl_init();
curl_setopt($curlHandle, CURLOPT_URL, $this->url);
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $url_string);
curl_setopt($curlHandle, CURLOPT_POST, 1);
$responseBody = curl_exec($curlHandle);
$responseInfo = curl_getinfo($curlHandle);
curl_close($curlHandle);
return $this->handleResponse($responseBody,$responseInfo);
}
private function handleResponse($body,$info)
{
if ($info['http_code']==200){ // successful submission
$xml_obj = simplexml_load_string($body);
// extract
return true;
}
else{
// error handling
return false;
}
}
}
$sms = new SendDATA();
$result = mysqli_query( $mysqli, "SELECT * FROM school_kids");
while ($row = mysqli_fetch_array($result)) {
$admNo = $row['admNo'];
$class = $row['class'];
$sms->send($admNo,$class,"header");
echo $admNo. " ".$class;
}
}
The question is rather unclear; when you say "this is the API body", I presume this JSON fragment is what the REST API at https://url-of-the-endpoint expects. If so, you are building your request body wrong. http_build_query creates an URL-encoded form data block (like key=value&anotherKey=another_value), not a JSON. For a JSON, here's what you want:
$data = array('students' => array
(
array('admissionNumber' => $admNo, 'class' => $class)
),
'appDomain':$this->appDomain
);
$url_string = $data = json_encode($data);
Also, you probably want to remove the HTTP headers from the response:
curl_setopt($curlHandle, CURLOPT_HEADER, false);

How to update segments and groups of an existing subscriber in MailChimp API 3

Iv'e written a method to subscribe users to MailChimp. Whats 'special' about it is that it automatically subscribe the users to groups within the list, and segments within the list, based on the users' cart items, wishlist items, and the item and / or category that he has subscribed from.
The integration with MailChimp is straight forward - I get the data > send curl > get response > handle response.
I'm looking for a way to constant update the users' groups and segments, based on their actions in my store.
Now, the only accepted statuses MailChimp can get are 'subscribed', 'pending', and 'clean'. All of them aren't updating, only inserting new subscribers. If the email is already subscribed, nothing is being updated, not even data that is different than what the subscriber has in its profile in my MailChimp lists.
Here's my code for reference:
protected static function subscribeToMailchimp($email, $fullname)
{
$params = EkerbaseJoomla::getPluginParams('system', 'ekerbaseusers');
$interests = self::getUserInterestsObject();
$apikey = $params->mailChimpApiKey;
$listId = $params->mailChimpListId;
$interestCategoryId = $params->mailChimpInterestCategoryId;
$auth = base64_encode( 'user:' . $apikey );
$apiUrl = 'https://'.substr($params->mailChimpApiKey, -3).'.api.mailchimp.com/3.0/lists/'.$listId;
$possibleGroups = json_decode(file_get_contents($apiUrl . '/interest-categories/' . $interestCategoryId . '/interests?apikey=' . $apikey))->interests;
$segments = json_decode(file_get_contents($apiUrl . '/segments?apikey=' . $apikey))->segments;
$data = [
'apikey' => $apikey,
'email_address' => $email,
'status' => 'subscribed',
'merge_fields' =>
[
'FNAME' => $fullname
]
];
if( ! empty($interests->categories) ) {
$data['interests'] = [];
foreach( $possibleGroups as $group ) {
if( in_array($group->name, $interests->categories) ) {
$data['interests'][$group->id] = true;
}
}
}
if( ! empty($interests->items) ) {
$data['segments'] = [];
foreach( $segments as $segment ) {
if( in_array($segment->name, $interests->items) ) {
$data['segments'][$segment->id] = true;
}
}
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl . '/members/');
curl_setopt($ch, CURLOPT_HTTPHEADER,
[
'Content-Type: application/json',
'Authorization: Basic '.$auth
]
);
curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/3.0');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$result = curl_exec($ch);
$response = json_decode($result);
switch( $response->status ) {
case 'subscribed':
$responseMessage = JText::_('EKERBASE_SUCCESS_NEWSLETTER');
$responseStatus = 'success';
$responseResult = 'mailchimp subscribing succeeded';
break;
default:
$responseStatus = 'error';
$responseMessage = $response->title;
$responseResult = 'mailchimp subscribing failed';
if( $response->title === 'Member Exists' ) {
$responseMessage = JText::_('EKERBASE_NEWSLETTER_ALREADY_SUBSCRIBER');
}
break;
}
return EkerbaseAjax::buildJsonResponse($responseMessage, $responseStatus, $responseResult);
}
If your integration is adding entirely new subscriber as expected, and the issue appears isolated to cases where the method is updating an existing sub's record, the issue may pertain to the HTTP method, and/or the api endpoint.
As v3 of MailChimp's API only allows subscribers to be initialized when using the POST method(which looks like it may be hard coded into cURL here), and is likely why entirely new subscribers are being added without issue.
This said, when wanting to add or update new subscribers using PUT would be recommended, and is specified in their docs.
Add or update a list member
more on http methods and their API
Additionally, along with this alternate method usage, to ensure existing subscribers are updated, you'll also need to append the MD5 hash of the lower case version of their email to to the endpoint. This only needs to be done for existing subs.
e.g. /members/{lowercase_email_MD5_hash}
Which should be provided in the response if you're first checking with MailChimp whether or not a subscriber exist, if you'd like to recycle that.

Gotomeeting php api(oauth) implementation

I am trying to create a php gotomeating api implementation. I successfully got the access_token but for any other requests I get error responses. This is my code:
<?php
session_start();
$key = '#';
$secret = '#';
$domain = $_SERVER['HTTP_HOST'];
$base = "/oauth/index.php";
$base_url = urlencode("http://$domain$base");
$OAuth_url = "https://api.citrixonline.com/oauth/authorize?client_id=$key&redirect_uri=$base_url";
$OAuth_exchange_keys_url = "http://api.citrixonline.com/oauth/access_token?grant_type=authorization_code&code={responseKey}&client_id=$key";
if($_SESSION['access_token']) CreateForm();else
if($_GET['send']) OAuth_Authentication($OAuth_url);
elseif($_GET['code']) OAuth_Exchanging_Response_Key($_GET['code'],$OAuth_exchange_keys_url);
function OAuth_Authentication ($url){
$_SESSION['access_token'] = false;
header("Location: $url");
}
function CreateForm(){
$data = getURL('https://api.citrixonline.com/G2M/rest/meetings?oauth_token='.$_SESSION['access_token'],false);
}
function OAuth_Exchanging_Response_Key($code,$url){
if($_SESSION['access_token']){
CreateForm();
return true;
}
$data = getURL(str_replace('{responseKey}',$code,$url));
if(IsJsonString($data)){
$data = json_decode($data);
$_SESSION['access_token'] = $data->access_token;
CreateForm();
}else{
echo 'error';
}
}
/*
* Helper functions
*/
/*
* checks if a string is json
*/
function IsJsonString($str){
try{
$jObject = json_decode($str);
}catch(Exception $e){
return false;
}
return (is_object($jObject)) ? true : false;
}
/*
* CURL function to get url
*/
function getURL($url,$auth_token = false,$data=false){
// Initialize session and set URL.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if($auth_token){
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: OAuth oauth_token='.$auth_token));
}
if($data){
curl_setopt($ch, CURLOPT_POST,true);
$d = json_encode('{ "subject":"test", "starttime":"2011-12-01T09:00:00Z", "endtime":"2011-12-01T10:00:00Z", "passwordrequired":false, "conferencecallinfo":"test", "timezonekey":"", "meetingtype":"Scheduled" }');
echo implode('&', array_map('urlify',array_keys($data),$data));
echo ';';
curl_setopt($ch, CURLOPT_POSTFIELDS,
implode('&', array_map('urlify',array_keys($data),$data))
);
}
// Get the response and close the channel.
$response = curl_exec($ch);
/*
* if redirect, redirect
*/
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($code == 301 || $code == 302) {
preg_match('/<a href="(.*?)">/', $response, $matches);
$newurl = str_replace('&','&',trim(array_pop($matches)));
$response = getURL($newurl);
} else {
$code = 0;
}
curl_close($ch);
return $response;
}
function urlify($key, $val) {
return urlencode($key).'='.urlencode($val);
}
to start the connect process you need to make a request to the php file fith send=1. I tryed diffrent atempts to get the list of meetings but could not get a good response.
Did anybody had prev problems with this or know of a solution for this?
Edit:
This is not a curl error, the server responds with error messages, in the forums from citrix they say it should work, no further details on why it dosen't work, if I have a problem with the way I implemented the oauth or the request code. The most comon error I get is: "error code:31305" that is not documented on the forum.
[I also posted this on the Citrix Developer Forums, but for completeness will mention it here as well.]
We are still finalizing the documentation for these interfaces and some parameters which are written as optional are actually required.
Compared to your example above, changes needed are:
set timezonekey to 67 (Pacific time)
set passwordrequired to false
set conferencecallinfo to Hybrid (meaning: both PSTN and VOIP will be provided)
Taking those changes into account, your sample data would look more like the following:
{"subject":"test meeting", "starttime":"2012-02-01T08:00:00",
"endtime":"2012-02-01T09:00:00", "timezonekey":"67",
"meetingtype":"Scheduled", "passwordrequired":"false",
"conferencecallinfo":"Hybrid"}
You can also check out a working PHP sample app I created: http://pastebin.com/zE77qzAz

How to use Constant Contact API?

I want to use API of the constant contact and want to insert user email using PHP while user register to the site.
please reply if any help.
Thanks in advance.
// fill in your Constant Contact login and API key
$ccuser = 'USERNAME_HERE';
$ccpass = 'PASS_HERE';
$cckey = 'APIKEY_HERE';
// fill in these values
$firstName = "";
$lastName = "";
$emailAddr = "";
$zip = "";
// represents the contact list identification number(s)
$contactListId = INTEGER_OR_ARRAY_OF_INTEGERS_HERE;
$contactListId = (!is_array($contactListId)) ? array($contactListId) : $contactListId;
$post = new SimpleXMLElement('<entry></entry>');
$post->addAttribute('xmlns', 'http://www.w3.org/2005/Atom');
$title = $post->addChild('title', "");
$title->addAttribute('type', 'text');
$post->addChild('updated', date('c'));
$post->addChild('author', "");
$post->addChild('id', 'data:,none');
$summary = $post->addChild('summary', 'Contact');
$summary->addAttribute('type', 'text');
$content = $post->addChild('content');
$content->addAttribute('type', 'application/vnd.ctct+xml');
$contact = $content->addChild('Contact');
$contact->addAttribute('xmlns', 'http://ws.constantcontact.com/ns/1.0/');
$contact->addChild('EmailAddress', $emailAddr);
$contact->addChild('FirstName', $firstName);
$contact->addChild('LastName', $lastName);
$contact->addChild('PostalCode', $zip);
$contact->addChild('OptInSource', 'ACTION_BY_CUSTOMER');
$contactlists = $contact->addChild('ContactLists');
// loop through each of the defined contact lists
foreach($contactListId AS $listId) {
$contactlist = $contactlists->addChild('ContactList');
$contactlist->addAttribute('id', 'http://api.constantcontact.com/ws/customers/' . $ccuser . '/lists/' . $listId);
}
$posturl = "https://api.constantcontact.com/ws/customers/{$ccuser}/contacts";
$authstr = $cckey . '%' . $ccuser . ':' . $ccpass;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $posturl);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, $authstr);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post->asXML());
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:application/atom+xml"));
curl_setopt($ch, CURLOPT_HEADER, false); // Do not return headers
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0); // If you set this to 0, it will take you to a page with the http response
$response = curl_exec($ch);
curl_close($ch);
// returns true on success, false on error
return (!is_numeric($response));
The developers of ConstantContact have launched PHP library to handle such kind of tasks.
Following version is for older PHP versions (5.2 or lesser). Download code from here: https://github.com/constantcontact/ctct_php_library
Following is an example to add a subscriber's email in your constant contact lists.
After downloading the above library, use following code to add an email in Constant Contact list(s).
session_start();
include_once('ConstantContact.php'); // Set path accordingly
$username = 'YOUR_CONSTANT_CONTACT_USER_NAME';
$apiKey = 'YOUR_API_KEY';
$password = 'YOUR_CONSTANT_CONTACT_PASSWORD';
$ConstantContact = new Constantcontact("basic", $apiKey, $username, $password);
$emailAddress = "new_email#test.com";
// Search for our new Email address
$search = $ConstantContact->searchContactsByEmail($emailAddress);
// If the search did not return a contact object
if($search == false){
$Contact = new Contact();
$Contact->emailAddress = $emailAddress;
//$Contact->firstName = $firstName;
//$Contact->lastName = $lastName;
// represents the contact list identification link(s)
$contactList = LINK_OR_ARRAY_OF_LINKS_HERE;
// For example,
// "http://api.constantcontact.com/ws/customers/USER_NAME/lists/14";
$Contact->lists = (!is_array($contactList)) ? array($contactList) : $contactList;
$NewContact = $ConstantContact->addContact($Contact);
if($NewContact){
echo "Contact Added. This is your newly created contact's information<br /><pre>";
print_r($NewContact);
echo "</pre>";
}
} else {
echo "Contact already exist.";
}
Note: The latest version can be found on the GitHub links given in following URL: http://developer.constantcontact.com/libraries/sample-code.html
But I am not sure if the above example code works with the newer library or not.
If you can't get this to work, you might have to add this curl_setopt:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

How to setup ios platform through code with apple push notification p12 certificate file?

I want to create an app with ios platform set up from the .p12 file. How do I do that?
This is the method for creating app:
class AppHandler
{
public $USER_AUTH_KEY = 'Insert your key here';
public function create($name, $apns_p12 = null, $apns_p12_password = null, $gcm_key = null, $android_gcm_sender_id = null)
{
$fields = array(
'name' => $name,
'apns_p12' => $apns_p12,
'apns_p12_password' => $apns_p12_password,
'gcm_key' => $gcm_key,
'android_gcm_sender_id' => $android_gcm_sender_id
);
$fields = json_encode($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/apps");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8',
"Authorization: Basic " . $this->USER_AUTH_KEY));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
try {
$response = curl_exec($ch);
if (!$response) {
throw new Exception("App wasn't created");
}
} catch (Exception $e) {
echo 'Error: ', $e->getMessage(), "\n";
} finally {
curl_close($ch);
}
$response = json_decode($response, true);
$return = array(
'id' => $response['id'],
'basic_auth_key' => $response['basic_auth_key']
);
return $return;
}
...
And this is the method with 2 ways of getting the insides of .p12 file:
public function getP12($pkcs12, $password = NULL): string
{
/*
// Way 1:
$pkcs12 = file_get_contents($pkcs12);
$encoded = base64_encode($pkcs12);
return $encoded;
*/
// Way 2:
$cert_store = file_get_contents($pkcs12);
if (!$cert_store) {
echo "Error: can't read file.\n";
exit;
}
$pkcs12Read = openssl_pkcs12_read($cert_store, $cert_info, $password);
if ($pkcs12Read) {
$result = base64_encode($cert_info['cert']);
return $result;
} else {
echo "Error: can't read cert.\n";
exit;
}
}
According to onesignal's doc I have to send apns_p12 as my apple push notification p12 certificate file, converted to a string and Base64 encoded.
And I do that this way:
$obj = new AppHandler();
$response = $obj->create('TestName', $obj->getP12('cert.p12', 'password'), 'password')
It creates an app with given name, however, the platform is not set up.
What do you mean by "the platform is not set up"? What error are you getting and where?
By the way, I finally gave up trying code the intricacies of APNS programming and instead went with AWS' Simple Notification Service: https://aws.amazon.com/sns. It handles both Apple and Google notifications by using the API to set up topics and subscribers, plus you can send up to 1 million notifications per month free.
Ok, I got it. I simply needed to add apns_env parameter:
$fields = array(
'name' => $name,
'apns_env' => $apns_env,
'apns_p12' => $apns_p12,
'apns_p12_password' => $apns_p12_password,
'gcm_key' => $gcm_key,
'android_gcm_sender_id' => $android_gcm_sender_id
);
And I should've taken insides of the file and converted them to a string and Base64 encoded like that:
public function getP12($pkcs12): string
{
$apns_12 = base64_encode(file_get_contents($pkcs12));
return $apns_12;
}

Categories