这是官方接入文档:关于openSDK6.8.0的更新说明 | 微信开放文档
根据官方文档的指引:
第一步:申请你的 AppID
首先要登录微信开发平放平台,注册账号,提交资料,然后审核通过才返回AppID和AppSecret
第二步:Android Studio 环境下:
- 在 build.gradle 文件中,添加如下依赖即可:
-
dependencies { api 'com.tencent.mm.opensdk:wechat-sdk-android:+' }
- 由于 jCenter 服务关停,需要修改成引用 Maven Central,在项目的根 build.gradle 文件中,添加如下代码即可:
-
buildscript { repositories { jcenter() // 原有 jCenter 引用可继续保留 mavenCentral() } } allprojects { repositories { jcenter() // 原有 jCenter 引用可继续保留 mavenCentral() } }
第三步:添加权限,以及初始化
-
<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"/>
初始化:在Application里就行初始化操作:
-
public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); WxLogin.initWx(this); } }
WxLogin类:
-
public class WxLogin { public static IWXAPI api; public static Context mContext; /** * 急的初始化 * * @param context */ public static void initWx(Context context) { UIUtils.initContext(context); mContext = context; api = WXAPIFactory.createWXAPI(context, WxData.WEIXIN_APP_ID, true); api.registerApp(WxData.WEIXIN_APP_ID); final IWXAPI msgApi = WXAPIFactory.createWXAPI(context, null); // 将该app注册到微信 msgApi.registerApp(WxData.WEIXIN_APP_ID); } public static void longWx() { if (mContext == null) { Toast.makeText(mContext, "你没有初始化,请在Application中做初始化动作,请调用 initWx(context)方法", Toast.LENGTH_SHORT).show(); return; } if (!api.isWXAppInstalled()) { Toast.makeText(mContext, "您还未安装微信客户端", Toast.LENGTH_SHORT).show(); return; } final SendAuth.Req req = new SendAuth.Req(); req.scope = WxData.SCOPE; req.state = WxData.STATE; api.sendReq(req); } }
UIUtils类:
-
public class UIUtils { private static Context mContext; public static void initContext(Context context) { mContext = context; } public static void runOnUIToast(String str){ Toast.makeText(mContext, str, Toast.LENGTH_SHORT).show(); } }
WxData类:
public class WxData {
/**
* 你的AppID
*
* 在此特别注意,本Demo只适用微信的登陆功能,并不能用到微信支付功能
*
* 在此注意,必须要和微信官网签名一致,否则调用不起来微信APP,
*
* 如果在你调用出错的情况下(微信APP死活不出来的情况下),请参阅作者简书网址 : https://www.jianshu.com/p/04ed0b65f3df
*
* 微信APP掉不出来:有以下原因:
*
* 1.签名不正确(APK所使用签名的MD5码) 签名MD5码不要有 : 如A0:5B:12:63.... ,要全部是小写(推荐)a05b1263...,这种形式的
*
* 2.APP_ID不正确
*
* 3.密匙不正确
*
* 4.包名不正确
*
* 不走回调WXEntryActivity
*
* 1.AndroidManifest.xml里没有配置
*
* <activity
* android:name=".wxapi.WXEntryActivity"
* android:exported="true"
* android:label="WXEntryActivity" />
* 2.必须是 你的包名.wxapi
* 如果你的所有信息填写正确,还是掉不起来微信,那就可能是微信服务器问题,请稍等3-5分钟,在尝试调用,否则就重复以上选项
* 大兄弟,记得细心一点哟~~~
*
*
*
*
*/
public static final String WEIXIN_APP_ID = "wxd59b4c89131231f";
public static final String APP_SECRET = "4f14bc84466839484131532150b";
/**
* 固定的
*
*/
public static final String SCOPE = "snsapi_userinfo";
public static final String STATE = "wechat_sdk_demo_test_neng";
}
WXEntryActivity类:
public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
private static final int RETURN_MSG_TYPE_LOGIN = 1;
private static final int RETURN_MSG_TYPE_SHARE = 2;
private IWXAPI mWeixinAPI;
private TextView id_tv;
private TextView nickname_tv;
private TextView sex_tv;
private ImageView imageView;
private Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wxentry);
id_tv = findViewById(R.id.id_tv);
nickname_tv = findViewById(R.id.nickname_tv);
sex_tv = findViewById(R.id.sex_tv);
imageView = findViewById(R.id.imageView);
handler = new Handler();
mWeixinAPI = WXAPIFactory.createWXAPI(this, WxData.WEIXIN_APP_ID, true);
mWeixinAPI.handleIntent(this.getIntent(), this);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
mWeixinAPI.handleIntent(intent, this);//必须调用此句话
}
@Override
public void onReq(BaseReq baseReq) {
Log.e("-----", "onReq: " + baseReq);
finish();
}
@Override
public void onResp(BaseResp baseResp) {
Log.e("-----", "errStr: " + baseResp.errStr);
Log.e("-----", "openId: " + baseResp.openId);
Log.e("-----", "transaction: " + baseResp.transaction);
Log.e("-----", "errCode: " + baseResp.errCode);
Log.e("-----", "getType: " + baseResp.getType());
Log.e("-----", "checkArgs: " + baseResp.checkArgs());
switch (baseResp.errCode) {
case BaseResp.ErrCode.ERR_AUTH_DENIED:
case BaseResp.ErrCode.ERR_USER_CANCEL:
if (RETURN_MSG_TYPE_SHARE == baseResp.getType()) UIUtils.runOnUIToast("分享失败");
else UIUtils.runOnUIToast("登录失败");
break;
case BaseResp.ErrCode.ERR_OK:
switch (baseResp.getType()) {
case RETURN_MSG_TYPE_LOGIN:
//拿到了微信返回的code,立马再去请求access_token
String code = ((SendAuth.Resp) baseResp).code;
getAccess_token(code);
//就在这个地方,用网络库什么的或者自己封的网络api,发请求去咯,注意是get请求
Log.e("--------", "code: " + code);
id_tv.setText("code: " + code);
break;
case RETURN_MSG_TYPE_SHARE:
UIUtils.runOnUIToast("微信分享成功");
finish();
break;
}
break;
}
}
/**
* 获取openid accessToken值用于后期操作
*
* @param code 请求码
*/
private void getAccess_token(final String code) {
String path = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
+ WxData.WEIXIN_APP_ID
+ "&secret="
+ WxData.APP_SECRET
+ "&code="
+ code
+ "&grant_type=authorization_code";
OkHttpUtils.get().url(path).build().execute(new StringCallback() {
@Override
public void onError(okhttp3.Call call, Exception e) {
}
@Override
public void onResponse(String response) {
Log.e("-----", "onResponse: " + response);
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(response);
String openid = jsonObject.getString("openid").toString().trim();
String access_token = jsonObject.getString("access_token").toString().trim();
getUserMesg(access_token, openid);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
/**
* 获取微信的个人信息
*
* @param access_token
* @param openid
*/
private void getUserMesg(final String access_token, final String openid) {
String path = "https://api.weixin.qq.com/sns/userinfo?access_token="
+ access_token
+ "&openid="
+ openid;
OkHttpUtils.get().url(path).build().execute(new StringCallback() {
@Override
public void onError(okhttp3.Call call, Exception e) {
}
@Override
public void onResponse(String response) {
Log.e("------", "全部数据: " + response);
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(response);
String nickname = jsonObject.getString("nickname");
int sex = Integer.parseInt(jsonObject.get("sex").toString());
String headimgurl = jsonObject.getString("headimgurl");
String openid1 = jsonObject.getString("openid");
Log.e("---", "用户基本信息:");
Log.e("---", "nickname:" + nickname);
nickname_tv.setText("nickname: " +nickname);
Log.e("---", "sex: " + sex);
sex_tv.setText("sex: " + sex + "");
Log.e("---", "headimgurl:" + headimgurl);
imageUrl(headimgurl);
// startLoca(nickname, openid1);
} catch (JSONException e) {
e.printStackTrace();
UIUtils.runOnUIToast("登陆错误,请重新再试");
}
// finish();
}
});
}
//请求显示图像
private void imageUrl(final String url) {
new Thread(new Runnable() {
@Override
public void run() {
try {
URL url1 = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection) url1.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(2000);
int responseCode = urlConnection.getResponseCode();
if (responseCode == 200) {
InputStream inputStream = urlConnection.getInputStream();
final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
handler.post(new Runnable() {
@Override
public void run() {
imageView.setImageBitmap(bitmap);
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
注意:WXEntryActivity类的注册:
<activity
android:name=".wxapi.WXEntryActivity"
android:exported="true"
android:label="WXEntryActivity" />
最后就是在Activity使用了:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.startWx).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
WxLogin.longWx();
}
});
}
}