Adwords API getting customerId - google-api

I have an adwords user's Oauth credentials, and I'm able to successfully make an API call to download a report, but I had to hard-code in the customerId as I couldn't figure out how to get it.
The get() method of the CustomerService in the API should return the customer ID, but what are the parameters to pass to it?
I tried a GET request to this URL
without any header params or body params, to which it returns:
"<html><body>No service was found.</body></html>".
I also tried with an Authorization and developerToken defined in the headers, but got the same response.
I also tried the python library, and defined an instance of AdWordsClient like this, but it's client_customer_id variable ends up as None:
from googleads.adwords import AdWordsClient
oauth_client = GoogleRefreshTokenClient(environ.get('GOOGLE_CLIENT_ID'), environ.get('GOOGLE_CLIENT_SECRET'), oauth_record.refresh_token)
adwords_client = AdWordsClient(environ.get('ADWORDS_DEVELOPER_TOKEN'), oauth_client, user_agent='agent'))
customer_id = adwords_client.client_customer_id
print 'customer_id:' + str(customer_id)
Unlike this question, I don't care about adding the user to my MCC account.

Here is how to get the customer ID with the googleads-python-lib library:
oauth_client = GoogleRefreshTokenClient(environ.get('GOOGLE_CLIENT_ID'), environ.get('GOOGLE_CLIENT_SECRET'), oauth_record.refresh_token)
adwords_client = AdWordsClient(environ.get('ADWORDS_DEVELOPER_TOKEN'), oauth_client, user_agent='your_user_agent_here')
customer = adwords_client.GetService('CustomerService').get()
customer_id = customer['customerId']

from googleads import oauth2, adwords
oauth_client = oauth2.GoogleRefreshTokenClient(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, refresh_token)
adwords_client = adwords.AdWordsClient(ADWORDS_DEVELOPER_TOKEN, oauth_client, user_agent='your_user_agent')
customers = adwords_client.GetService('CustomerService', version='v201809').getCustomers()
print(customers['customer_id'])

Related

How to get payer email after a success payment wit paypal API (Laravel paypal/rest-api-sdk-php)?

I'm using the paypal API with Laravel, everything works fine. I just need to find the way to get the user email address and name.
$payment = Payment::get($payment_id, $this->_api_context);
$execution = new PaymentExecution();
$execution->setPayerId( $request->query('PayerID') );
$result = $payment->execute($execution, $this->_api_context);
if ($result->getState() == 'approved') {
// I should get the info about the payer here
}
The v1/payments PayPal-PHP-SDK is deprecated, you should not use it for any new integration.
The current supported SDK is the v2/checkout/orders Checkout-PHP-SDK, which you should use instead.
You can try the srmklive package "v3" if you like, otherwise integrate directly.
You should be able to create two routes, one for 'Create Order' and one for 'Capture Order', documented here. These routes should return only JSON data (no HTML or text). Pair those two routes with the following approval flow: https://developer.paypal.com/demo/checkout/#/pattern/server
The capture order response may have details about the payer and payment, if not use can do a 'Get' API call on the order ID for this information. Store it in your database before returning the JSON to the client code.

Getting user details from access token in Django rest framework -simple JWT

I am using React and Django rest framework for a project. I use Django rest framework simple JWT for authentication. Now, I want to display the username in the navbar after the user logs in. So, is there a way in simple JWT for returning user details from the access token generated after authentication, just like Djoser returns user credentials when supplied the access token?
Sorry if this question is silly but I was not able to find a solution to this anywhere.
if you want to obtain the information of the owner of the token you can consult it in REQUEST.
class ViewProtect(APIView):
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
def post(self, request, format=None):
token_user_email = request.user.email
token_user_username = request.user.username
pass
About the backend, basically I use this library
from restframework_simplejwt.tokens import AccessToken
The function AccessToken() take as input the string access_token_str and return the object access_token_obj.
To get the user_id, you can use the instruction
user_id=access_token_obj['user_id'].
In the following example I have created the function
get_user_from_access_token_in_django_rest_framework_simplejwt().
This function is just a wrapper around AccessToken()
Full code:
#Path current file
#/blabla/django/project004/core/view.py
from restframework_simplejwt.tokens import AccessToken
from django.contrib.auth.models import User
#Example data.
#access_token_str = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX3BrIjoxLCJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiY29sZF9zdHVmZiI6IuKYgyIsImV4cCI6MTIzNDU2LCJqdGkiOiJmZDJmOWQ1ZTFhN2M0MmU4OTQ5MzVlMzYyYmNhOGJjYSJ9.NHlztMGER7UADHZJlxNG0WSi22a2KaYSfd1S-AuT7lU'
def get_user_from_access_token_in_django_rest_framework_simplejwt(access_token_str):
access_token_obj = AccessToken(access_token_str)
user_id=access_token_obj['user_id']
user=User.objects.get(id=user_id)
print('user_id: ', user_id )
print('user: ', user)
print('user.id: ', user.id )
content = {'user_id': user_id, 'user':user, 'user.id':user.id}
return Response(content)
Credits:
#davesque;
https://github.com/jazzband/djangorestframework-simplejwt/issues/140
Update.
The string access_token_str I write in the file is just an example. You should pass it as argument.
Here's how I've done it.
On Django, I followed the steps described on this page in order to add the user's name inside the JWT token : https://django-rest-framework-simplejwt.readthedocs.io/en/latest/customizing_token_claims.html
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework_simplejwt.views import TokenObtainPairView
class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
#classmethod
def get_token(cls, user):
token = super().get_token(user)
# Add name to token
token['name'] = user.get_full_name()
# You can add other information into the token here
return token
class MyTokenObtainPairView(TokenObtainPairView):
serializer_class = MyTokenObtainPairSerializer
Then, I updated my urls.py to use the custom view:
path('token/', MyTokenObtainPairView.as_view(), name='token_obtain_pair'),
Finally, in my Vue.js application, I installed the jwt-decode package and used it like this:
const token = localStorage.getItem('access_token');
const decoded = jwt_decode(token);
console.log(decoded)
// decoded.name contains the user's full name
Note that I store the access token in the local storage beforehand.

