导入依赖
implementation 'com.tencent.mm.opensdk:wechat-sdk-android-without-mta:5.3.1'
登录
将微信注册到APP 可以在onCreate的里边初始化
wxApi = WXAPIFactory.createWXAPI(this, Constants.wechat_appid, true)
wxApi!!.registerApp(Constants.wechat_appid)
登录代码,这里判断微信客户端是否存在可以根据包名来判断,也可以使用api,但是在高版本需要适配,下文有提及
if (wxApi!!.isWXAppInstalled()) {
val req = SendAuth.Req()
req.scope = "snsapi_userinfo"
req.state = "wechat_sdk_demo_test"
wxApi!!.sendReq(req)
} else {
ToastUtil.getInstance()._short(this,"请先安装微信客户端")
}
支付
将微信注册到APP 可以在onCreate的里边初始化
wxApi = WXAPIFactory.createWXAPI(this, Constants.wechat_appid, true)
wxApi!!.registerApp(Constants.wechat_appid)
支付代码,支付相关的一系列参数有后台接口返回,拿过来直接用就可以
if (wxApi?.isWXAppInstalled == true) {
val request = PayReq()
request.appId = Constants.wechat_appid
request.partnerId = data.partnerId
request.prepayId = data.prepayId
request.packageValue = data.packageStr
request.nonceStr = data.noncestr
request.timeStamp = data.timestamp
request.sign = data.sign
wxApi?.sendReq(request)
} else {
ToastUtil.getInstance()._short(activity, "请先安装微信客户端")
}
结果回调
在你的包名相应目录下新建一个wxapi目录,并在该wxapi目录下新增一个WXEntryActivity类,该类继承自Activity,
并在manifest文件里面加上exported属性,设置为true,例如:
<activity
android:name=".wxapi.WXEntryActivity"
android:label="@string/app_name"
android:theme="@android:style/Theme.Translucent.NoTitleBar"
android:exported="true"
android:taskAffinity="net.sourceforge.simcpux"
android:launchMode="singleTask">
</activity>
public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
private IWXAPI api;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
api = WXAPIFactory.createWXAPI(this, Constants.wechat_appid);
api.handleIntent(getIntent(), this);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
api.handleIntent(intent, this);
}
@Override
public void onReq(BaseReq req) {
}
@Override
public void onResp(BaseResp resp) {
int type = resp.getType();
if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
int errCode = resp.errCode;
if (errCode == -2) {
Toast.makeText(getApplicationContext(), "取消支付", Toast.LENGTH_SHORT).show();
finish();
} else if (errCode == 0) {
Toast.makeText(getApplicationContext(), "支付完成", Toast.LENGTH_SHORT).show();
finish();
} else {
Toast.makeText(getApplicationContext(), "支付失败", Toast.LENGTH_SHORT).show();
finish();
}
}else if (resp.getType() == ConstantsAPI.COMMAND_SENDAUTH){
}
}
}
微信回调之后,根据自己的业务逻辑来进行处理
Android版本11及以上版本, 判断手机是否安装微信isWXAppInstalled()一直返回false
AndroidManifest.xml中添加以下节点(类似其他三方SDK接入的时候,如果你突然发现方法不能用了,就去看看targetSdkVersion…)
<queries>
<package android:name="com.tencent.mm"/>
</queries>