why coinbase callback url not working? - php

i have the below code for button creation.
public function createButton($name, $price, $currency, $custom=null, $options=array(),$callback)
{
// $callback=$this->generateReceiveAddress("http://www.tgigo.com");
// print_r($callback);exit;
$params = array(
"name" => $name,
"price_string" => $price,
"price_currency_iso" => $currency,
"callback_url"=>"http://www.tgigo.com"
);
if($custom !== null) {
$params['custom'] = $custom;
}
foreach($options as $option => $value) {
$params[$option] = $value;
}
return $this->createButtonWithOptions($params);
}
public function createButtonWithOptions($options=array())
{
$response = $this->post("buttons", array( "button" => $options ));
if(!$response->success) {
return $response;
}
$returnValue = new stdClass();
$returnValue->button = $response->button;
$returnValue->embedHtml = "<div class=\"coinbase-button\" data-code=\"" . $response->button->code . "\"></div><script src=\"https://coinbase.com/assets/button.js\" type=\"text/javascript\"></script>";
$returnValue->success = true;
return $returnValue;
}
and i have the below response for above code.
{"success":true,"button":{"code":"675cda22e31b314db557f0538f8ad27e","type":"buy_now","style":"buy_now_large","text":"Pay With Bitcoin","name":"Your Order #1234","description":"1 widget at $100","custom":"my custom tracking code for this order","callback_url":"http://www.tgigo.com","price":{"cents":100000,"currency_iso":"BTC"}}}
using this code payment process completed,but not redirected to the call back url.
any one please help me.
Thanks in advance :)

The callback_url parameter is for a callback that receives a POST request behind the scenes when payment is complete. The user's browser is not redirected there. You probably want success_url.
https://coinbase.com/api/doc/1.0/buttons/create.html

Related

How to pass calculated/final value of one function to other functions in a controller of Codeigniter application

