I have a function on my site that creates a promo code for an affiliate automatically once every 24 hours. If 24 hours have passed since the creation of the promo code, it is deleted old promo from the database, and a new one is generated anew. But now there is a problem with this function, it generates a new promo code every time, regardless of whether 24 hours have passed or not.
My function:
public function autoGroupPromos()
{
$userList = Promo::get();
$userIds = $userList->pluck('user_id');
foreach ($userIds as $id) {
$date = Carbon::now();
$promoCodes = Promocode::query()->where('vk_user_id', '!=', null)->get();
foreach ($promoCodes as $promos) {
// If promo create 24 hours ago
$hours = $promos->created_at->diffInHours($date);
if ($hours >= 24) {
$promos->delete();
}
}
$permitted_chars = '0123456789abcdefghijklmnopqrstuvwxyz';
$code = substr(str_shuffle($permitted_chars), 0, 8);
Promocode::query()->create([
'name' => $code,
'sum' => '0.25',
'activates' => '100',
'vk_user_id' => $id
]);
$promoText = Promocode::where('vk_user_id', $id)->orderBy('created_at', 'desc')->first();
$promoName = $promoText->name;
$message = 'Your new promo: ' . $promoName . ';
$url = 'https://api.vk.com/method/messages.send';
$params = array(
'message' => $message,
'access_token' => 'token',
'v' => '5.81',
'peer_ids' => $id
);
$result = file_get_contents($url, false, stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => http_build_query($params)
)
)));
}
}
That is, if less than 24 hours have passed since the promo was created - it should not be deleted and a new promo code should not be generated. But now unfortunately there is an error somewhere.
What can be the problem?
function autoGroupPromos()
{
// removed for loop to clean outdated promos in single request
// note that this way of deleting rows won't fire model events (if any)
Promocode::whereNotNull('vk_user_id')
->where('created_at', '<=', Carbon::now()->subDay(1))
->delete();
$permitted_chars = '0123456789abcdefghijklmnopqrstuvwxyz';
$userIds = Promo::pluck('user_id');
foreach ($userIds as $id) {
/* in the begining we cleaned all outdated codes, so if user still has
some - no need to create new */
if (Promocode::where('vk_user_id', $id)->exists()){
continue;
}
$code = substr(str_shuffle($permitted_chars), 0, 8);
/* you can immidiately get create model like this -
no need to make another request
$createdPromo = Promocode::create([*/
Promocode::create([
'name' => $code,
'sum' => '0.25',
'activates' => '100',
'vk_user_id' => $id
]);
/* didn't get why you were requesting newly created
promo to get name field if you put there $code value */
$message = `Your new promo: $code`;
$url = 'https://api.vk.com/method/messages.send';
$params = array(
'message' => $message,
'access_token' => 'token',
'v' => '5.81',
'peer_ids' => $id
);
$result = file_get_contents($url, false, stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => http_build_query($params)
)
)));
}
}
upd: here can be a bit cleaner way with hasOneOfMany and skipping each user request to check if promocode exists
// User model
public function promocodes() {
return $this->hasMany(Promocode::class);
}
public function promocode() {
return $this->hasOne(Promocode::class)->latestOfMany();
}
function autoGroupPromos()
{
// note that this way of deleting rows won't fire model events (if any)
Promocode::whereNotNull('vk_user_id')
->where('created_at', '<=', Carbon::now()->subDay(1))
->delete();
$permitted_chars = '0123456789abcdefghijklmnopqrstuvwxyz';
// taking users without promo after cleanup
User::whereDoesntHave('promo')->get()
->each(function (User $user) use ($permitted_chars) {
$code = substr(str_shuffle($permitted_chars), 0, 8);
// pay attention on relation name - using hasMany
$user->promocodes()->save(
new Promocode([
'name' => $code,
'sum' => '0.25',
'activates' => '100',
])
);
$message = `Your new promo: $code`;
$url = 'https://api.vk.com/method/messages.send';
$params = array(
'message' => $message,
'access_token' => 'token',
'v' => '5.81',
'peer_ids' => $id
);
$result = file_get_contents($url, false, stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => http_build_query($params)
)
)));
});
}
link Inserting & Updating Related Models
Related
The situation:
I build an authentication service that uses Basic Authentication to check if the user exists on an external database and fetches some data. The users in question only exist on the external database.
The problem:
Typo3 needs to have an user entry in the fe_user table to login the user.
So whenever this entry does not exist, the user cannot login.
What I want to do:
Create the user in the authentication service to avoid using a sql dump from the external database and ensure that synchronisation is possible.
The relevant code:
public function authUser(array $user) {
$a_user = $this->login['uname'];
$a_pwd = $this->login['uident_text'];
$url = 'https://soliday.fluchtpunkt.at/api/queryMediaItems';
$data = json_decode('{"language":"de-at"}');
$basicAuth = base64_encode("$a_user:$a_pwd");
// use key 'http' even if you send the request to https://...
$options = array (
'http' => array (
'header' => array(
"Content-Type: application/json",
"Accept: application/json",
"Authorization: Basic {$basicAuth}"
),
'method' => 'POST',
'content' => '{"language":"de-at"}'
)
);
$context = stream_context_create ( $options );
$result = file_get_contents ($url, false, $context);
$response = gzdecode($result);
$checkUser = $this->fetchUserRecord ( $this->login ['uname'] );
if (!is_array($checkUser)&& $result!== FALSE) {
$this->createUser();
}
// failure
if ($result === FALSE) {
return static::STATUS_AUTHENTICATION_FAILURE_BREAK;
}
$this->processData($response);
// success
return static::STATUS_AUTHENTICATION_SUCCESS_BREAK;
}
public function createUser() {
$username = $this->login ['uname'];
$password = $this->login ['uident_text'];
$record = $GLOBALS ['TYPO3_DB']->exec_SELECTgetSingleRow ( '*', 'fe_users', "username = '" . $username . "' AND disable = 0 AND deleted = 0" );
if (! $record) {
// user has no DB record (yet), create one using defaults registered in extension config
// password is not important, username is set to the user's input
$record = array (
'username' => $username,
'password' => $password,
'name' => '',
'email' => '',
'disable' => '0',
'deleted' => '0',
'pid' => $this->config ['storagePid'],
'usergroup' => $this->config ['addUsersToGroups'],
'tstamp' => time ()
);
if (t3lib_extMgm::isLoaded ( 'extbase' )) {
$record ['tx_extbase_type'] = $this->config ['recordType'];
}
$GLOBALS ['TYPO3_DB']->exec_INSERTquery ( 'fe_users', $record );
$uid = $GLOBALS ['TYPO3_DB']->sql_insert_id ();
$record = $GLOBALS ['TYPO3_DB']->exec_SELECTgetSingleRow ( '*', 'fe_users', 'uid = ' . intval ( $uid ) );
}
$_SESSION [$this->sessionKey] ['user'] ['fe'] = $record;
}
the ext_localconf.php file:
<?php
if (!defined('TYPO3_MODE')) {
die ('Access denied.');
}
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addService(
$_EXTKEY,
'auth' /* sv type */,
'AuthService' /* sv key */,
array(
'title' => 'GET Authentication service',
'description' => 'Authenticates users with GET request.',
'subtype' => 'getUserFE, authUserFE',
'available' => true,
'priority' => 90,
'quality' => 90,
'os' => '',
'exec' => '',
'className' => Plaspack\professionalZoneLogin\Service\AuthService::class,
)
);
You should extend AuthenticationService with your own code, way of doing that is described here https://docs.typo3.org/typo3cms/CoreApiReference/ApiOverview/Xclasses/Index.html
Not sure if it's related, but t3lib_extMgm should be \TYPO3\CMS\Core\Utility\ExtensionManagementUtility unless you're using TYPO3 6.
You can also see if you get any SQL errors by calling $GLOBALS['TYPO3_DB']->sql_error().
In my wp project, I am using Assently for e-signature implementation. Though I have an account and created a pdf form file to be filled by the user I just am not able to proceed a bit. I am finding documentation not clear.
Also, I am not clear about what needs to be done so that the user will be shown form to process the transaction.
So, any help/suggestions to proceed forward is appreciated.
I have tried the following based on assently-laravel. But it's asking me to login. What is an error here?
Code:
define('ASSENTLY_DEBUG', true);
define('ASSENTLY_KEY', 'key');
define('ASSENTLY_SECRET', 'secret-generated');
include_once('assently/Assently.php');
$assently = new Assently();
$assently->authenticate(ASSENTLY_KEY, ASSENTLY_SECRET);
$url = 'https://test.assently.com/api/v2/createcasefromtemplate';
$default = array(
'Id' => '5a0e0869-' . rand(1111, 9999) . '-4b79-' . rand(1111, 9999) . '-466ea5cca5ce'
);
$data = array(
'auth' => $assently->auth(),
'templateId' => '0e004e2b-b192-4ce2-8f47-d7a4576d7df6',
'newCaseId' => '5a0e0869-' . rand(1111, 9999) . '-4b79-' . rand(1111, 9999) . '-466ea5cca5ce',
'agentUsername' => ''
);
$data = array(
'json' => $data
);
$options = array(
'http' => array(
'header' => "Content-type: application/json; charset=utf-8\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
echo '<pre>';
print_r($result);
die;
create this class inside assently folder
use Assently\AssentlyCase;
use Exception;
class CustomAssentlyCase extends AssentlyCase
{
public function createFromTemplate($data)
{
$default = [
'newCaseId' => '5a0e0869-'.rand(1111, 9999).'-4b79-'.rand(1111, 9999).'-466ea5cca5ce'
];
$json = array_merge($default, $data);
try{
$response = $this->client->post($this->url('createcasefromtemplate'), [
'auth' => $this->assently->auth(),
'json' => $json
]);
}catch(Exception $e){
print_r($e->getMessage());
}
return $response;
}
}
Use
define('ASSENTLY_DEBUG', true);
define('ASSENTLY_KEY', 'key');
define('ASSENTLY_SECRET', 'secret-generated');
include_once('assently/Assently.php');
include_once('assently/CustomAssentlyCase.php');
$assently = new Assently();
$assently->authenticate(ASSENTLY_KEY, ASSENTLY_SECRET);
$data = array(
'templateId' => '0e004e2b-b192-4ce2-8f47-d7a4576d7df6',
'newCaseId' => '5a0e0869-'.rand(1111, 9999).'-4b79-'.rand(1111, 9999).'-466ea5cca5ce',
'agentUsername' => 'agentUsername' // PUT your agent username here it is required
);
$customAssentlyCase = new CustomAssentlyCase($assently);
$result = $customAssentlyCase->createFromTemplate($data);
print_r($result);
Try this, though not tested but should work. Good luck.
Where did I make a mistake? My PHP-script:
<?php
// Set username and password
$lgname = "someUsername";
$lgpassword = "somePassword";
// First login to receive 1) token, 2) sessionid and 3) cookieprefix
$parameters = array('action' => 'login', 'lgname' => "$lgname", 'lgpassword' => "$lgpassword", 'format' => 'json');
options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($parameters)
),
);
$context = stream_context_create($options);
$result = file_get_contents("http://en.wikipedia.org/w/api.php", false, $context);
// Echo out the answer from MediaWiki-API
echo "$result";
// Put the needed parts of the answer into variables and echo them out
$array = json_decode($result,true);
$token = $array["login"]["token"];
$sessionid = $array["login"]["sessionid"];
$cookieprefix = $array["login"]["cookieprefix"];
echo "</BR>token: $token, sessionid: $sessionid, cookieprefix: $cookieprefix</BR>";
// Second login to 1) post token and 2) send sessionID within the header
$parameters = array('action' => 'login', 'lgname' => "$lgname", 'lgpassword' => "$lgpassword", 'lgtoken' => "$token", 'format' => 'json');
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n" .
"Cookie: " . $cookieprefix . "_session = $sessionid\r\n",
'method' => 'POST',
'content' => http_build_query($parameters)
),
);
$context = stream_context_create($options);
$result = file_get_contents("http://en.wikipedia.org/w/api.php", false, $context);
// Echo out result
echo "$result";
?>
What I get as an answer to my second POST-request is (exactly the same as to my first POST-request) that I need a token (even though I posted the token and even the sessionID in my second POST-request):
{"login": {
"result":"NeedToken",
"token":"82b3f2e1f1aa702ca6ceae473bb16bde",
"cookieprefix":"dewiki",
"sessionid":"531143bd7425722bf1be88e520dea6d5"}
}
The mistake is in using file_get_contents() in the first place. Use a PHP library for the MediaWiki web API, instead.
If you really want to do things yourself, ask a token from meta=tokens.
I'm trying to setup recurring payments in paypal with PHP. But the problem that I'm having is that I don't know if I'm doing the right thing. I have this class which makes the request to the Paypal API:
<?php
class Paypal {
protected $_errors = array();
protected $_credentials = array(
'USER' => 'my-user-id',
'PWD' => 'my-pass',
'SIGNATURE' => 'my-signature',
);
protected $_endPoint = 'https://api-3t.sandbox.paypal.com/nvp';
protected $_version = '74.0';
public function request($method,$params = array()) {
$this -> _errors = array();
if( empty($method) ) {
$this -> _errors = array('API method is missing');
return false;
}
$requestParams = array(
'METHOD' => $method,
'VERSION' => $this -> _version
) + $this -> _credentials;
$request = http_build_query($requestParams + $params);
$http_header = array(
'X-PAYPAL-SECURITY-USERID' => 'my-user-id',
'X-PAYPAL-SECURITY-PASSWORD' => 'my-pass',
'X-PAYPAL-SECURITY-SIGNATURE' => 'my-signature',
'X-PAYPAL-REQUEST-DATA-FORMAT' => 'JSON',
'X-PAYPAL-RESPONSE-DATA-FORMAT' => 'JSON'
);
$curlOptions = array (
CURLOPT_HTTPHEADER => $http_header,
CURLOPT_URL => $this -> _endPoint,
CURLOPT_VERBOSE => 1,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $request
);
$ch = curl_init();
curl_setopt_array($ch,$curlOptions);
$response = curl_exec($ch);
if (curl_errno($ch)) {
$this -> _errors = curl_error($ch);
curl_close($ch);
return false;
} else {
curl_close($ch);
$responseArray = array();
parse_str($response,$responseArray);
return $responseArray;
}
}
}
?>
Then I'm making the initial request like this:
session_start();
require_once('Paypal.php');
$paypal = new Paypal();
$amount = 1;
$requestParams = array(
'RETURNURL' => 'http://localhost/tester/paypal/new_test/test_done.php',
'CANCELURL' => 'http://localhost/tester/paypal/new_test/test_cancel.php',
'NOSHIPPING' => '1',
'ALLOWNOTE' => '1',
'L_BILLINGTYPE0' => 'RecurringPayments',
'L_BILLINGAGREEMENTDESCRIPTION0' => 'site donation'
);
$orderParams = array(
'PAYMENTREQUEST_0_AMT' => '1',
'PAYMENTREQUEST_0_CURRENCYCODE' => 'USD',
'PAYMENTREQUEST_0_ITEMAMT' => $amount
);
$item = array(
'L_PAYMENTREQUEST_0_NAME0' => 'site donation',
'L_PAYMENTREQUEST_0_DESC0' => 'site donation',
'L_PAYMENTREQUEST_0_AMT0' => $amount,
'L_PAYMENTREQUEST_0_QTY0' => '1'
);
$response = $paypal->request('SetExpressCheckout', $requestParams + $orderParams + $item);
$sandbox_location = 'https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token=';
if(is_array($response) && $response['ACK'] == 'Success'){
$token = $response['TOKEN'];
$_SESSION['token'] = $token;
header('Location: ' . $sandbox_location . urlencode($token));
}
?>
As you can see I'm using the SetExpressCheckout API method to get the token that I need and store it in a session so that I can use it later with the request for CreateRecurringPaymentsProfile.
I'm currently redirected to a page similar to this:
Once the user is done logging in with paypal and confirming the amount it redirects to the success page that I've specified which contains this code:
session_start();
require_once('Paypal.php');
$amount = 1;
$paypal = new Paypal();
$token_param = array('TOKEN' => $_SESSION['token']);
$current_date = date('Y-m-d');
$recurring_payment_params = array(
'PROFILESTARTDATE' => gmdate('Y-m-d H:i:s', strtotime($current_date . ' + 1 months')),
'DESC' => 'site donation',
'BILLINGPERIOD' => 'Month',
'BILLINGFREQUENCY' => '1',
'TOTALBILLINGCYCLES' => '0',
'AMT' => $amount
);
$recurringpayment_response = $paypal->request('CreateRecurringPaymentsProfile', $recurring_payment_params + $token_param);
This works, I've verified in the sandbox account that the recurring payment profile was created and that the next billing due is next month. But the problem is that its not really visible in the paypal interface (the screenshot earlier) that they're paying for a subscription. Perhaps I'm getting the redirect url wrong? (https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token=) or do I have to add additional arguments to the SetExpressCheckout method? Please help.
You're only showing the login screen. After you login you'll see information about the subscription and the button will see "Agree and Pay" or "Agree and Continue" (depending on your useraction value in the return URL) instead of just "Pay" or "Continue".
Im creating a widget for a Wordpress site and i am trying to get the twitter following count, I can get the followers count which is taken from http://www.wpbeginner.com/wp-tutorials/displaying-the-total-number-of-twitter-followers-as-text-on-wordpress/. Any help would be great.
thanks Pierce
Current code in functions.php:
// Twitter
function getTwitterFollowers($screenName = 'hellowWorld')
{
// some variables
$consumerKey = 'hidden';
$consumerSecret = 'hidden';
$token = get_option('cfTwitterToken');
// get follower count from cache
$numberOfFollowers = get_transient('cfTwitterFollowers');
// cache version does not exist or expired
if (false === $numberOfFollowers) {
// getting new auth bearer only if we don't have one
if(!$token) {
// preparing credentials
$credentials = $consumerKey . ':' . $consumerSecret;
$toSend = base64_encode($credentials);
// http post arguments
$args = array(
'method' => 'POST',
'httpversion' => '1.1',
'blocking' => true,
'headers' => array(
'Authorization' => 'Basic ' . $toSend,
'Content-Type' => 'application/x-www-form-urlencoded;charset=UTF-8'
),
'body' => array( 'grant_type' => 'client_credentials' )
);
add_filter('https_ssl_verify', '__return_false');
$response = wp_remote_post('https://api.twitter.com/oauth2/token', $args);
$keys = json_decode(wp_remote_retrieve_body($response));
if($keys) {
// saving token to wp_options table
update_option('cfTwitterToken', $keys->access_token);
$token = $keys->access_token;
}
}
// we have bearer token wether we obtained it from API or from options
$args = array(
'httpversion' => '1.1',
'blocking' => true,
'headers' => array(
'Authorization' => "Bearer $token"
)
);
add_filter('https_ssl_verify', '__return_false');
$api_url = "https://api.twitter.com/1.1/users/show.json?screen_name=$screenName";
$response = wp_remote_get($api_url, $args);
if (!is_wp_error($response)) {
$followers = json_decode(wp_remote_retrieve_body($response));
$numberOfFollowers = $followers->followers_count;
} else {
// get old value and break
$numberOfFollowers = get_option('cfNumberOfFollowers');
// uncomment below to debug
//die($response->get_error_message());
}
// cache for an hour
set_transient('cfTwitterFollowers', $numberOfFollowers, 1*60*60);
update_option('cfNumberOfFollowers', $numberOfFollowers);
}
return $numberOfFollowers;
}
It was pretty simple if I just read the documentation anyway...
Instead of followers_count i replaced it with friends_count as outlined in the API 1.1 documentation. :)