Magento 1.8.0.0: Add custom payment method redirecting to a new page - magento

I'm working locally with magento 1.8.0.0. I succeeded to create a custom payment method. The method is appearing to the list of payment method at the "Payment Information" during the checkout. The problem is that when I select it, it automatically brings a credit card form, which is not what I want. What I want is to select it and once I click the "continue" button I get redirected to another php page containing my own form.

Solution by OP.
For you who want to redirect to the gateway and want the gateway to redirect back to your controller's action method, here is how things work:
In the file app/code/local/Yourcompany/Yourmodule/Model/PaymentMethod.php ,do as follow:
class Yourcompany_Yourmodule_Model_PaymentMethod extends Mage_Payment_Model_Method_Abstract{
protected $_code = "yourmodule";
protected $_isGateway = true;
protected $_canAuthorize = true;
protected function _getCheckout() {
return Mage::getSingleton('checkout/session'); }
public function getOrderPlaceRedirectUrl() { return Mage::getUrl(yourmodule/index/youraction', array('_secure' => true)); }}
In the line return Mage::getUrl(yourmodule/index/youraction', array('_secure' => true)); , "index" means that my controller php file is named IndexController.php. You may change the name as you wish.
In the file app/code/local/Yourcompany/Yourmodule/controllers/IndexController.php , you may code as follow:
class Yourcompany_Yourmodule_IndexController extends Mage_Core_Controller_Front_Action{
public function indexAction() {
$this->loadLayout();
$block = $this->getLayout()->createBlock('Mage_Core_Block_Template','yourmodule',array('template' => 'yourmodule/redirect.phtml'));
$this->getLayout()->getBlock('content')->append($block);
$this->renderLayout(); }
/*In the response action, you may code like this*/
public function responseAction() {
$status=$_REQUEST['param1'];
$orderNo=$_REQUEST['param2'];
if(somecondition)
{
/*update order status */
$ordera = Mage::getModel('sales/order')->loadByIncrementId($orderNo);
$ordera->setState(Mage_Sales_Model_Order::STATE_PENDING_PAYMENT, true)->save();
$this->_redirect("checkout/onepage/success");
}
else
{
$this->_redirect("checkout/cart/");
}
} }
The indexAction() is redirecting to a template redirect.phtml file. This file will collect some parameters to send to the gateway (order number, customer name, total money, etc.). You may put that phtml file here:
app/design/frontend/base/default/template/yourmodule/redirect.phtml
Its content may be coded as follow:
<?php
$orderId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
$order = Mage::getSingleton('sales/order')->loadByIncrementId($orderId);
$order_amount=$order->getGrandTotal();
$customerData = Mage::getSingleton('customer/session')->getCustomer();
$customerAddressId = Mage::getSingleton('customer/session')->getCustomer()->getDefaultBilling(); //oder getDefaultShipping
$address = Mage::getModel('customer/address')->load($customerAddressId);
$customer_name=$address->getFirstname().' '.$address->getLastname();
$customer_email=$customerData->getEmail();
?>
<form name="myjs" method="post" action="http://yourgatewayaddreshere">
<input type="hidden" name="customername" value="<?php echo $customer_name; ?>">
<input type="hidden" name="customermail" value="<?php echo $customer_email; ?>">
<input type="hidden" name="TotalMoney" value="<?php echo $order_amount; ?>">
</form>
<script type="text/javascript">
document.myjs.submit();
</script>

Related

Trying to obtain data whose status are active in database and it should be displayed in dropdown list

I'm trying to give a dropdown list in view, but that should be from database.
This is my Controller:
public function index()
{
$this->load->view('welcome_message');
}
public function subject()
{
$this->load->view('sub');
}
In view simple dropdown list i have given,Each subject is having different id, which I have given in value of the option tag.
And only the subjects which statuses are active should be listed.
How to do that???
load your model in your controller assuming asadminmodel
Change your controller to
public function subject()
{
$this->load->model('adminmodel');
$data['info']=$this->adminmodel->get_dropdown();
$this->load->view('sub', $data);
}
In your model add get_dropdown() function
public function get_dropdown()
{
$this->db->where('status', 'active');
$query=$this->db->get('tablename');
return $query->result_array();
}
In your view page
<select>
<?php foreach($info as $info){ ?>
<option value="<?php echo $info['id']; ?>"><?php echo $info['subject']; ?></option>
<?php } ?>
</select>

Get specific row from database with codeigniter

I'm new to this so i have this silly question.I want to make a login form and when the user logs in i want to show all his information in the screen(username attack defence...).The thing is i don't know how to call the specific function i've made because in my controller calls function index() by default and not the function guser().
login view
<h2>Login</h2>
<?php if($error==1){ ?>
<p>Your Username/password did not match </p>
<?php } ?>
<form action="<?=base_url()?>index.php/Users/login" method="post">
<p>Username: <input name="user" type="text" /> </p>
<p>Password: <input name="password" type="password" /> </p>
<p><input type="submit" value="Login" /></p>
</form>
users controller
<?php
class Users Extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('User');
}
function index(){
$data['users']=$this->User->get_users();//sto model post tha kalesei tin sinartisi get_posts
$this->load->view('Post_index',$data);
}
function guser($id){
$data['user']=$this->User->get_user($id);
$this->load->view('Post_index',$data);
}
function login(){
$data['error'] = 0; // simenei oti den exei errors
if($_POST){
$user=$this->input->post('user',true);//pairnei to username p edose o xristis(einai idio me to $_POST)
$password=$this->input->post('password',true);//pairnei to password p edose o xristis
//$type=$this->input->post('charact',true);
$user1=$this->User->login($user,$password);//,$type);
if(!$user1){
$data['error']=1;
}else{
$this->session->set_userdata('id',$user1['id']);
$this->session->set_userdata('user',$user1['user']);
$this->session->set_userdata('name',$user1['name']);
$this->session->set_userdata('money',$user1['money']);
$this->session->set_userdata('attack',$user1['attack']);
$this->session->set_userdata('defence',$user1['defence']);
$this->session->set_userdata('level',$user1['level']);
$this->session->set_userdata('xp',$user1['xp']);
redirect(base_url().'index.php/Users');
}
}
$this->load->view('Login',$data);
}
function registerSam(){
if($_POST){
$data=array(
'user'=>$_POST['user'],
'name'=>$_POST['name'],
'password'=>$_POST['password'],
'charact'=>"Samurai",
'money'=>400,
'attack'=>10,
'defence'=>5,
'level'=>0,
'xp'=>0
);
$userid=$this->User->create_user($data);
}
}
function registerKnight(){
if($_POST){
$data=array(
'user'=>$_POST['user'],
'name'=>$_POST['name'],
'password'=>$_POST['password'],
'charact'=>"Knight",
'money'=>400,
'attack'=>5,
'defence'=>10,
'level'=>0,
'xp'=>0
);
$userid=$this->User->create_user($data);
}
}
}
?>
user model
<?php
class User Extends CI_Model{
function create_user($data){
$this->db->insert('unityusers',$data);
}
function login($user,$password){
$where=array(
'user'=>$user,
'password'=>$password,
);
$this->db->select()->from('unityusers')->where($where);
$query=$this->db->get();
return $query->first_row('array');
}
function get_user($id){
$this->db->select()->from('unityusers')->where(array('id'=>$id));
$query=$this->db->get();
return $query->first_row('array');
}
function get_users($num=20,$start=0){// tha paroume 20 posts k tha arxisoume apo to proto
$this->db->select()->from('unityusers')->limit($num,$start);
$query=$this->db->get();
return $query->result_array();
}
}
?>
Although you have accepted the answer I like to point out some basic functionality for you to more improved code.
Different technique to load the data to view from controller:
function index(){
$users = $this->User->get_users();
$this->load->view('Post_index',['users' => $users, 'any_other_data' => $any_other_data ... and so on]);
}
When you get post data in the controller then you should check for a validation first inside your login function. And in login functionality it will be more useful. setting-validation-rules
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required',
Loading a model and it's function. You don't need to use uppercase in this as give below.
$this->load->model('user');
$this->user->get_users();
Your registration Function registerSam you don't need to create an array of post data Codeigniter will provide the functionality to get all your post data at once. To remove unnecessary data from that array use unset.
$your_post_array = $this->input->post();
To call a specific function made, you can access it via a browser using the link
BASE_URL/index.php/ControllerName/MethodName
So, in your case to call the guser method, the url would be
BASE_URL/index.php/users/guser
Hope that helps.
You have an error in guser function on the controller. You don't need to passs any argument to the function. You can get ID of user from the session, which was actually added in session once the user has entered correct credentials.
Also after login, you need to redirect user to guser function instead of users. Because as per your controller users function dosen't exist.
Change From
redirect(base_url().'index.php/Users');
To
redirect(base_url().'index.php/guser');
Please check below for solution.
function guser(){
$data['user']=$this->User->get_user($this->session->userdata('id'));
$this->load->view('Post_index',$data);
}
Let me know if it not works.

Oauth Implementation using PHP and JS facebook SDK

Hai Fellow Developers,
I am implementing A facebook Login to my Web App using codeigniter (E-commerce kind of platform).
So, I have lot of filters in my site based upon them i am trying to fetch data and requesting a service. so user has to log in to request a service, so at last i am forcing user to login to continue (like buying something).
Here comes the problem, I implemented Facebook login using Javascript SDK and trying to get accesstoken. and created a FACEBOOK library in codeigniter which fetches user's data using FacebookJavaScriptLoginHelper. and now i should update user details in all sessions and attach the user name dynamically to the current view in codeigniter.
you can look below what i have tried upto now:
Facebook Libabry:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if ( session_status() == PHP_SESSION_NONE ) {
session_start();
}
// Autoload the required files
require_once( APPPATH . 'libraries/facebook/autoload.php' );
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\FacebookJavaScriptLoginHelper;
use Facebook\GraphObject;
use Facebook\GraphUser;
class Facebook {
var $ci;
var $helper;
var $session;
var $permissions;
public function __construct() {
$this->ci =& get_instance();
$this->permissions = $this->ci->config->item('permissions', 'facebook');
// Initialize the SDK
FacebookSession::setDefaultApplication( $this->ci->config->item('api_id', 'facebook'), $this->ci->config->item('app_secret', 'facebook') );
$this->helper = new FacebookJavaScriptLoginHelper();
// No session exists
try {
$this->session = $this->helper->getSession();
} catch( FacebookRequestException $ex ) {
} catch( Exception $ex ) {
// When validation fails or other local issues
}
}
/**
* Returns the login URL.
*/
public function login_url() {
return $this->helper->getLoginUrl( $this->permissions );
}
/**
* Returns the current user's info as an array.
*/
public function get_user() {
if ( $this->session) {
$request = ( new FacebookRequest( $this->session, 'GET', '/me' ) )->execute();
// Get response as an array
$user = $request->getGraphObject()->asArray();
return $user;
}
return false;
}
public function logout(){
session_start();
session_destroy();
}
}
And in My controller i have my index function like this
public function index(){
$fb_data = $this->facebook->get_user();
$profile_data=array(
'name'=>$fb_data['name'],
'id' =>$fb_data['id'],
'image'=>'http://graph.facebook.com/'.$fb_data['id'].'/picture?width=300',
'email'=>$fb_data['email'],
'oauthProvider'=>'facebook',
);
$this->session->set_userdata('user_name', $fb_data['name']);
echo json_encode($profile_data);
}
My Header View:
<?php if($this->session->userdata('user_name')): ?>
<li id="userName" class="dropdown">
Welcome <span class="user_name"><?php echo $this->session->userdata('user_name')?></span><span class="caret"></span>
<ul class="dropdown-menu">
<li>Account settings</li>
<li>Logout</li>
</ul>
</li>
<?php else: ?>
<li id="login">Login</li>
<?php endif; ?>
Ajax call
$.ajax({
url:"<?php echo base_url('redirectoauth');?>",
success:function(data){
var data=$.parseJSON(data);
$('.user_name').html(data.name);
$('#userName').css('display','block')
$('#login').css('display','none');
$('#socialLogin').modal('hide');
}
});
Any references or tuts,suggestions on architecture to overcome this problem.
this will fix your issue
ajax call
$.ajax({
url:"<?php echo base_url('redirectoauth');?>",
success:function(data){
var data=$.parseJSON(data);
$('.user_name').html(data.name);
$('#logined').css('display','block')
$('#sociallogined').css('display','none');
$('#socialLogin').modal('hide');
}
});
view
<ul id="logined" <?php echo $this->session->userdata('user_name') ? 'style="display:none"' :''; ?>>
<li id="userName" class="dropdown">
Welcome <span class="user_name"><?php echo $this->session->userdata('user_name')?></span><span class="caret"></span>
<ul class="dropdown-menu">
<li>Account settings</li>
<li>Logout</li>
</ul>
</li>
</ul>
<ul id="sociallogined">
<li id="login">Login</li>
</ul>

Models in codeigniter

In CodeIgniter, I designed a page, which there is a login form, and a simple home page.
The validation I did client side validation only.
view login.php :-
<form name="login" id="login" action="<?php echo base_url() ?>login/success" onsubmit="return validatelogin()" method="post">
... HTML
<input type="text" id="username" name="username" />
<input type="password" id="passwrd" name="passwrd">
Javascript validation in the view page "login.php",
function validatelogin(){
var x=document.forms["login"]["username"].value;
var y=document.forms["login"]["passwrd"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
if (y==null || y=="")
{
alert("Password field must be filled out");
return false;
}
if(x!="monisha" && y!="monisha"){
alert("Username and Password incorrect");
return false;
}
return true;
}
Controller - login.php :-
class Login extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->library('session');
}
function index(){
$this->load->view('login');
}
function success() {
$data = array('username' => "monisha");
$this->session->set_userdata($data);
redirect ('home');
}
}
I created the table "login", which is having the username and password fields.
I need to validate it using the database and the database query. Can anybody please assist me on what all changes I have to do in controller file, and the view page, to get this done.?
Learn form validation in CI first! http://ellislab.com/codeigniter/user-guide/libraries/form_validation.html
You need to change this accordingly.
In Controller:
$this->load->helper(array('form')); #no need to do this if already loaded
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required||is_unique[table_name.column_name]');
$this->form_validation->set_rules('passwrd', 'Password', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('view_name');
}
else
{
redirect('controller/function', 'refresh');
}
In view page:
<?php echo validation_errors(); ?>

CodeIgniter update page - Simple CRUD website assistance required

After looking through the forums and starting to try to create a basic CRUD website I am currently struggling to have a page that updates the articles as follows. If someone could kindly tell me where I am going wrong, I will be most greatful. I am getting a 404 error at 'news/input'
model (at news_model.php)
public function update($id, $data)
{
$this->db->where('id', $id);
$this->db->update('news', $data);
}
controller (news.php)
public function update($id){
$data = array(
'title' => $this->input->post('title'),
'slug' => $this->input->post('slug'),
'text' => $this->input->post('text'));
if($this->news_model->exists($id)) {
$this->news_model->update($id, $data);
}
else {
$this->news_model->insert($data);
}
}
html (views/news/input.php)
<h2>Update a news item</h2>
<?php echo validation_errors(); ?>
<?php echo form_open('news/update') ?>
<label for="title">Title</label>
<input type="input" name="title" /><br />
<label for="slug">Slug</label>
<input type="input" name="slug" /><br />
<label for="text">Text</label>
<textarea name="text"></textarea><br />
<input type="submit" name="submit" value="Update an item" />
You get a 404 because your news controller seems to have no method 'input'. Try adding something like this:
public function input(){
// load the form
$this->load->view('/news/input');
}
Note that for updating data you will need to fetch and pass it into the view first, then render the (filled out) form using set_val() and other CI functions.
Currently you're "hardcoding" the HTML form which makes populating and maintaining state (when validation fails) difficult. I suggest you play through the forms tutorial on the CI website.
Edit:
To create a update/insert (upsert) controller change as follows:
Controller:
function upsert($id = false){
$data['id'] = $id; // create a data array so that you can pass the ID into the view.
// you need to differntiate the bevaviour depending on 1st load (insert) or re-load (update):
if(isset($_POST('title'))){ // or any other means by which you can determine if data's been posted. I generally look for the value of my submit buttons
if($id){
$this->news_model->update($id, $this->input->post()); // there's post data AND an id -> it's an update
} else {
$this->news_model->insert($id, $this->input->post()); // there's post data but NO id -> it's an insert
}
} else { // nothing's been posted -> it's an initial load. If the id is set, it's an update, so we need data to populate the form, if not it's an insert and we can pass an empty array (or an array of default values)
if($id){
$data['news'] = $this->news_model->getOne($id); // this should return an array of the news item. You need to iterate through this array in the view and create the appropriate, populated HTML input fields.
} else {
$data['news'] = $this->news_model->getDefaults(); // ( or just array();) no id -> it's an insert
}
}
$this->load->view('/news/input',$data);
}
And amend the $id to the action-url in your view:
<?php echo form_open('news/upsert/'.$id) ?>

Resources