Using sessions we can achieve this, but need this without sessions or cookies.
<?php
class Employees extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function auth() {
$adminEmail = $this->input->post('adminEmail');
$adminPassword = $this->input->post('adminPassword');
if ($adminEmail != "" && $adminPassword != "") {
$query = $this->db->query("select * from admin_tbl where email= '$adminEmail' and password = '$adminPassword'");
//if user exist
if ($query->num_rows() <= 0) {
$response = array();
$jwtoken = "";
$this->session->set_flashdata("invalid", "Wrong email or password");
$response = array(
'status' => 'invalid',
'message' => $_SESSION['invalid'],
'token' => $jwtoken,
);
//used to send finalized values
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
return $jwtoken; //return value
} else {
// $this->session->set_userdata('adminEmail', $adminEmail);
$response = array();
$jwt = new JWT();
$data = array(
'adminEmail' => $adminEmail,
'iat' => time()
);
$jwtoken = $jwt->encode($data, jwtSecretKey, 'HS256');
// I want to pass $jwtoken's variable to all the functions in a controller
$this->session->set_flashdata("login", "Scucessfully login!");
// if (isset($_SESSION['adminEmail'])) {
if ($jwtoken != "") {
$response = array(
'status' => 'valid',
'message' => $_SESSION['login'],
'token' => $jwtoken
);
}
$abc = $jwtoken;
//used to send finalized values
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
return $jwtoken; //return value
}
}
}
public function addNew()
{
$response = array();
$this->auth(); // this value is always null returned by auth() method
}
}
?>
This is more of a OOP programming basics question. If you want to re-use a variable in another function of the same controller object, you have to set the variable globally for the Employees class and then set/get its value in your functions by using $this->yourVariableName. But the set value of the object instance can only be reused in that instance only. Which means that after the auth() function, another function should be called subsequently to "access" the $this->yourVariableName.
Another way is to pass the $jwtoken as a parameter to a function.
But the following code answers your question "How to pass calculated/final value of one function to other functions in a controller of Codeigniter application", if it doesn't, then your question should be corrected I guess.
Edit:
Ow ok, first the auth() function is being called, then you would like to pass the $jwtoken value to another function, am I right? Well once a function is finished executing, the variable "disappears" if not passed to another function. If you would like to process the $jwtoken value immediately within the auth() function, then the answer is to pass the $jwtoken value to another function from within the auth() function:
<?php
class Employees extends CI_Controller
{
public function __construct() {
parent::__construct();
}
public function auth() {
$adminEmail = $this->input->post('adminEmail');
$adminPassword = $this->input->post('adminPassword');
if ($adminEmail != "" && $adminPassword != "") {
$query = $this->db->query("select * from admin_tbl where email= '$adminEmail' and password = '$adminPassword'");
//if user exist
if ($query->num_rows() <= 0) {
$response = array();
$jwtoken = "";
$this->session->set_flashdata("invalid", "Wrong email or password");
$response = array(
'status' => 'invalid',
'message' => $_SESSION['invalid'],
'token' => $jwtoken,
);
//used to send finalized values
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
return $jwtoken; //return value
} else {
// $this->session->set_userdata('adminEmail', $adminEmail);
$response = array();
$jwt = new JWT();
$data = array(
'adminEmail' => $adminEmail,
'iat' => time()
);
$jwtoken = $jwt->encode($data, jwtSecretKey, 'HS256');
// I want to pass $jwtoken's variable to all the functions in a controller
// this is one way you can pass the value to another function, depending on what you want to do, you can also place a condition and continue only if the return value of the following function is respected:
$this->addNew($jwtoken);
// What is the addNew() supposed to do?
$this->session->set_flashdata("login", "Scucessfully login!");
// if (isset($_SESSION['adminEmail'])) {
if ($jwtoken != "") {
$response = array(
'status' => 'valid',
'message' => $_SESSION['login'],
'token' => $jwtoken
);
}
$abc = $jwtoken;
//used to send finalized values
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
return $jwtoken; //return value
}
}
}
public function addNew($jwtoken = "default_value_if_not_set") {
echo $jwtoken;
}
}
Since you are creating an API, I assume the API is a REST api and stateless, so there is no interference of sessions and cookies.
I assume your process works like this:
User does a login request from the app to the api and the api returns a token when the credentials check is valid
The token is stored in the app (in a local database for example) and used for other requests
So the only thing you need to do is (I assume you have a route to addNew):
public function addNew() {
$token = $this->input->get('token');
$loginData = $this->validateToken($token);
//... add new process
}
And from your app you need to pass the token with the request to the api.
How do you validate the token?
To obtain the data you have set in the token, you have to decode the token:
/**
* throws SignatureInvalidException
*/
function validateToken($token)
{
$jwt = new JWT();
return $jwt->decode($token, jwtSecretKey, 'HS256');
}
Code improvement
Avoid using sessions and cookies
Since your api is stateless, you have to avoid settings cookies or sessions. So in your controller you can remove the flash data helper:
public function auth() {
$adminEmail = $this->input->post('adminEmail');
$adminPassword = $this->input->post('adminPassword');
if ($adminEmail != "" && $adminPassword != "") {
$query = $this->db->query("select * from admin_tbl where email= '$adminEmail' and password = '$adminPassword'");
//if user exist
if ($query->num_rows() <= 0) {
$response = array();
$jwtoken = "";
# REMOVE THIS LINE
# $this->session->set_flashdata("invalid", "Wrong email or password");
$response = array(
'status' => 'invalid',
'message' => "Wrong email or password", //CHANGE THIS LINE
'token' => $jwtoken,
);
//used to send finalized values
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
return $jwtoken; //return value
} else {
// $this->session->set_userdata('adminEmail', $adminEmail);
$response = array();
$jwt = new JWT();
$data = array(
'adminEmail' => $adminEmail,
'iat' => time()
);
$jwtoken = $jwt->encode($data, jwtSecretKey, 'HS256');
// I want to pass $jwtoken's variable to all the functions in a controller
# REMOVE THIS LINE
# $this->session->set_flashdata("login", "Scucessfully login!");
// if (isset($_SESSION['adminEmail'])) {
if ($jwtoken != "") {
$response = array(
'status' => 'valid',
'message' => "Scucessfully login!", //CHANGE THIS LINE
'token' => $jwtoken
);
}
$abc = $jwtoken;
//used to send finalized values
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
return $jwtoken; //return value
}
}
}
Return the output response instead of $jwtoken
In your response you have already set the the token, so you can simply return the response:
return $this->output
->set_content_type('application/json')
->set_output(json_encode($response));
Your query is vulnerable to sql injections
Use escape method around you variables or bind the params:
$sql = "select * from admin_tbl where email=? and password = ?";
$query = $this->db->query($sql, array($adminEmail, $adminPassword));

How can we add status code response when we hit a rest api?

