Parcourir la source

抽取公众号部分微信请求URL到常量类中 #195

master
Binary Wang il y a 8 ans
Parent
révision
bb83ead12c
5 fichiers modifiés avec 139 ajouts et 101 suppressions
  1. +90
    -0
      weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpApiUrls.java
  2. +25
    -71
      weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/AbstractWxMpServiceImpl.java
  3. +12
    -13
      weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/apache/WxMpServiceImpl.java
  4. +2
    -3
      weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/jodd/WxMpServiceImpl.java
  5. +10
    -14
      weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/okhttp/WxMpServiceImpl.java

+ 90
- 0
weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpApiUrls.java Voir le fichier

@@ -0,0 +1,90 @@
package me.chanjar.weixin.mp.api;

/**
* <pre>
* 公众号相关接口URL常量类
* Created by Binary Wang on 2017-4-28.
* @author <a href="https://github.com/binarywang">binarywang(Binary Wang)</a>
* </pre>
*/
public class WxMpApiUrls {
/**
* 获取access_token
*/
public static final String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";

/**
* 获得jsapi_ticket
*/
public static final String GET_JSAPI_TICKET_URL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi";

/**
* 上传群发用的图文消息
*/
public static final String MEDIA_UPLOAD_NEWS_URL = "https://api.weixin.qq.com/cgi-bin/media/uploadnews";

/**
* 上传群发用的视频
*/
public static final String MEDIA_UPLOAD_VIDEO_URL = "https://api.weixin.qq.com/cgi-bin/media/uploadvideo";

/**
* 分组群发消息
*/
public static final String MESSAGE_MASS_SENDALL_URL = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall";

/**
* 按openId列表群发消息
*/
public static final String MESSAGE_MASS_SEND_URL = "https://api.weixin.qq.com/cgi-bin/message/mass/send";

/**
* 群发消息预览接口
*/
public static final String MESSAGE_MASS_PREVIEW_URL = "https://api.weixin.qq.com/cgi-bin/message/mass/preview";

/**
* 长链接转短链接接口
*/
public static final String SHORTURL_API_URL = "https://api.weixin.qq.com/cgi-bin/shorturl";

/**
* 语义查询接口
*/
public static final String SEMANTIC_SEMPROXY_SEARCH_URL = "https://api.weixin.qq.com/semantic/semproxy/search";

/**
* 用code换取oauth2的access token
*/
public static final String OAUTH2_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";

/**
* 刷新oauth2的access token
*/
public static final String OAUTH2_REFRESH_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=%s&grant_type=refresh_token&refresh_token=%s";

/**
* 用oauth2获取用户信息
*/
public static final String OAUTH2_USERINFO_URL = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=%s";

/**
* 验证oauth2的access token是否有效
*/
public static final String OAUTH2_VALIDATE_TOKEN_URL = "https://api.weixin.qq.com/sns/auth?access_token=%s&openid=%s";

/**
* 获取微信服务器IP地址
*/
public static final String GET_CALLBACK_IP_URL = "https://api.weixin.qq.com/cgi-bin/getcallbackip";

/**
* 第三方使用网站应用授权登录的url
*/
public static final String QRCONNECT_URL = "https://open.weixin.qq.com/connect/qrconnect?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect";

/**
* oauth2授权的url连接
*/
public static final String CONNECT_OAUTH2_AUTHORIZE_URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect";
}

+ 25
- 71
weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/AbstractWxMpServiceImpl.java Voir le fichier

@@ -15,6 +15,7 @@ import me.chanjar.weixin.common.util.http.*;
import me.chanjar.weixin.mp.api.*;
import me.chanjar.weixin.mp.bean.*;
import me.chanjar.weixin.mp.bean.result.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@@ -70,8 +71,7 @@ public abstract class AbstractWxMpServiceImpl<H, P> implements WxMpService, Requ
}

