I am trying to save the data in database which is response by paypal.
Here is my try, I get the data from paypal response like this.
public function getDone(Request $request)
{
$id = $request->get('paymentId');
$token = $request->get('token');
$payer_id = $request->get('PayerID');
$payment = PayPal::getById($id, $this->_apiContext);
$paymentExecution = PayPal::PaymentExecution();
$paymentExecution->setPayerId($payer_id);
$executePayment = $payment->execute($paymentExecution, $this->_apiContext);
print_r($executePayment);
}
the result is here
PayPal\Rest\ApiContext Object ( [requestId:PayPal\Rest\ApiContext:private] => 216056242044171493312944593 [credential:PayPal\Rest\ApiContext:private] => PayPal\Auth\OAuthTokenCredential Object ( [logger:PayPal\Auth\OAuthTokenCredential:private] => PayPal\Core\PayPalLoggingManager Object ( [loggerName:PayPal\Core\PayPalLoggingManager:private] => PayPal\Auth\OAuthTokenCredential [isLoggingEnabled:PayPal\Core\PayPalLoggingManager:private] => [loggingLevel:PayPal\Core\PayPalLoggingManager:private] => [loggerFile:PayPal\Core\PayPalLoggingManager:private] => ) [clientId:PayPal\Auth\OAuthTokenCredential:private] => AVFGCgHNihKu_MpwgbpDPuB9FO8Z5hdgGrEx1mZPhQoOs2vLzFf1Dv6qA2bN5Ja_qucPYkN0X5Hrz9ZE [clientSecret:PayPal\Auth\OAuthTokenCredential:private] => EBdP51X4tMAi9WYcgI1ue0TQLljyvDBxO1yQAFJn7X7z_GP7mAOMnAsDCsREotfEOCESD_D6Qp14plTy [accessToken:PayPal\Auth\OAuthTokenCredential:private] => A21AAG85CiMoJ6JFJfQIfSMdzPm1sbwy7AZcT1zyxNbfw2-WXms8hgALJK3uFJy9DfG3oVQTKrIEApTwvDoiXAp49SrIiBfmw [tokenExpiresIn:PayPal\Auth\OAuthTokenCredential:private] => 32315 [tokenCreateTime:PayPal\Auth\OAuthTokenCredential:private] => 1493312949 [cipher:PayPal\Auth\OAuthTokenCredential:private] => PayPal\Security\Cipher Object ( [secretKey:PayPal\Security\Cipher:private] => EBdP51X4tMAi9WYcgI1ue0TQLljyvDBxO1yQAFJn7X7z_GP7mAOMnAsDCsREotfEOCESD_D6Qp14plTy ) [_propMap:PayPal\Common\PayPalModel:private] => Array ( ) ) )
I want to save in database and how i try to do it is here
public function getDone(Request $request)
{
$id = $request->get('paymentId');
$token = $request->get('token');
$payer_id = $request->get('PayerID');
$payment = PayPal::getById($id, $this->_apiContext);
$paymentExecution = PayPal::PaymentExecution();
$paymentExecution->setPayerId($payer_id);
$executePayment = $payment->execute($paymentExecution, $this->_apiContext);
if($request->tx){
if($payment=Payment::where('transaction_id',$request->tx)->first()){
$payment_id=$payment->id;
}else{
$payment=new Payment;
$payment->transaction_id=$request->email;
$payment->transaction_id=$request->name;
$payment->item_number=$request->item_number;
$payment->transaction_id=$request->tx;
$payment->currency_code=$request->cc;
$payment->payment_status=$request->st;
$payment->save();
$payment_id=$payment->id;
}
return 'Pyament has been done and your payment id is : '.$payment_id;
}else{
return 'Payment has failed';
}
}
The error is showing like
Payment has failed
Here is my database which is trying to save in
public function up()
{
Schema::create('payments', function (Blueprint $table) {
$table->increments('id');
$table->string('email');
$table->string('name');
$table->string('item_number');
$table->string('transaction_id');
$table->string('currency_code');
$table->string('payment_status');
$table->timestamps();
});
}
Where am i wrong in my codes, please guide me to save in database.
Please guide me. Thanks.
Related
In this code, I would like to get time when the user joined and left and store it to DB. What happens it that I get the same value in both 'joined' and 'left' tables. How to fix it so it would store different values?
Schema::create('user_info', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('ip');
$table->string('joined');
$table->string('left');
});
in LoginController
public function logout() {
$left = now();
auth()->logout();
session()->forget('name');
session()->put('left', $left);
return redirect('/');
}
in Model
protected $fillable = ['ip','name', 'joined'];
const CREATED_AT = 'joined';
const UPDATED_AT = 'left';
public static function storeUser() {
UserInfo::create([
'ip' => Request::ip(),
'name' => Auth::user()->name,
'joined' => now(),
]);
}
BroadcastServiceProvider.php
Broadcast::channel('chat', function ($user) {
$ip = Request::ip();
$time = now();
if (auth()->check() && !session()->has('name')) {
UserInfo::storeUser();
session()->put('name',$user->name);
return [
'id' => $user->id,
'ip' => $ip,
'name' => $user->name,
'joined' => $time,
];
}
});
This image illustates the behaviour after some changes you'll see below. It show that data with key 'left' for now goes not to the intended user but to the first user with this name.
The follow up of this question is here How to override this code so that it insert data properly?
CREATED_AT and UPDATED_AT are timestamps that gets changed by the Eloquent model, whenever a model gets created it's also modified or updated from a non-existing to existing so this is why you get the same value
In the logout function, update the user's left column
public function logout() {
$user_id = auth()->id(); // Get authenticated user ID
$user_info = App\UserInfo::find($user_id); // Get user info
$user_info->left = now(); // Change here
$user_info->save(); // Update here
auth()->logout();
session()->forget('name');
session()->put('left', $left);
return redirect('/');
}
According to your table, there's no way to distinguish between users and their info since the name is not unique
Make a user_id based relationship
User model
public function info()
{
return $this->hasOne(UserInfo::class);
}
UserInfo model
public function user()
{
return $this->belongsTo(User::class);
}
And in the user_infos migration
Schema::create('user_infos', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->string('name');
$table->string('ip');
$table->dateTime('joined');
$table->dateTime('left');
});
Cleaner Method
public function logout() {
$info = auth()->user()->info; // Get user info
$info->left = now(); // Change here
$info->save(); // Update here
auth()->logout();
session()->forget('name');
session()->put('left', $left);
return redirect('/');
}
Hope this helps
I have two models TeamMember and ProjectRequest.
A TeamMember can have one ProjectRequest, that is why I created the following Eloquent relationship on TeamMember:
class TeamMember extends Model {
//
protected $table = 'team_members';
protected $fillable = ['project_request_id'];
// Relations
public function projectTeam() {
return $this->hasOne('\App\Models\ProjectRequest', 'project_request_id');
}
}
In my Controller I want to query both tables, however it returns the failure message.
What is important to know is that $request->projectTeam is an array of emails, looking like this:
array:2 [
0 => "mv#something.com"
1 => "as#something.com"
]
Meaning that I need to bulk insert into team_members table the project_request_ id for each team member where the emails are in the array.
How can I do that in the right way? The following is my attempt:
public function createProjectTeam(Request $request){
try {
$title = $request->projectTitle;
$TeamMember = $request->projectTeam;
$projectRequest = ProjectRequest::create(['project_title' => $title]);
$projectRequestId = $projectRequest->id;
$projectTeam = $this->teamMembers->projectTeam()->create(['project_request_id'=> $projectRequestId])->where('email', $TeamMember);
//$projectTeam = TeamMember::createMany(['project_request_id' => $projectRequestId])->where($TeamMember);
//dd($projectTeam);
return $projectRequest.$projectTeam;
} catch(\Exception $e){
return ['success' => false, 'message' => 'project team creation failed'];
}
}
There are a few things you can do.
Eloquent offers a whereIn() method which allows you to query where a field equals one or more in a specified array.
Secondly, you can use the update() method to update all qualifying team members with the project_request_id:
public function createProjectTeam(Request $request)
{
try {
$projectRequest = ProjectRequest::create(['project_title' => $request->projectTitle]);
TeamMember::whereIn('email', $request->projectTeam)
->update([
'project_request_id' => $projectRequest->id
]);
return [
'success' => true,
'team_members' => $request->projectTeam
];
} catch(\Exception $e) {
return [
'success' => false,
'message' => 'project team creation failed'
];
}
}
I hope this helps.
I have the UsersFixture with three records.
The test methods first() and second(), which both are before guest_can_login(), pr's show "Joe", "Joe", as expected. But with test method third(), which comes after guest_can_login(), I get notice error: trying to get property of non-object.
So, for a reason, something in the guest_can_login() breaks the rest of the test methods. I have tried by making a duplicate of guest_can_login() as well.
I think it is strange, as tearDown should "reset" everything after each test. I'm out of ideas. And after reading the Cakephp Testing docs, I haven't been able to solve it.
Any suggestions to help me solve this is much appreciated.
Code below (gist if you prefer: https://gist.github.com/chris-andre/2eb3ad053073caf4f1c81722428a900b):
public $fixtures = [
'app.users',
'app.tenants',
'app.roles',
'app.roles_users',
];
public $Users;
public function setUp()
{
parent::setUp();
$config = TableRegistry::getTableLocator()->exists('Users') ? [] : ['className' => UsersTable::class];
$this->Users = TableRegistry::getTableLocator()->get('Users', $config);
}
/**
* tearDown method
*
* #return void
*/
public function tearDown()
{
unset($this->Users);
TableRegistry::clear();
parent::tearDown();
}
/** #test */
public function guest_can_register()
{
$this->enableCsrfToken();
$this->enableSecurityToken();
$this->configRequest([
'headers' => [
'host' => 'timbas.test'
]
]);
$data = [
'email' => 'chris#andre.com',
'first_name' => 'Christian',
'last_name' => 'Andreassen',
'password' => '123456',
'tenant' => ['name' => 'Test Company AS', 'domain' => 'testcomp', 'active' => true],
'active' => true
];
$this->post('/register', $data);
$this->assertResponseSuccess();
$this->assertRedirect(['controller' => 'Users', 'action' => 'login', '_host' => 'testcomp.timbas.test']);
$user = $this->Users->find()
->contain(['Tenants', 'Roles'])
->where(['Users.email' => 'chris#andre.com'])
->first();
}
/** #test */
public function first()
{
$users = $this->Users->find()->first();
pr($users->first_name);
}
/** #test */
public function second()
{
$users = $this->Users->find()->first();
pr($users->first_name);
}
/** #test */
public function guest_can_login()
{
$this->enableCsrfToken();
$this->enableSecurityToken();
$this->configRequest([
'headers' => [
'host' => 'testcomp.timbas.test'
]
]);
$data = [
'email' => 'chris#andre.com',
'first_name' => 'Christian',
'last_name' => 'Andreassen',
'password' => '123456',
'tenant' => ['name' => 'Test Company AS', 'domain' => 'testcomp', 'active' => true],
'active' => true,
'roles' => ['_ids' => [ADMINISTRATOR_ROLE_ID]]
];
$user = $this->Users->newEntity($data, [
'associated' => ['Tenants', 'Roles']
]);
$this->Users->save($user);
$getNewUser = $this->Users->find()
->contain(['Roles'])
->where(['Users.email' => 'chris#andre.com'])
->first()
->toArray();
// pr($getNewUser->id);
$this->post('/users/login', [
'email' => 'chris#andre.com',
'password' => '123456'
]);
$this->assertSession($getNewUser, 'Auth.User');
}
/** #test */
public function third()
{
$users = $this->Users->find()->first();
pr($users->first_name);
}
EDIT 2018-08-06:
Users::register() is a global context, I cannot be accessed from url with subdomain. E.g. tenant1.domain.com/register will throw a badRequest, while domain.com/register is a valid url. On registration success, user is forwarded to login from right url. Login-url = Tenants.domain + domain + suffix, e.g. tenant1.domain.com. When user is on the tenant scope (url with subdomain), the Tenants.id where Tenants.domain = tenant1, will be added to the where clause in all queries for the models having the behavior attached.
Now, what happens in third() is that the tenant_id from the newly created Tenant in guest_can_login() is added to the query, which means the test "is still on the tenant scope" when third() is run. That is the problem.
The other problem is that setUp() is called on all test methods but third(). testDown() is called on every test methods.
App\Middleware\TenantMiddleware.php:
use InstanceConfigTrait;
/**
* Default config.
* Options:
* - globalScope: tells the middleware what controller and action tenant scope is not being used
* Example
* 'globalScope' => [
* 'Pages' => ['*'], // All actions in PagesController is global
* 'Users' => ['register'] // Register action in UsersController is global
* ]
* #var array
*/
protected $_defaultConfig = [
'globalScope' => [
'Users' => ['register'],
'Landing' => ['*'],
'Pages' => ['*']
],
];
public function __construct($config = [])
{
if (!isset($config['primaryDomain'])) {
$config['primaryDomain'] = Configure::read('Site.domain');
}
$this->setConfig($config);
}
/**
* Invoke method.
*
* #param \Cake\Http\ServerRequest $request The request.
* #param \Psr\Http\Message\ResponseInterface $response The response.
* #param callable $next Callback to invoke the next middleware.
* #return \Psr\Http\Message\ResponseInterface A response
*/
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next)
{
// Get subdomains
$subdomains = $request->subdomains();
// If subdomains not empty, the first is always the tenants domain
$subdomain = !empty($subdomains) ? $subdomains[0] : '';
Tenant::setDomain($subdomain);
// Get params of current request
$params = $request->getAttribute('params');
$controller = $params['controller'];
$action = $params['action'];
// Set tenantScope as default
Tenant::setScope('tenant');
$globalScope = $this->getConfig('globalScope');
// If Controller and action is a global scope
if (array_key_exists($controller, $globalScope)) {
if (in_array($action, $globalScope[$controller]) || in_array('*', $globalScope[$controller])) {
Tenant::setScope('global');
}
}
if (
(Tenant::getScope() === 'tenant' && Tenant::tenant() === null)
|| (Tenant::getDomain() === '' && Tenant::getScope() === 'tenant')
|| (Tenant::getDomain() !== '' && Tenant::getScope() === 'global')
) {
throw new NotFoundException('The page you are looking for does not exists.');
}
$primaryDomain = $this->getConfig('primaryDomain');
if (array_key_exists($controller, $globalScope)) {
if (in_array($action, $globalScope[$controller]) && Tenant::getScope() === 'global') {
}
}
return $next($request, $response);
}
App\Model\Behavior\TenantScopeBehavior.php:
protected $_table;
/**
* Default configuration.
*
* #var array
*/
protected $_defaultConfig = [];
public function __construct(Table $table, array $config = [])
{
parent::__construct($table, $config);
}
public function beforeFind(Event $event, Query $query, ArrayObject $options)
{
$model = $this->_table->getAlias();
$foreig_key = 'tenant_id';
if (!isset($options['skipTenantCheck']) || $options['skipTenantCheck'] !== true) {
if (Tenant::getScope() === 'tenant') {
if ($model === 'Tenants') {
$query->where(['Tenants.id' => Tenant::tenant()->id]);
} else {
$query->where([$model . '.' . $foreig_key => Tenant::tenant()->id]);
}
}
}
return $query;
}
public function beforeSave(Event $event, Entity $entity, $options)
{
if (Tenant::getScope() === 'tenant') {
if ($entity->isNew()) {
$entity->tenant_id = Tenant::tenant()->id;
} else {
// Check if current tenant is owner
if ($this->_table->getAlias() === 'Tenants') {
if ($entity->id != Tenant::tenant()->id) {
throw new BadRequestException();
}
} else {
if ($entity->tenant_id != Tenant::tenant()->id) {
throw new BadRequestException();
}
}
}
}
return true;
}
public function beforeDelete(Event $event, Entity $entity, $options)
{
if (Tenant::getScope() === 'tenant') {
if ($entity->tenant_id != Tenant::tenant()->id) { //current tenant is NOT owner
throw new BadRequestException();
}
}
return true;
}
App\Tenant\Tenant.php:
/**
* $_domain will be empty or comtain the domain (subdomain from url)
* #var string can be empty
*/
protected static $_domain;
/**
* $_scope shall be 'global' or 'tenant'.
* #var string
*/
protected static $_scope;
/**
* #var null|object \App\Model\Entity\Tenant
*/
protected static $_tenant;
/**
* Gets domain from $_domain and returns the string
* #return string
*/
public static function getDomain()
{
return self::$_domain;
}
/**
* Set the tenant scope domain. Will be set in the TenantMiddleware, and shall not be set anywhere else
* #param string $domain
* #return string empty or with domain
*/
public static function setDomain($domain)
{
self::$_domain = $domain;
}
/**
* Tenant method
* Return the object \App\Model\Table\Tenants ro null
* #return type
*/
public static function tenant()
{
$tenant = static::_getTenant();
return $tenant;
}
protected static function _getTenant()
{
if (self::$_tenant === null) {
$cachedTenants = Cache::read('tenants');
if($cachedTenants !== false) {
// do something
}
$tenantsTable = TableRegistry::get('Tenants');
$tenant = $tenantsTable->find('all', ['skipTenantCheck' => true])
->where(['Tenants.domain' => self::getDomain()])
->where(['Tenants.active' => true])
->first();
self::$_tenant = $tenant;
}
return self::$_tenant;
}
public static function getScope()
{
return self::$_scope;
}
/**
* Description
* #param type $scope
* #return type
*/
public static function setScope($scope)
{
self::$_scope = $scope;
}
when I try to seed database using php artisan db:seed
following exception is occured
Array to string conversion (SQL: insert into users (name, email, password, remember_token, verified, verification_token, admin, updated_at, created_at) values (Rosanna Nicolas, kuhn.wilhelm#example.net, $2y$10$bW.zAFI2rZaLSUKIsqoPLu24nH
otRIHRQkXYyKu8QwdcWRaOzblsC, l6ERPG47fC, 1, , 0, 2018-03-03 20:40:07, 2018-03-03 20:40:07))
this is my ModelFactory.php file
$factory->define(User::class, function (Faker\Generator $faker) {
static $password;
return [
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'password' => $password ?: $password = bcrypt('secret'),
'remember_token' => str_random(10),
'verified' => $verified = $faker->randomElement([User::VERIFIED_USER,User::UNVERIFIED_USER]),
'verification_token' => $verified == User::VERIFIED_USER ? null : User::generateVerificationCode(),
'admin' => $verified = $faker->randomElements([User::ADMIN_USER, User::REGULAR_USER]),
];});
this is my migration code
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->string('verified')->default(User::UNVERIFIED_USER);
$table->string('verification_token')->nullable();
$table->string('admin')->default(User::REGULAR_USER);
$table->timestamps();
});
}
this is my seeder class
public function run()
{
DB::statement('SET FOREIGN_KEY_CHECKS = 0');
User::truncate();
Category::truncate();
Product::truncate();
Transaction::truncate();
DB::table('category_product') -> truncate();
$usersQuantity = 200;
$categoriesQuantity = 30;
$productsQuantity = 1000;
$transactionsQuantity = 1000;
factory(User::class, $usersQuantity)->create();
factory(Category::class, $categoriesQuantity)->create();
factory(Product::class, $productsQuantity)->create()->each(
function ($product) {
$categories = Category::all()->random(mt_rand(1, 5))->pluck('id');
$product->categories()->attach($categories);
});
factory(Transaction::class, $transactionsQuantity)->create();
}
and this is the model
class User extends Authenticatable{
use Notifiable;
const VERIFIED_USER = '1';
const UNVERIFIED_USER = '0';
const ADMIN_USER = '1';
const REGULAR_USER = '0';
protected $table = 'users';
protected $fillable = [
'name',
'email',
'password',
'verified',
'verification_token',
'admin',
];
protected $hidden = [
'password',
'remember_token',
'verification_token',
];
public function isVerified(){
return $this->verified == User::VERIFIED_USER;
}
public function isAdmin(){
return $this->admin == User::ADMIN_USER;
}
public static function generateVerificationCode(){
return str_random(40);
}
anyone can give the solution it will be grateful. !
Well for starters the randomElements function returns an array, not a string.
I am a newbie in Laravel, so everything is under exploration period. I use angular http post to send data over to laravel and in laravel controller i am able to
dd($request)
Request {#40
#json: ParameterBag {#32
#parameters: array:4 [
"GPTour_id" => 1
"customer_id" => 1
"status" => "Confirmed"
"note" => "asdfasdf"
]
}
#userResolver: Closure {#300
class: "Illuminate\Auth\AuthServiceProvider"
this: AuthServiceProvider {#22 …}
use: array:1 [
"$app" => Application {#3
#basePath: "/Users/haophung/Dropbox/server/websites/nglaravelyep/laravel-backend"
#hasBeenBootstrapped: true
#booted: true
#bootingCallbacks: []
However, if i use
$request->input('key')
i got $request is undefined. Please advise!!!
public function addGospelCustomer(Request $request)
{
if ($request) {
$customer_id = $request->get('customer_id');
$tour_id = $request->get('GPTour_id');
$validator = Validator::make($request->all(), [
'customer_id' =>'required'
]);
if ($validator->fails()) {
return response()->json(['error' => $validator->errors()], 406);
}
$gospel_customer = Gospel_tour::find($tour_id)->with(['customers' => function($query) {
$query->where('id', $customer_id);
}])->first();
if ($gospel_customer === 'null') {
return response()->json(['error' => "The Customer is already on the list"], 406);
}
return 'success';//response()->json(['success' => $request], 200);
}else {
return response()->json(['error' =>'can not add customer'], 401);
}
}
ErrorException in GospelController.php line 60:
Undefined variable: customer_id
I think the problem is
$gospel_customer = Gospel_tour::find($tour_id)->with(['customers' => function($query) {
$query->where('id', $customer_id);
}])->first();
I can echo $customer_id out, but in this eloquent is not defined
You need to typehint requestion in your function definition
public function name(Request $request) {}
And use it like
$key = $request->key;
$key = $request->get('key');
Or use the global function
$key = request('key');
Update
Where you have the error exception do
$gospel_customer = Gospel_tour::find($tour_id)->with(['customers' => function($query) use ($customer_id) {
$query->where('id', $customer_id);
}]);
The error occurs because you are inside a closure, and it doesn't have access to external variables.