How can we be able to get a status code response if we are not able to pass the data on the api? I need your help guys I am completely new on this. Thanks in advance.
contoller
...
public function user(Request $request) {
$params = [
"firstName" => $request->firstname,
"lastName" => $request->lastname,
];
return $this->VoucherFactory->saveUser($params);
}
...
VoucherFactory.php
...
public function saveUser($params)
{
return $this->HttpClient->makeRequestPost($params, 'api/users', true);
//status code response logic
}
...
I'd do smth like this:
In the factory:
public function saveUser($params)
{
// No params passed, set code to 400
if(empty($params)) {
$statusCode = 400;
} else {
// Params passed, try to save user
$saveUserResult = $this->HttpClient->makeRequestPost($params, 'api/users', true);
// User saved ok
if($saveUserResult) {
$statusCode = 200;
} else {
$statusCode = 400;
}
}
return ["code" => $statusCode];
}
And than in the controller:
public function user(Request $request) {
$params = [
"firstName" => $request->firstname,
"lastName" => $request->lastname,
];
$result = $this->VoucherFactory->saveUser($params);
return $result["code"];
// Or if using some kind of framework, smth like:
// return $this->view(null, $result["code"]);
}
in you saveUser() function,
$this->HttpClient->makeRequestPost($params, 'api/users', true);
//after
return response()->setStatusCode(Response::HTTP_OK);
or in api/users route Controller, return the desired response

Yii2 creates new session instead of opening existing

I am working on a simple logic of storing my shopping cart in session using Yii2 native yii\web\Session.
Every time I add an item to a cart I call a method:
public function actionAdd( ) {
$id = Yii::$app->request->get('id');
$product = Product::findOne($id);
$session = Yii::$app->session;
$session->open();
$cart = new Cart();
$cart->addToCart($product);
$this->layout = false;
return $this->render('cart-modal', compact('session'));
}
this method works with a Cart model and adds my item to the session:
public function addToCart($product, $qty = 1) {
if(isset($_SESSION['cart'][$product->id])) {
$_SESSION['cart'][$product->id]['qty'] += $qty;
} else {
$_SESSION['cart'][$product->id] = [
'qty' => $qty,
'title' => $product->title,
'price' => $product->price,
'image' => $product->image,
];
}
}
and all goes well until I try add another item.
Then Yii instead of opening existing session creates a new one with this last item I've add. What can be the reason of this kind of behavior?
I'm working on a local web server OpenServer and haven't changed any setting that might be related to sessions.
You are basically not using session component at all. Change your code to:
public function actionAdd( ) {
$id = Yii::$app->request->get('id');
$product = Product::findOne($id);
// REMOVE THIS
// session is started automatically when using component
// $session = Yii::$app->session;
// $session->open();
$cart = new Cart();
$cart->addToCart($product);
$this->layout = false;
return $this->render('cart-modal', compact('session'));
}
public function addToCart($product, $qty = 1) {
$session = Yii::$app->session;
if ($session->has('cart')) {
$cart = $session['cart']; // you can not modify session subarray directly
} else {
$cart = [];
}
if(isset($cart[$product->id])) {
$cart[$product->id]['qty'] += $qty;
} else {
$cart[$product->id] = [
'qty' => $qty,
'title' => $product->title,
'price' => $product->price,
'image' => $product->image,
];
}
$session->set('cart', $cart);
}
I hope it helps. If not it means problem is somewhere else but nevertheless you should use session component properly.
Ok, I've figured. The problem was with my server. As soon as I moved to VPS this issue has gone.

PHP Post Data Formatting

