代码之家  ›  专栏  ›  技术社区  ›  user2573699

所需用户凭据:谷歌云打印提交API

  •  3
  • user2573699  · 技术社区  · 8 年前

    我试图访问提交API,这是谷歌云打印的一部分,但我遇到了错误“需要用户凭据”。

    我能够一路通过身份验证,并且能够检索我的访问令牌。我是按照这个指南做的 https://developers.google.com/cloud-print/docs/appDevGuide

    我不知道哪里出了问题。有人知道凭证应该输入到哪里吗?

    以下是我这部分的代码:

    function submitPrintJob(token){
            try{
    
                var params = {'printerid':'PRINTER_ID','title':'Test Print Job','ticket':{"version": "1.0", "print": {}},'contentType':'application/pdf'};
                var response = https.post({
                    url: 'https://www.google.com/cloudprint/submit',
                    body: params,
                    headers: {'Authorization':'Bearer ' + token}
                });
    
                log.debug('submitPrintJob','Response - ' + response.body);
            }catch(e){
                log.error('submitPrintJob','Error - ' + e.message);
            }
        }
    

    这段代码是在Netsuite中完成的,Netsuite就是https的所在地。post API即将发布。我也知道我没有发送文件,但我至少需要通过这一步。我也通过邮递员发现了这个错误。

    编辑以添加获取令牌的部分: 我将请求发送至: https://accounts.google.com/o/oauth2/v2/auth 参数: 响应类型:代码, 范围: https://www.googleapis.com/auth/cloud-platform.read-only , 状态:状态参数通过值, 重定向_uri:ScripletURL 客户id:客户id

    Google oauth返回一个授权码。我用这种方式将代码交换为令牌:

            function getToken(code){
                try{
    
                    var params = {'code':code,'client_id':CLIENT_ID,'client_secret':CLIENT_SECRET,'redirect_uri':REDIRECT_URI,'grant_type':'authorization_code'}
                    var response = https.post({
                        url: 'https://www.googleapis.com/oauth2/v4/token',
                        body: params,
                        headers: {'Content-Type':'application/x-www-form-urlencoded'}
                    });
    
                    var token = response.body.access_token;
    
                    submitPrintJob(token);
    
                }catch(e){
                    log.error('getAuthCode','Error - ' + e.message);
                }
            }
    
    1 回复  |  直到 8 年前
        1
  •  2
  •   Morfinismo    8 年前

    正如我所想,问题在于如何获得访问令牌。为了获得有效的访问令牌来开展云打印业务,您需要包含适当的范围。这意味着你的params对象应该是这样的:

    var params = {'code':code,'client_id':CLIENT_ID,'client_secret':CLIENT_SECRET,'redirect_uri':REDIRECT_URI, 'scope': 'https://www.googleapis.com/auth/cloudprint', 'grant_type':'authorization_code'}
    

    这将为您提供一个有效的访问令牌,以便与Google Cloud Print交互。我希望有帮助!