Parameters URL with DRF routers

I'm using Django Rest Framework for created a API. In this project i want to capture parameters in the URL. For example i want to capture the username and password of a user and my idea is like this:
http://localhost:8000/accounts/login/?unsername=username&password=password
But i cant, I' usin routers and django-filter, but i cant get the parameters url. My project files are there:
view.py:
class AccountsData(viewsets.ModelViewSet):
queryset = models.UserData.objects.all()
serializer_class = serializers.AccountsDataSerializer
permission_classes = (IsAuthenticated,)
filter_backends = (filters.DjangoFilterBackend,)
filterset_fields = ['username', 'password']
lookup_url_kwarg = 'username'
#action(methods=['get'], detail=True, url_name='login', url_path='login')
def login(self, request, pk=None):
return Response({"Login successfully"}, 200)
urls.py:
from api import views
router = routers.SimpleRouter()
router.register(r'accounts', views.AccountsData)
Request query parameters have nothing to do with routing, they are passed with the request independently of how you configure the route. You have access to them in request.query_params, for example, request.query_params.get('username') would get the value of the username parameter.
Being said that, your idea has a terrible mistake: password or any kind of confidential data should NEVER go in query parameters, you should use an http verb that carries the data in its body (POST, for example).

list_comments Ruby implementation with YouTube video_id

Having trouble implementing the list_comments method in the following code example (n.b. the API is initialised successfully):
# initialize API
service = Google::Apis::YoutubeV3::YouTubeService.new
service.client_options.application_name = APPLICATION_NAME
service.authorization = authorize
response = service.list_comments('snippet, replies')
Currently the method returns the following error:
missingRequiredParameter: No filter selected. Expected one of: id, idParam, parentId (Google::Apis::ClientError)
I have successfully tested the API call here:
https://developers.google.com/youtube/v3/docs/comments/list
What I'm struggling with is when I test the API call I can pass a videoId to identify a resource, however the method implementation does not allow for this. Could anyone shed some light on how to pass a videoId to the method call?
Found the solution! The method that allows you to specify video_id (or channel_id) to select a specific resource is: list_comment_threads from the Google::Apis::YoutubeV3::YouTubeService module.
response = service.list_comment_threads('snippet', video_id: 'hy1v891n3kA').to_json

Post from Angular 5 front-end to Django Rest Framework back-end

I am trying to create a post request from Angular 5 to DRF. The field is a form that a user submits. I created the serializer and i can post something from DRF interface
models.py
class UserForm(models.Model):
id_user_form = models.AutoField(primary_key=True)
user = models.ForeignKey(User, on_delete=models.CASCADE, db_column='idUser', unique=False)
name = models.CharField(max_length=50)
type = models.CharField(max_length=25)
location = models.CharField(max_length=200)
serilizers.py
`class UserFormSerializer(serializers.ModelSerializer):
class Meta:
model = UserForm
fields = ('user', 'name', 'type', 'location')
def create(self, validated_data):
user_data = validated_data.pop('user')
user_form = UserForm.objects.create(user_id=user_data, **validated_data)
return user_form
views.py
class FormSubmit(generics.ListCreateAPIView):
queryset = UserForm.objects.all()
serializer_class = UserFormSerializer
When i try to post it via Angular I get this error:
Forbidden (CSRF token missing or incorrect.): /api/form/
Am I doing something wrong?
Had the exact same problem when I wanted to upload a profile picture to my Django REST backend.
You have 2 options, basically.
The first one is disabling the CSRF checks, which are by default enforced by DRF. Have a read here. You may do this for testing purposes.
The second option would be to pass the CSRF Token inside your request header. To do that, have a look at the $cookies API.
With that, you can get the token out of the cookie and paste it into your header like so: 'X-CSRFToken': your-csrf-token-here.
You can verify this by opening your dev tools inside the browser and navigating to your site's cookies. You should see one called csrftoken there.
I hope this sent you on the right track.

Resources