As per the Eventbrite API v3 documentation, the preferred way to submit the data is as JSON. I am attempting to update via ExtJS grid simple organizer data. The changes are not being processed.
The solution is in MODX and the updateFromGrid.class.php looks like this:
class UpdateOrganizerFromGridProcessor extends modProcessor {
public function initialize() {
$data = $this->getProperty('data');
if (empty($data)) return $this->modx->lexicon('invalid_data');
$data = $this->modx->fromJSON($data);
if (empty($data)) return $this->modx->lexicon('invalid_data');
$this->id = $data['id'];
$this->params = array ();
// build JSON content for form submission...cooking key names
$this->formData = array (
'organizer.name' => $data['name'],
'organizer.description.html' => $data['description'],
'organizer.logo.id' => $data['logo_id'],
);
$this->formJSON = $this->modx->toJSON($this->formData);
$this->args = array('id' => $this->id, 'params' => $this->params);
return parent::initialize();
}
public function process() {
// call to main class to save changes to the Eventbrite API
$this->mgr_client = new Ebents($this->modx);
$this->output = $this->mgr_client->postData('organizers', $this->args, $this->formJSON);
$response = json_decode(json_encode($this->output), true);
return $this->outputArray($response);
}
}
return 'UpdateOrganizerFromGridProcessor';
The json output from the above is:
{"organizer.name":"Joe Organizer","organizer.description":"Joe is the Uberest Organizer."}
And my post function is:
//send data to Eventbrite
function postData($method, $args, $JSONdata) {
error_log("JSON Payload : " . $JSONdata);
// Get the URI we need.
$uri = $this->build_uri($method, $args);
// Construct the full URL.
$request_url = $this->endpoint . $uri;
// This array is used to authenticate our request.
$options = array(
'http' => array(
'header' => "Content-type: application/json\r\n"
. "Accept: application/json\r\n",
'method' => 'POST',
'content' => $JSONdata,
'header' => "Authorization: Bearer " . $this->token
)
);
// Call the URL and get the data.
error_log("URL: " . $request_url);
error_log("Content: " . $options['http']['content']);
$resp = file_get_contents($request_url, false, stream_context_create($options));
// parse our response
if($resp){
$resp = json_decode( $resp );
if( isset( $resp->error ) && isset($resp->error->error_message) ){
error_log( $resp->error->error_message );
}
}
// Return it as arrays/objects.
return $resp;
}
function build_uri($method, $args) {
// Get variables from the $args.
extract($args);
// Get rid of the args array.
unset($args);
// Create an array of all the vars within this function scope.
// This should be at most 'method', 'id' and 'data'.
$vars = get_defined_vars();
unset($vars['params']);
// Put them together with a slash.
$uri = implode($vars, '/');
if (!empty($params)) {
return $uri ."?". http_build_query($params);
}
return $uri;
}
The post is working however there is no update to the data and the response back is the original data set. What am I missing here?
I figured it out. It was an issue with a missing slash right before the query string. I also removed the JSON data payload and am submitting as form encoded. The final class is below:
class UpdateOrganizerFromGridProcessor extends modProcessor {
public function initialize() {
$data = $this->getProperty('data');
if (empty($data)) return $this->modx->lexicon('invalid_data');
$data = $this->modx->fromJSON($data);
if (empty($data)) return $this->modx->lexicon('invalid_data');
$this->id = $data['id'];
$this->params = array (
'organizer.name' => $data['name'],
'organizer.description.html' => $data['description'],
'organizer.logo.id' => $data['logo_id'],
);
$this->args = array('id' => $this->id, 'data'=> '', 'params' => $this->params);
return parent::initialize();
}
public function process() {
// call to main class to save changes to the Eventbrite API
$this->mgr_client = new Ebents($this->modx);
$this->output = $this->mgr_client->postData('organizers', $this->args);
$response = json_decode(json_encode($this->output), true);
return $this->outputArray($response);
}
}
return 'UpdateOrganizerFromGridProcessor';

How can i run a check on a MySQL database for a FB ID, & other personal data so only a certain page is shown when revisiting?

I have created a Facebook App that i need people to only enter their data to once.
It's all working and the database is being populated, but i need to make sure people don't keep coming back and re-entering their data endlessly.
What's the best way to check if the user has already submitted their data ?
The signed_request could still have been submitted and their data not entered so i need the check for both to work.
Ideally the PHP would just check for FB ID + other data, and only display a confirmation / thankyou page.
Currently my php to send to the database is:
class Users_Model extends CI_Model {
protected $_name = 'users';
function add($id,$key,$value) {
$data = array(
'id' => $id,
'name' => $key,
'value' => $value
);
return $this->db->insert($this->_name, $data);
}
function update($id,$key,$value) {
$data = array(
'value' => $value
);
$this->db->where(array(
'id' => $id,
'name' => $key
));
return $this->db->update($this->_name, $data);
}
function exists($id,$key=null) {
if($key == null) {
$this->db->where(array(
'id' => $id
));
} else {
$this->db->where(array(
'id' => $id,
'name' => $key
));
}
$query = $this->db->get($this->_name);
if($query->num_rows() > 0) {
return true;
}
return false;
}
function remove($id) {
$data = array(
'id' => $id,
);
return $this->db->delete($this->_name, $data);
}
function all() {
$query = $this->db->get($this->_name);
$results = array();
if($query->num_rows() > 0) {
foreach($query->result() as $row) {
$results[]=$row;
}
}
return $results;
}
}
Any help much appreciated...
What's the best way to check if the user has already submitted their data ?
Check if you already have a record for the user’s Facebook id in your database.

Categories