微信登录
1.前往 微信开放平台 注册账号,然后创建应用, 签名工具下载 。
创建成功得到 appid 和 secret 。
注意:添加应用的时候会要签名,你测试的签名跟线上的签名不一样,会出现测试环境下可以调起微信,但是线上发布的不行,原因就是签名的问题,注意及时更换。
- 在 app/build.gradle 中添加依赖:
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"/>
- 注册到微信(在需要的地方调用即可)
private static final String APP_ID = "wx......";
private IWXAPI api;
private void regToWx() {
api = WXAPIFactory.createWXAPI(this, APP_ID, true);
api.registerApp(APP_ID);
}
- 调用微信登录授权
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);
}
6.在包名下新建 wxapi 包和 WXEntryActivity 类
public class WXEntryActivity extends Activity implements IWXAPIEventHandler
WXEntryActivity 是微信回调的一个类,通常给个透明的主题或者处理完业务逻辑就直接 finish。
在 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();
}
});
}
微信分享
关于分享的介绍:官方文档,以分享网页为例
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