if (this.getWxMpConfigStorage().isJsapiTicketExpired()) {
String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi";
String responseContent = execute(new SimpleGetRequestExecutor(), url, null);
String responseContent = execute(new SimpleGetRequestExecutor(), WxMpApiUrls.GET_JSAPI_TICKET_URL, null);
JsonElement tmpJsonElement = JSON_PARSER.parse(responseContent);
JsonObject tmpJsonObject = tmpJsonElement.getAsJsonObject();
String jsapiTicket = tmpJsonObject.get("ticket").getAsString();
@@ -107,93 +107,66 @@ public abstract class AbstractWxMpServiceImpl<H, P> implements WxMpService, Requ

@Override
public WxMpMassUploadResult massNewsUpload(WxMpMassNews news) throws WxErrorException {
String url = "https://api.weixin.qq.com/cgi-bin/media/uploadnews";
String responseContent = this.post(url, news.toJson());
String responseContent = this.post(WxMpApiUrls.MEDIA_UPLOAD_NEWS_URL, news.toJson());
return WxMpMassUploadResult.fromJson(responseContent);
}

@Override
public WxMpMassUploadResult massVideoUpload(WxMpMassVideo video) throws WxErrorException {
String url = "https://api.weixin.qq.com/cgi-bin/media/uploadvideo";
String responseContent = this.post(url, video.toJson());
String responseContent = this.post(WxMpApiUrls.MEDIA_UPLOAD_VIDEO_URL, video.toJson());
return WxMpMassUploadResult.fromJson(responseContent);
}

@Override
public WxMpMassSendResult massGroupMessageSend(WxMpMassTagMessage message) throws WxErrorException {
String url = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall";
String responseContent = this.post(url, message.toJson());
String responseContent = this.post(WxMpApiUrls.MESSAGE_MASS_SENDALL_URL, message.toJson());
return WxMpMassSendResult.fromJson(responseContent);
}

@Override
public WxMpMassSendResult massOpenIdsMessageSend(WxMpMassOpenIdsMessage message) throws WxErrorException {
String url = "https://api.weixin.qq.com/cgi-bin/message/mass/send";
String responseContent = this.post(url, message.toJson());
String responseContent = this.post(WxMpApiUrls.MESSAGE_MASS_SEND_URL, message.toJson());
return WxMpMassSendResult.fromJson(responseContent);
}

@Override
public WxMpMassSendResult massMessagePreview(WxMpMassPreviewMessage wxMpMassPreviewMessage) throws Exception {
String url = "https://api.weixin.qq.com/cgi-bin/message/mass/preview";
String responseContent = this.post(url, wxMpMassPreviewMessage.toJson());
String responseContent = this.post(WxMpApiUrls.MESSAGE_MASS_PREVIEW_URL, wxMpMassPreviewMessage.toJson());
return WxMpMassSendResult.fromJson(responseContent);
}

@Override
public String shortUrl(String long_url) throws WxErrorException {
String url = "https://api.weixin.qq.com/cgi-bin/shorturl";
JsonObject o = new JsonObject();
o.addProperty("action", "long2short");
o.addProperty("long_url", long_url);
String responseContent = this.post(url, o.toString());
String responseContent = this.post(WxMpApiUrls.SHORTURL_API_URL, o.toString());
JsonElement tmpJsonElement = JSON_PARSER.parse(responseContent);
return tmpJsonElement.getAsJsonObject().get("short_url").getAsString();
}

@Override
public WxMpSemanticQueryResult semanticQuery(WxMpSemanticQuery semanticQuery) throws WxErrorException {
String url = "https://api.weixin.qq.com/semantic/semproxy/search";
String responseContent = this.post(url, semanticQuery.toJson());
String responseContent = this.post(WxMpApiUrls.SEMANTIC_SEMPROXY_SEARCH_URL, semanticQuery.toJson());
return WxMpSemanticQueryResult.fromJson(responseContent);
}

@Override
public String oauth2buildAuthorizationUrl(String redirectURI, String scope, String state) {
StringBuilder url = new StringBuilder();
url.append("https://open.weixin.qq.com/connect/oauth2/authorize?");
url.append("appid=").append(this.getWxMpConfigStorage().getAppId());
url.append("&redirect_uri=").append(URIUtil.encodeURIComponent(redirectURI));
url.append("&response_type=code");
url.append("&scope=").append(scope);
if (state != null) {
url.append("&state=").append(state);
}
url.append("#wechat_redirect");
return url.toString();
return String.format(WxMpApiUrls.CONNECT_OAUTH2_AUTHORIZE_URL,
this.getWxMpConfigStorage().getAppId(), URIUtil.encodeURIComponent(redirectURI), scope, StringUtils.trimToEmpty(state));
}

@Override
public String buildQrConnectUrl(String redirectURI, String scope,
String state) {
StringBuilder url = new StringBuilder();
url.append("https://open.weixin.qq.com/connect/qrconnect?");
url.append("appid=").append(this.getWxMpConfigStorage().getAppId());
url.append("&redirect_uri=").append(URIUtil.encodeURIComponent(redirectURI));
url.append("&response_type=code");
url.append("&scope=").append(scope);
if (state != null) {
url.append("&state=").append(state);
}

url.append("#wechat_redirect");
return url.toString();
public String buildQrConnectUrl(String redirectURI, String scope, String state) {
return String.format(WxMpApiUrls.QRCONNECT_URL,
this.getWxMpConfigStorage().getAppId(), URIUtil.encodeURIComponent(redirectURI), scope, StringUtils.trimToEmpty(state));
}

private WxMpOAuth2AccessToken getOAuth2AccessToken(StringBuilder url) throws WxErrorException {
private WxMpOAuth2AccessToken getOAuth2AccessToken(String url) throws WxErrorException {
try {
RequestExecutor<String, String> executor = new SimpleGetRequestExecutor();
String responseText = executor.execute(this, url.toString(), null);
String responseText = executor.execute(this, url, null);
return WxMpOAuth2AccessToken.fromJson(responseText);
} catch (IOException e) {
throw new RuntimeException(e);
@@ -202,42 +175,27 @@ public abstract class AbstractWxMpServiceImpl<H, P> implements WxMpService, Requ

@Override
public WxMpOAuth2AccessToken oauth2getAccessToken(String code) throws WxErrorException {
StringBuilder url = new StringBuilder();
url.append("https://api.weixin.qq.com/sns/oauth2/access_token?");
url.append("appid=").append(this.getWxMpConfigStorage().getAppId());
url.append("&secret=").append(this.getWxMpConfigStorage().getSecret());
url.append("&code=").append(code);
url.append("&grant_type=authorization_code");

String url = String.format(WxMpApiUrls.OAUTH2_ACCESS_TOKEN_URL, this.getWxMpConfigStorage().getAppId(), this.getWxMpConfigStorage().getSecret(), code);
return this.getOAuth2AccessToken(url);
}

@Override
public WxMpOAuth2AccessToken oauth2refreshAccessToken(String refreshToken) throws WxErrorException {
StringBuilder url = new StringBuilder();
url.append("https://api.weixin.qq.com/sns/oauth2/refresh_token?");
url.append("appid=").append(this.getWxMpConfigStorage().getAppId());
url.append("&grant_type=refresh_token");
url.append("&refresh_token=").append(refreshToken);

String url = String.format(WxMpApiUrls.OAUTH2_REFRESH_TOKEN_URL, this.getWxMpConfigStorage().getAppId(), refreshToken);
return this.getOAuth2AccessToken(url);
}

@Override
public WxMpUser oauth2getUserInfo(WxMpOAuth2AccessToken oAuth2AccessToken, String lang) throws WxErrorException {
StringBuilder url = new StringBuilder();
url.append("https://api.weixin.qq.com/sns/userinfo?");
url.append("access_token=").append(oAuth2AccessToken.getAccessToken());
url.append("&openid=").append(oAuth2AccessToken.getOpenId());
if (lang == null) {
url.append("&lang=zh_CN");
} else {
url.append("&lang=").append(lang);
lang = "zh_CN";
}

String url = String.format(WxMpApiUrls.OAUTH2_USERINFO_URL, oAuth2AccessToken.getAccessToken(), oAuth2AccessToken.getOpenId(), lang);

try {
RequestExecutor<String, String> executor = new SimpleGetRequestExecutor();
String responseText = executor.execute(this, url.toString(), null);
String responseText = executor.execute(this, url, null);
return WxMpUser.fromJson(responseText);
} catch (IOException e) {
throw new RuntimeException(e);
@@ -246,14 +204,11 @@ public abstract class AbstractWxMpServiceImpl<H, P> implements WxMpService, Requ

@Override
public boolean oauth2validateAccessToken(WxMpOAuth2AccessToken oAuth2AccessToken) {
StringBuilder url = new StringBuilder();
url.append("https://api.weixin.qq.com/sns/auth?");
url.append("access_token=").append(oAuth2AccessToken.getAccessToken());
url.append("&openid=").append(oAuth2AccessToken.getOpenId());
String url = String.format(WxMpApiUrls.OAUTH2_VALIDATE_TOKEN_URL, oAuth2AccessToken.getAccessToken(), oAuth2AccessToken.getOpenId());

try {
RequestExecutor<String, String> executor = new SimpleGetRequestExecutor();
executor.execute(this, url.toString(), null);
executor.execute(this, url, null);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (WxErrorException e) {
@@ -264,8 +219,7 @@ public abstract class AbstractWxMpServiceImpl<H, P> implements WxMpService, Requ

@Override
public String[] getCallbackIP() throws WxErrorException {
String url = "https://api.weixin.qq.com/cgi-bin/getcallbackip";
String responseContent = get(url, null);
String responseContent = this.get(WxMpApiUrls.GET_CALLBACK_IP_URL, null);
JsonElement tmpJsonElement = JSON_PARSER.parse(responseContent);
JsonArray ipList = tmpJsonElement.getAsJsonObject().get("ip_list").getAsJsonArray();
String[] ipArray = new String[ipList.size()];


+ 12
- 13
weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/apache/WxMpServiceImpl.java Voir le fichier

@@ -1,22 +1,22 @@
package me.chanjar.weixin.mp.api.impl.apache;

import java.io.IOException;
import java.util.concurrent.locks.Lock;

import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;

import me.chanjar.weixin.common.bean.WxAccessToken;
import me.chanjar.weixin.common.bean.result.WxError;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.util.http.apache.ApacheHttpClientBuilder;
import me.chanjar.weixin.common.util.http.apache.DefaultApacheHttpClientBuilder;
import me.chanjar.weixin.mp.api.WxMpApiUrls;
import me.chanjar.weixin.mp.api.WxMpConfigStorage;
import me.chanjar.weixin.mp.api.impl.AbstractWxMpServiceImpl;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;

import java.io.IOException;
import java.util.concurrent.locks.Lock;

/**
* apache-http方式实现
@@ -66,9 +66,8 @@ public class WxMpServiceImpl extends AbstractWxMpServiceImpl<CloseableHttpClient
}

if (this.getWxMpConfigStorage().isAccessTokenExpired()) {
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
"&appid=" + this.getWxMpConfigStorage().getAppId() + "&secret="
+ this.getWxMpConfigStorage().getSecret();
String url = String.format(WxMpApiUrls.GET_ACCESS_TOKEN_URL,
this.getWxMpConfigStorage().getAppId(), this.getWxMpConfigStorage().getSecret());
try {
HttpGet httpGet = new HttpGet(url);
if (this.getRequestHttpProxy() != null) {


+ 2
- 3
weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/jodd/WxMpServiceImpl.java Voir le fichier

@@ -51,9 +51,8 @@ public class WxMpServiceImpl extends AbstractWxMpServiceImpl<HttpConnectionProvi
}

if (this.getWxMpConfigStorage().isAccessTokenExpired()) {
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
"&appid=" + this.getWxMpConfigStorage().getAppId() + "&secret="
+ this.getWxMpConfigStorage().getSecret();
String url = String.format(WxMpApiUrls.GET_ACCESS_TOKEN_URL,
this.getWxMpConfigStorage().getAppId(), this.getWxMpConfigStorage().getSecret());

HttpRequest request = HttpRequest.get(url);



+ 10
- 14
weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/okhttp/WxMpServiceImpl.java Voir le fichier

@@ -1,23 +1,21 @@
package me.chanjar.weixin.mp.api.impl.okhttp;

import java.io.IOException;
import java.util.concurrent.locks.Lock;

import me.chanjar.weixin.common.bean.WxAccessToken;
import me.chanjar.weixin.common.bean.result.WxError;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.util.http.okhttp.OkhttpProxyInfo;
import me.chanjar.weixin.mp.api.*;
import me.chanjar.weixin.mp.api.impl.*;
import me.chanjar.weixin.mp.api.WxMpApiUrls;
import me.chanjar.weixin.mp.api.WxMpConfigStorage;
import me.chanjar.weixin.mp.api.impl.AbstractWxMpServiceImpl;
import okhttp3.*;

public class WxMpServiceImpl extends AbstractWxMpServiceImpl<ConnectionPool, OkhttpProxyInfo> {
import java.io.IOException;
import java.util.concurrent.locks.Lock;

public class WxMpServiceImpl extends AbstractWxMpServiceImpl<ConnectionPool, OkhttpProxyInfo> {
private ConnectionPool httpClient;
private OkhttpProxyInfo httpProxy;


@Override
public ConnectionPool getRequestHttpClient() {
return httpClient;
@@ -28,7 +26,6 @@ public class WxMpServiceImpl extends AbstractWxMpServiceImpl<ConnectionPool, Okh
return httpProxy;
}


@Override
public String getAccessToken(boolean forceRefresh) throws WxErrorException {
Lock lock = this.getWxMpConfigStorage().getAccessTokenLock();
@@ -40,9 +37,8 @@ public class WxMpServiceImpl extends AbstractWxMpServiceImpl<ConnectionPool, Okh
}

if (this.getWxMpConfigStorage().isAccessTokenExpired()) {
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
"&appid=" + this.getWxMpConfigStorage().getAppId() + "&secret="
+ this.getWxMpConfigStorage().getSecret();
String url = String.format(WxMpApiUrls.GET_ACCESS_TOKEN_URL,
this.getWxMpConfigStorage().getAppId(), this.getWxMpConfigStorage().getSecret());

OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder().connectionPool(httpClient);
//设置代理
@@ -62,8 +58,8 @@ public class WxMpServiceImpl extends AbstractWxMpServiceImpl<ConnectionPool, Okh
//得到httpClient
OkHttpClient client = clientBuilder.build();

Request request =new Request.Builder().url(url).get().build();
Response response =client.newCall(request).execute();
Request request = new Request.Builder().url(url).get().build();
Response response = client.newCall(request).execute();
String resultContent = response.body().toString();
WxError error = WxError.fromJson(resultContent);
if (error.getErrorCode() != 0) {


Chargement…
Annuler
Enregistrer