官方接入指北:
https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=8_5
SDK&DEMO下载:https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=11_1
1. 微信开发者账号中创建应用
获取app_id ,app_secret
2. Application中初始化操作
public static IWXAPI WXapi;
private void initWX() {
WXapi = WXAPIFactory.createWXAPI(this, BuildConfig.WX_APP_ID, true);
WXapi.registerApp(BuildConfig.WX_APP_ID);
}
3. 支付相关代码
/**
* 微信支付
*/
private void channelWechat() {
WxPayModel wxPayModel ;//后台接口获取订单信息
PayReq request = new PayReq();
request.appId = wxPayModel.getAppid();
request.partnerId = wxPayModel.getPartnerid();
request.prepayId = wxPayModel.getPrepayid();
request.packageValue = wxPayModel.getPackageStr();
request.nonceStr = wxPayModel.getNoncestr();
request.timeStamp = wxPayModel.getTimestamp();
request.sign = wxPayModel.getSign();
AppApplication.WXapi.sendReq(request);
}
@Override
public void onEventMainThread(EventBean bean) {
super.onEventMainThread(bean);
if (bean.getFrom() == Constant.Event_Msg.PAY_SUCCESS_WECHAT) {
//0成功;-1错误;-2用户取消
if (bean.getIndex() == -2)
doBack();
else
payResult(bean.getIndex() == 0 ? true : false);
}
}
private void payResult(boolean success) {
DialogUtils.showMsg(this, "提示", "订单支付" + (success ? "成功" : "失败,重新支付"), (context, builder, dialog, dialogId, which, editText) -> {
EventBus.getDefault().post(new EventBean(Constant.Event_Msg.PAY_SUCCESS));
finish();
}, (context, builder, dialog, dialogId, which, editText) -> {
if (success) {
EventBus.getDefault().post(new EventBean(Constant.Event_Msg.PAY_SUCCESS));
finish();
}
}, !success, "取消", "确定", false);
}
private void doBack() {
DialogUtils.showMsg(this, "提示", "您的订单还未支付完成,请尽快完成支付。", (context, builder, dialog, dialogId, which, editText) -> {
EventBus.getDefault().post(new EventBean(Constant.Event_Msg.PAY_SUCCESS));
finish();
}, (context, builder, dialog, dialogId, which, editText) -> {
}, true, "确认离开", "继续支付", false);
}
4. 本地创建WXPayEntryActivity类
注意WXPayEntryActivity类地址必须与applicationId一致。
public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {
IWXAPI api;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
api= AppApplication.WXapi;
// api = WXAPIFactory.createWXAPI(this, BuildConfig.WX_APP_ID, true);
// api.registerApp(BuildConfig.WX_APP_ID);
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) {
//0成功;-1错误;-2用户取消
EventBus.getDefault().post(new EventBean(Constant.Event_Msg.PAY_SUCCESS_WECHAT, resp.errCode));
finish();
}
}