I already did a server-side setup for Paypal Payments. I get the product price from the Html form and then creates a payment with paypalrestsdk module. Important Chunk of code from the whole system is here:-
payment = paypalrestsdk.Payment({
"intent": "sale",
# Set payment method
"payer": {
"payment_method": "paypal"
},
# Set redirect URLs
"redirect_urls": {
"return_url": url_for('after_payment_done_2_sol', hash_id=hash_id, user_id=current_user.user_id, _external=True),
"cancel_url": url_for('topup', _external=True)
},
# Set transaction object
"transactions": [{
"amount": {
"total": query.total_price,
"currency": "USD"
},
"description": f"Payment Method for paying {query.total_price} for Top Up"
}]
})
if payment.create():
print('Payment "{}" created successfully'.format(payment.id))
for link in payment.links:
if link.method == "REDIRECT":
redirect_url = str(link.href)
print('Redirect for approval: {}'.format(redirect_url))
return redirect(redirect_url)
So this will create a link to "Pay X Amount via Paypal". But i want to integrate smart Buttons like here
https://developer.paypal.com/demo/checkout/#/pattern/server. Now here there is a codeblocks like:
<script>
// Render the PayPal button into #paypal-button-container
paypal.Buttons({
// How Does this work?????????????????????
// Set up the transaction
createOrder: function(data, actions) {
return fetch('/demo/checkout/api/paypal/order/create/', {
method: 'post'
}).then(function(res) {
return res.json();
}).then(function(data) {
return data.orderID;
});
},
// ???????????????????????????????????????? How does this Work?????
// Finalize the transaction
onApprove: function(data, actions) {
return fetch('/demo/checkout/api/paypal/order/' + data.orderID + '/capture/', {
method: 'post'
}).then(function(res) {
return res.json();
}).then(function(details) {
// Show a success message to the buyer
alert('Transaction completed by ' + details.payer.name.given_name + '!');
});
}
}).render('#paypal-button-container');
</script>
So here how does onAprrove and createOrder Works? And how should i set up my route in flask? Any help Please!
That is a server-side integration, so /demo/.... needs to be replaced with URLs that will trigger server-side code, on your webserver.
If you want javascript for a client-side integration, use https://developer.paypal.com/demo/checkout/#/pattern/client
Related
I'm making an app, and i already have a server running in my local. I can acess trought my navigator the url:
Request URL: http://localhost:4444/categorie?page_size=15&page=1
Request Method: GET
Status Code: 200 OK
Remote Address: 127.0.0.1:4444
Referrer Policy: no-referrer-when-downgrade
Preview:
{
"count": 4,
"next": null,
"previous": null,
"results": [
{
"uid": "_b656062d3754",
"name": "Pinga"
},
{
"uid": "_0c644473c244",
"name": "Cerveja"
},
{
"uid": "_75df557ccbaa",
"name": "Vinhos"
},
{
"uid": "_8e32ce3baded",
"name": "Refrigerantes"
}
]
}
But when i try in flutter, the request never respond:
getCategories() async {
String url = 'http://localhost:4444/categorie?page_size=15&page=1';
var response = await http.get(url);
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON
return response.body;
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
I'm running the server in my Windows10 using Django. And my flutter app is in the Android Studio using a Virtual Machine as device.
I tryed to change the ip to 127.0.0.1 and 10.0.0.1 but still not working. Have i change the host of Django or enable any configuration in my flutter or inside VirutalBox?
Request to other sites is working well. The problem is in local.
My dependencies:
environment:
sdk: ">=2.1.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.2
http: any
dev_dependencies:
flutter_test:
sdk: flutter
Your localhost on your PC is not the same on your Android emulator. To access your PC's localhost from the Android emulator, you need to point to 10.0.2.2.
This means that you need to change your code to:
String url = 'http://10.0.2.2:4444/categorie?page_size=15&page=1';
Use this in pubspec file under dependencies:
http: ^0.12.0+2
Use this method for Http request
getCategories() async {
final response = await http.get("http://localhost:4444/categorie?page_size=15&page=1",
headers: {
'content-type': 'application/json',
},
);
if (response.statusCode == 200) {
final result = json.decode(response.body);
var list = result['results'] as List;
// make a model class
List<Categories> categories_= list.map((i) => Categories.fromJson(i)).toList();
setState(() => {
// update value
});
} else {
setState(() => {
// Show error
});
}
}
Model class:
class Categories{
String uid;
String name;
Categories({this.uid, this.name});
Categories.fromJson(Map<String, dynamic> json) {
uid = json['uid'];
name = json['name'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['uid'] = this.uid;
data['name'] = this.name;
return data;
}
}
I am new to Vue but have experience with Django. I am using this boilerplate from Github: https://github.com/gtalarico/django-vue-template
I really like the structure of that boilerplate because it is not overwelming at all and not a lot of code is written to succesfully interact with the back-end API of Django.
It has GET, POST & DELETE already pre-installed and connected to Django REST. So far so good. However I try to add a PUT method to it so I can update models. I try to follow the same structure but I can't get it to work.
My productService.js:
import api from '#/services/api'
export default {
fetchProducts() {
return api.get(`products/`)
.then(response => response.data)
},
postProduct(payload) {
return api.post(`products/`, payload)
.then(response => response.data)
},
deleteProduct(proId) {
return api.delete(`products/${proId}`)
.then(response => response.data)
},
updateProduct(proId) {
return api.put(`products/${proId}`)
.then(response => response.data)
}
}
The updateProduct is the new code I added.
Then in store --> products.js:
const actions = {
getProducts ({ commit }) {
productService.fetchProducts()
.then(products => {
commit('setProducts', products)
})
},
addProduct({ commit }, product) {
productService.postProduct(product)
.then(() => {
commit('addProduct', product)
})
},
deleteProduct( { commit }, proId) {
productService.deleteProduct(proId)
commit('deleteProduct', proId)
},
updateProduct( { commit }, proId) {
productService.updateProduct(proId)
commit('updateProduct', proId)
}
}
const mutations = {
setProducts (state, products) {
state.products = products
},
addProduct(state, product) {
state.products.push(product)
},
deleteProduct(state, proId) {
state.products = state.products.filter(obj => obj.pk !== proId)
},
updateProduct(state, proId) {
state.products = state.products.filter(obj => obj.pk !== proId)
}
}
Here again I added updateProduct.
Then in my Products.vue:
......
<b-tbody>
<b-tr v-for="(pro, index) in products" :key="index">
<b-td>{{ index }}</b-td>
<b-td variant="success">{{ pro.name }}</b-td>
<b-td>{{ pro.price }}</b-td>
<b-td>
<b-button variant="outline-primary" v-b-modal="'myModal' + index">Edit</b-button>
<b-modal v-bind:id="'myModal' + index" title="BootstrapVue">
<input type="text" :placeholder="pro.name" v-model="name">
<input type="number" :placeholder="pro.price" v-model="price">
<b-button type="submit" #click="updateProduct(pro.pk)" variant="outline-primary">Update</b-button>
</b-modal>
</b-td>
<b-td><b-button #click="deleteProduct(pro.pk)" variant="outline-primary">Delete</b-button></b-td>
</b-tr>
.....
<script>
import { mapState, mapActions } from 'vuex'
export default {
name: "Products",
data() {
return {
name: "",
price: "",
};
},
computed: mapState({
products: state => state.products.products
}),
methods: mapActions('products', [
'addProduct',
'deleteProduct',
'updateProduct'
]),
created() {
this.$store.dispatch('products/getProducts')
}
};
</script>
Everything works fine except the PUT action to update a product. I figured that you have to use the ID of a product to be able to edit it with PUT. So that's why I used the same snippet as DELETE. But right now I am still deleting it instead of editing.
I also used now placeholder to display the text of a product entry, which is also not the correct way.. I want to use the modal to edit a product entry and then update it.
Can someone point me in the right direction?
I am using Skype Web SDK with ionic.
I have two buttons in app after login like "Idle" and "Busy". When I click on it, its changing status of user on Skype for business o365 accordingly.
Now, When I run the app, After login, its work well for first one hour or so and then the app stops reflecting status on Skype For Business.
I get 404 - not found error once it stops updating status.
POST https://webpooldb41e02.infra.lync.com/ucwa/oauth/v1/applications/1145363530/me/reportMyActivity 404 (Not Found)
below is the code I am using for authentication,
let authContext = new Microsoft.ADAL.AuthenticationContext("https://login.windows.net/common");
authContext.acquireTokenSilentAsync("https://graph.windows.net", "Client_id")
.then(function(res) {
console.log(res);
cordova.plugins.backgroundMode.disableWebViewOptimizations();
Skype.initialize({
apiKey: 'Api Key'
}, function (api) {
console.log(new Date().toLocaleString()+" 2");
console.log(api.UIApplicationInstance);
//console.log(this.ucwaData);
window.skypeWebApp = "";
window.skypeWebApp = api.UIApplicationInstance;
window.skypeWebApp.signInManager.signIn({
"client_id": client_id,
"origins": ["https://webdir.online.lync.com/autodiscover/autodiscoverservice.svc/root"],
"cors": true,
"version": 'SkypeOnlinePreviewApp/1.0.0',
"redirect_uri": 'https://login.microsoftonline.com/common/oauth2/nativeclient'
}).then(function () {
console.log(new Date().toLocaleString()+" done");
});
}, function (err) {
console.log(new Date().toLocaleString()+" 3");
console.log(err);
});
}, function () {
cordova.plugins.backgroundMode.disableWebViewOptimizations();
// We require user credentials so triggers authentication dialog
authContext.acquireTokenAsync("https://graph.windows.net", "client_id", "https://login.microsoftonline.com/common/oauth2/nativeclient")
.then(function(res){
if (typeof(document.getElementById("login_with_office")) != 'undefined' && document.getElementById("login_with_office") != null)
{
document.getElementById("login_with_office").innerHTML = "Please wait … Connecting";
}
console.log(res);
//document.getElementById("login_with_office").setAttribute('disabled', 'disabled');
ctrl.loginwitho365();
}, function (err) {
console.log(new Date().toLocaleString()+" Failed to authenticate: " + err);
});
});
And Below is the code I am using for updating status,
window.skypeWebApp.signInManager.state.get().then(function (stat) {
if(stat == "SignedIn")
{
window.skypeWebApp.personsAndGroupsManager.mePerson.status.set(availability);
}
else
{
//Signin COde
}
});
I'm setting up unit tests on my Sails application's models, controllers and services.
I stumbled upon a confusing issue, while testing my User model. Excerpt of User.js:
module.exports = {
attributes: {
username: {
type: 'string',
required: true
},
[... other attributes...] ,
isAdmin: {
type: 'boolean',
defaultsTo: false
},
toJSON: function() {
var obj = this.toObject();
// Don't send back the isAdmin attribute
delete obj.isAdmin;
delete obj.updatedAt;
return obj;
}
}
}
Following is my test.js, meant to be run with mocha. Note that I turned on the pluralize flag in blueprints config. Also, I use sails-ember-blueprints, in order to have Ember Data-compliant blueprints. So my request has to look like {user: {...}}.
// Require app factory
var Sails = require('sails/lib/app');
var assert = require('assert');
var request = require('supertest');
// Instantiate the Sails app instance we'll be using
var app = Sails();
var User;
before(function(done) {
// Lift Sails and store the app reference
app.lift({
globals: true,
// load almost everything but policies
loadHooks: ['moduleloader', 'userconfig', 'orm', 'http', 'controllers', 'services', 'request', 'responses', 'blueprints'],
}, function() {
User = app.models.user;
console.log('Sails lifted!');
done();
});
});
// After Function
after(function(done) {
app.lower(done);
});
describe.only('User', function() {
describe('.update()', function() {
it('should modify isAdmin attribute', function (done) {
User.findOneByUsername('skippy').exec(function(err, user) {
if(err) throw new Error('User not found');
user.isAdmin = false;
request(app.hooks.http.app)
.put('/users/' + user.id)
.send({user:user})
.expect(200)
.expect('Content-Type', /json/)
.end(function() {
User.findOneByUsername('skippy').exec(function(err, user) {
assert.equal(user.isAdmin, false);
done();
});
});
});
});
});
});
Before I set up a policy that will prevent write access on User.isAdmin, I expect my user.isAdmin attribute to be updated by this request.
Before running the test, my user's isAdmin flag is set to true. Running the test shows the flag isn't updated:
1) User .update() should modify isAdmin attribute:
Uncaught AssertionError: true == false
This is even more puzzling since the following QUnit test, run on client side, does update the isAdmin attribute, though it cannot tell if it was updated, since I remove isAdmin from the payload in User.toJSON().
var user;
module( "user", {
setup: function( assert ) {
stop(2000);
// Authenticate with user skippy
$.post('/auth/local', {identifier: 'skippy', password: 'Guru-Meditation!!'}, function (data) {
user = data.user;
}).always(QUnit.start);
}
, teardown: function( assert ) {
$.get('/logout', function(data) {
});
}
});
asyncTest("PUT /users with isAdmin attribute should modify it in the db and return the user", function () {
stop(1000);
user.isAdmin = true;
$.ajax({
url: '/users/' + user.id,
type: 'put',
data: {user: user},
success: function (data) {
console.log(data);
// I can not test isAdmin value here
equal(data.user.firstName, user.firstName, "first name should not be modified");
start();
},
error: function (reason) {
equal(typeof reason, 'object', 'reason for failure should be an object');
start();
}
});
});
In the mongoDB console:
> db.user.find({username: 'skippy'});
{ "_id" : ObjectId("541d9b451043c7f1d1fd565a"), "isAdmin" : false, ..., "username" : "skippy" }
Yet even more puzzling, is that commenting out delete obj.isAdmin in User.toJSON() makes the mocha test pass!
So, I wonder:
Is the toJSON() method on Waterline models only used for output filtering? Or does it have an effect on write operations such as update().
Might this issue be related to supertest? Since the jQuery.ajax() in my QUnit test does modify the isAdmin flag, it is quite strange that the supertest request does not.
Any suggestion really appreciated.
Hello i have a to do list on my sencha application and i want to add an item at this list.
This list is provided by web service with database data
when i add an item ,i can retrieve him on my database but the list isn't refresh and i don't understand how to do this.
Someone can help me ?
here my list:
config: {
id:'Listetaches',
grouped:true,
store:'PokerStore',
sorters:'Tache_Libelle',
itemTpl:'{Tache_Libelle} <br/> Durée estimé : {Tache_Estimation} h',
onItemDisclosure :true
}
here my store:
config:{
model:'PlanningPoker.model.Poker',
autoLoad:true,
id:'storeList',
grouper: function(record){
return record.get('Tache_Libelle')[0];
},
proxy:{
type:'ajax',
url:'Myurl',
useDefaultXhrHeader : false,
reader:{
type:'json',
},
},
autoSync: true,
}
here my controller where i add an item
onAddtache: function(button, e, options) {
var libelle=Ext.getCmp('libelle').getValue();
var description=Ext.getCmp('description').getValue();
Ext.Ajax.request({
url: 'Myurl',
method: 'POST',
useDefaultXhrHeader : false,
params: {
Libelle: libelle,
Description:description,
},
callback: function(options, success, response) {
console.log(response.responseText);
button.up('navigationview').pop();
}
});
},
I think you have to reload your store again after adding an item.
Step 1: On your application the store loads the data from the database. (The data is saved locally)
Step 2 :Then you add a new item to your database, but the store still has the data of Step 1.
Add a store.load() or store.sync() to the callback of your Ajax request
callback: function(options, success, response) {
console.log(response.responseText);
button.up('navigationview').pop();
Ext.getStore('PokerStore').load();
}