react native 接入微信登陆(Android)
-
官方地址:https://developers.weixin.qq.com/doc/oplatform/Mobile_App/Access_Guide/Android.html
-
添加依赖
api 'com.tencent.mm.opensdk:wechat-sdk-android-without-mta:+'
-
包名.wxapi.WXEntryActivity.java
public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IWXAPI wxapi = WXAPIFactory.createWXAPI(this, "APP_ID", false);
wxapi.handleIntent(getIntent(), this);
}
@Override
public void onReq(BaseReq baseReq) {
}
@Override
public void onResp(BaseResp baseResp) {
if (baseResp.errCode == BaseResp.ErrCode.ERR_OK) {
String code = ((SendAuth.Resp) baseResp).code;
String url = "https://api.weixin.qq.com/sns/oauth2/access_token" +
"?appid=wx3b302e27c2439dbf&secret=cf886e9fc9977a8d4b5e0be1a66a2851&code="
+ code + "&grant_type=authorization_code";
Request request = new Request.Builder().url(url).get().build();
new OkHttpClient().newCall(request).enqueue(new Callback() {
@Override
@EverythingIsNonNull
public void onFailure(Call call, IOException e) {
MyModule.promise.reject(new Exception("操作失败"));
finish();
}
@Override
@EverythingIsNonNull
public void onResponse(Call call, Response response) throws IOException {
Map map = new Gson().fromJson(Objects.requireNonNull(response.body()).string(), Map.class);
WritableMap writableMap = Arguments.createMap();
writableMap.putString("openid", Objects.requireNonNull(map.get("openid")).toString());
MyModule.promise.resolve(writableMap);
finish();
}
});
} else {
MyModule.promise.reject(new Exception("操作失败"));
finish();
}
}
}
- 注册Activity
<activity
android:name=".wxapi.WXEntryActivity"
android:exported="true"
android:label="@string/app_name"
android:launchMode="singleTask"
android:taskAffinity="包名"
android:theme="@android:style/Theme.Translucent.NoTitleBar" />
- MainActivity.java
public class MainActivity extends ReactActivity {
static IWXAPI api;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
api = WXAPIFactory.createWXAPI(this, "APP_ID", true);
api.registerApp("APP_ID");
}
}
- 登陆代码
final SendAuth.Req req = new SendAuth.Req();
req.scope = "snsapi_userinfo";
req.state = "wechat_sdk_demo_test";
MainActivity.api.sendReq(req);
- 其他参考QQ登陆