饿了么开放平台商家应用授权认证认证服务器向客户端发送访问令牌
c、认证服务器向客户端发送访问令牌,HTTP返回示例如下:
HTTP/1.1 200 OK Content-Type: application/json;charset=UTF-8 Content-Length: 113 { "access_token": "c199e3dc2705388f927e27d5ea6833d4", "trace_id": "fe.sopush_service^^5D77063E0EAC493A89780BBC3AEDB332|1703038197150", "token_type": "Bearer", "expires_in": 2592000 }
返回值字段说明:
字段名 | 类型 | 释义 |
---|---|---|
access_token | String | 访问令牌,API调用时需要,请开发者全局变量保存,不要局部保存 |
trace_id | String | 用来唯一标记此次调用,排查问题时可提供此信息 |
token_type | String | 令牌类型,固定值,开发者可忽略 |
expires_in | Number | 令牌的有效时间,单位秒 |
示例代码
java-sdk
package me.ele.demo; import eleme.openapi.sdk.api.exception.ServiceException; import eleme.openapi.sdk.config.Config; import eleme.openapi.sdk.oauth.OAuthClient; import eleme.openapi.sdk.oauth.response.Token; public class getToken { public static void main(String[] args) throws ServiceException { // 变量为true: 沙箱环境 false: 生产环境 boolean isSandbox = false; // 当前环境key String appKey = "xxx"; // 当前环境secret String appSecret = "xxxx"; // 实例化一个配置类 Config config = new Config(isSandbox, appKey, appSecret); // 使用config对象,实例化一个授权类 OAuthClient client = new OAuthClient(config); // 使用授权类获取token Token token = client.getTokenInClientCredentials(); if (token.isSuccess()) { System.out.println(token); System.out.println(token); } else { System.out.println("error_code: " + token.getError()); System.out.println("error_desc: " + token.getError_description()); } } }
CURL
curl --location --request POST 'https://open-api-sandbox.shop.ele.me/token' \ --header 'Authorization: Basic XXXXXXXX' \ --header 'Host: open-api-sandbox.shop.ele.me' \ --header 'Content-Type: application/x-www-form-urlencoded' \ --data-urlencode 'grant_type=client_credentials'
java(OkHttp)
package org.ele.demo; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.FormBody; import java.io.IOException; import java.util.concurrent.TimeUnit; public class okhttpbrandGetToken { public static void main(String[] args) { OkHttpClient client = new OkHttpClient().newBuilder() .connectTimeout(10, TimeUnit.SECONDS) // 添加连接超时 .readTimeout(10, TimeUnit.SECONDS) // 添加读取超时 .writeTimeout(10, TimeUnit.SECONDS) // 添加写入超时 .build(); // 使用 FormBody.Builder 构建表单数据 FormBody formBody = new FormBody.Builder() .add("grant_type", "client_credentials") .build(); Request request = new Request.Builder() .url("https://open-api.shop.ele.me/token") // 修改为正式环境地址 .post(formBody) // 直接使用 post 方法 .addHeader("Authorization", "Basic XXXXXX") .addHeader("Host", "open-api.shop.ele.me") // 修改为正式环境 Host .build(); // Content-Type 会由 FormBody 自动添加 try { Response response = client.newCall(request).execute(); // 处理响应 if (response.isSuccessful()) { String responseBody = response.body().string(); // 处理响应内容 System.out.println(responseBody); } } catch (IOException e) { e.printStackTrace(); } } }