1、接入微信SDK
implementation 'com.tencent.mm.opensdk:wechat-sdk-android-without-mta:+'
2、从公司业务后台拿到订单信息后调用微信SDK,发起微信支付
//orderInfo 业务后台的数据
public void pay(Activity a, WeChatPayOrderInfo orderInfo) {
//需要一个注册微信支付的APPID
WXUtil.getInstance(a).getApi().registerApp("wx_appid");
try {
PayReq request = new PayReq();
request.appId = LoginConfig.getAPP_ID_WX();
request.partnerId = orderInfo.getPtn();
request.prepayId = orderInfo.getOi();
request.packageValue = orderInfo.getOds();
request.nonceStr = orderInfo.getNes();
request.timeStamp = String.valueOf(orderInfo.getTtp());
request.sign = orderInfo.getSn();
WXUtil.getInstance(a).getApi().sendReq(request);
} catch (Exception e) {
e.printStackTrace();
Log.e("解析异常:" + e.toString());
}
}
3、在包名.wxapi目录下,创建一个WXPayEntryActivity.java界面,别忘了需要在Manifest.xml里面注册activity
public class WXPayEntryActivity extends AppCompatActivity implements IWXAPIEventHandler {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
boolean result = WXUtil.getInstance(this).getApi().handleIntent(getIntent(), this);
if (!result) {
ILog.e("参数不合法,未被SDK处理,退出");
finish();
}
} catch (Exception e) {
e.printStackTrace();
ILog.e("e:" + e.getMessage());
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
WXUtil.getInstance(this).getApi().handleIntent(data, this);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
WXUtil.getInstance(this).getApi().handleIntent(intent, this);
finish();
}
@Override
public void onReq(BaseReq baseReq) {
}
@Override
public void onResp(BaseResp baseResp) {
ILog.e("baseResp:" + baseResp.getType());
if (baseResp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {//微信支付
PayResp resp = (PayResp) baseResp;
switch (baseResp.errCode) {
case BaseResp.ErrCode.ERR_OK://支付成功
Log.e("微信支付成功");
this.finish();
break;
case BaseResp.ErrCode.ERR_USER_CANCEL:
case BaseResp.ErrCode.ERR_COMM:
case BaseResp.ErrCode.ERR_SENT_FAILED:
case BaseResp.ErrCode.ERR_AUTH_DENIED:
case BaseResp.ErrCode.ERR_BAN:
case BaseResp.ErrCode.ERR_UNSUPPORT:
Log.e("微信支付失败:" + resp.errCode);
this.finish();
break;
}
}
}
@Override
public Resources getResources() {
Resources res = super.getResources();
Configuration config = new Configuration();
config.setToDefaults();
res.updateConfiguration(config, res.getDisplayMetrics());
return res;
}
}
到此微信支付就完成了!!!