1.先去微信开放平台注册账号,然后创建应用,签名工具下载(在页面最下面),不细说。
创建成功得到appid和secret(注册到微信、获取参数什么的都会用到)
有个注意点,就是添加应用的时候会要签名,你测试的签名跟线上的签名不一样,会出现测试环境下可以调起微信,但是线上发布的不行,原因就是签名的问题,注意及时更换。
2.配置环境,添加依赖
dependencies {
compile 'com.tencent.mm.opensdk:wechat-sdk-android-with-mta:+'
}
或
dependencies {
compile 'com.tencent.mm.opensdk:wechat-sdk-android-without-mta:+'
}
(其中,前者包含统计功能)
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
4.注册到微信(在需要的地方调用,比如onCreate)
private static final String APP_ID = "wx......";
private IWXAPI api;
private void regToWx() {
api = WXAPIFactory.createWXAPI(this, APP_ID, true);
api.registerApp(APP_ID);
}
5.调用微信登录授权
private void wxLogin() {
// send oauth request
SendAuth.Req req = new SendAuth.Req();
req.scope = "snsapi_userinfo";
req.state = "wechat_sdk_demo_test";
api.sendReq(req);
}
public class WXEntryActivity extends Activity implements IWXAPIEventHandler
WXEntryActivity是微信回调的一个类,通常给个透明的主题或者处理完业务逻辑就直接finish。
这个回调是有点绕的(用第三方集成的话就没有这么麻烦...),需要在回调中拿到code,然后再根据code去获取AccessToken,然后再根据AccessToken和OpenId去获取UserInfo。(根据固定的url和参数去请求就能拿到,下面的代码也可以直接用,改改参数就行,请求方式也没有特别要求,官网要求get,反手一个post也拿到了...)
在onCreate中
// 通过WXAPIFactory工厂,获取IWXAPI的实例
api = WXAPIFactory.createWXAPI(this, GlobalConstant.APP_ID, false);
api.handleIntent(getIntent(), this);
// 微信发送请求到第三方应用时,会回调到该方法
@Override
public void onReq(BaseReq baseReq) {
LogUtil.i("onReq" + baseReq.getType());
}
// 第三方应用发送到微信的请求处理后的响应结果,会回调到该方法
@Override
public void onResp(BaseResp baseResp) {
// baseresp.getType 1:第三方授权, 2:分享
// Toast.makeText(this, "baseresp.getType = " + baseResp.getType(), Toast.LENGTH_SHORT).show();
int result = 0;
switch (baseResp.errCode) {
case BaseResp.ErrCode.ERR_OK:
result = R.string.errcode_success;//发送成功
String code = ((SendAuth.Resp) baseResp).code;
LogUtil.i(code);
getAccessToken(code);
break;
case BaseResp.ErrCode.ERR_USER_CANCEL://发送取消
result = R.string.errcode_cancel;
finish();
break;
case BaseResp.ErrCode.ERR_AUTH_DENIED://发送被拒绝
result = R.string.errcode_deny;
break;
case BaseResp.ErrCode.ERR_UNSUPPORT:
result = R.string.errcode_unsupported;//不支持错误
break;
default:
result = R.string.errcode_unknown;//发送返回
break;
}
Toast.makeText(this, result, Toast.LENGTH_LONG).show();
}
/**
* @param code 根据code再去获取AccessToken
*/
private void getAccessToken(String code) {
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
HttpUtil httpUtil = new HttpUtil();
Map<String, String> params = new HashMap<>();
params.put("appid", GlobalConstant.APP_ID);
params.put("secret", GlobalConstant.SECRET);
params.put("code", code);
params.put("grant_type", "authorization_code");
httpUtil.postRequest(url, params, new MyStringCallBack() {
@Override
public void onError(Call call, Exception e, int id) {
super.onError(call, e, id);
}
@Override
public void onResponse(String response, int id) {
LogUtil.i(response);
AccessToken mAccessToken = GsonUtil.GsonToBean(response, AccessToken.class);
getUserInfo(mAccessToken.access_token, mAccessToken.openid);
}
});
}
/**
* @param access_token 根据access_token再去获取UserInfo
*/
private void getUserInfo(String access_token, String openid) {
String url = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
HttpUtil httpUtil = new HttpUtil();
Map<String, String> params = new HashMap<>();
params.put("access_token", access_token);
params.put("openid", openid);
httpUtil.postRequest(url, params, new MyStringCallBack() {
@Override
public void onError(Call call, Exception e, int id) {
super.onError(call, e, id);
}
@Override
public void onResponse(String response, int id) {
LogUtil.i(response);
WXUserInfo mWXUserInfo = GsonUtil.GsonToBean(response, WXUserInfo.class);
......
finish();
}
});
}
到此登录授权就结束了
7.微信分享
关于分享的介绍:官方文档,以分享网页为例
private void shareWebPage() {
//初始化一个WXWebpageObject对象,填写url
WXWebpageObject wxWebpageObject = new WXWebpageObject();
wxWebpageObject.webpageUrl = "www.baidu.com";
//用WXWebpageObject对象初始化一个WXMediaMessage对象,填写标题和描述
WXMediaMessage wxMediaMessage = new WXMediaMessage(wxWebpageObject);
wxMediaMessage.title = "网页标题";
wxMediaMessage.description = "网页描述";
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.icon);//图标
wxMediaMessage.thumbData = bmpToByteArray(bitmap, true);
//构造一个Req
SendMessageToWX.Req req = new SendMessageToWX.Req();
req.transaction = buildTransaction("webpage");//transaction字段用于唯一标示的一个请求
req.message = wxMediaMessage;
req.scene = SendMessageToWX.Req.WXSceneSession;//发送到聊天界面——WXSceneSession
//调用api接口发送数据到微信
api.sendReq(req);
}
附上两个上面用到的方法:
private String buildTransaction(final String type) {
return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
}
public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
ByteArrayOutputStream output = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
if (needRecycle) {
bmp.recycle();
}
byte[] result = output.toByteArray();
try {
output.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
发送到聊天界面——WXSceneSession
发送到朋友圈——WXSceneTimeline
添加到微信收藏——WXSceneFavorite
需要就都写上
流程稍微繁琐,但是没有难度,很多人都说官方文档写的不清不楚,毕竟写文档的人跟没用过的人视角不一样,所以还是多看看文档吧。