① 首先要调起微信支付 ,执行微信或者是支付宝支付
上图中已经注释的查询该笔订单是不是真正的意义上的支付成功了,这个查询要放在服务中去查询也就是 调起的QueryPayResultServices
②再看这个
QueryPayResultServices 是如何写的
public class QueryPayResultService extends IntentService { private Intent intent; private UserDao userDao; private Handler handler = new Handler(new Handler.Callback() { @Override public boolean handleMessage(Message msg) { switch (msg.what) { case PayResultUtil.FLAG_REAL_PAY_STATUS: handleRealPayResult(msg); break; } //如果支付成功了,要分支判断: 1.修改数据库,展示结果 2. 展示结果; ToastUtil.toast_debug("toast from service!"); return true; } }); /** * Creates an IntentService. Invoked by your subclass's constructor. * <p/> * Used to name the worker thread, important only for debugging. */ public QueryPayResultService() { super("QueryPayResultService"); } @Override public void onCreate() { super.onCreate(); ToastUtil.toast_debug("开启了服务"); } @Override public void onDestroy() { // super.onDestroy(); ToastUtil.toast_debug("销毁了服务"); } @Override protected void onHandleIntent(Intent intent) { //这个方法在工作线程中运行,所以不要在此再开子线程了 //后到的任务在队列里面按顺序依次执行 this.intent = intent; String phoneNumber = intent.getStringExtra(Constants.PhoneNumber); String payOrderId = intent.getStringExtra(Constants.PayOrderID); String[] params = {Constants.AppID, GlobalConfig.AppID, Constants.ECID, GlobalConfig.ECID, Constants.PhoneNumber, phoneNumber, Constants.PayOrderID, payOrderId}; PayResultUtil.retrieveRealPayStatus(handler, params); } /** 这个方法就相当于getMassage * *****处理从服务器上获取到的真实支付结果***** */ private void handleRealPayResult(Message msg) { if (userDao == null) { userDao = UserDao.getDaoInstance(this); } String payType = intent.getStringExtra(Constants.PayType);//区分用户支付方式:ZFB or WECHAT String type = intent.getStringExtra(Constants.Type); int payStatus = msg.arg2; //支付状态:1、支付成功;2、支付取消;3、支付失败;4、准备支付; String result = ""; System.out.println("1====================payStatus=" + payStatus); if ("DEPOSIT".equals(type)) {//押金的支付结果 System.out.println("2=======================payStatus" + payStatus); if (payStatus == 1) { result = "支付成功"; LoginResultBean user = userDao.queryCurrentProcessingUser(); //Caution:需求改变后:将当前正在支付押金的用户设为当前用户 user.setCurrentUser(true);//这个为什么没有执行呢?? user.setDespositStatus(2);//押金已付,更新押金状态 userDao.update(user); } else { System.out.println("2=======================失败"); result = "支付失败"; ToastUtil.toast("请重新支付"); } } else if ("ORDERPAYMENT".equals(type)) {//预定的支付结果 System.out.println("3=======================payStatus" + payStatus); if (payStatus == 1) { result = "订单支付成功"; if (SPUtils.getInt("MainActivityList") == 1) { openActivity(ListpaySuccessActivity.class); } openActivity(MainActivity.class); } else { System.out.println("3=======================失败"); result = "订单支付失败"; } } else if ("WITHDRAW".equals(type)) {//提现的支付结果 } ToastUtil.toast(result); } private void openActivity(Class cls) { // TODO: 2017/9/26 这个打开方式不正确!要改 Intent intent = new Intent(getApplicationContext(), cls); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);// // intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);// startActivity(intent); } }
这个就是这个服务的代码,一经调用就执行查询操作,根据服务器返回的结果来做判读。
③是一个调用 查询结果的工具类去查询 ————>去服务期查询
PayResultUtil.retrieveRealPayStatus(handler, params);
这是
PayResultUtil
*/ public class PayResultUtil { private static final String TAG = "PayResultUtil"; public static final int FLAG_REAL_PAY_STATUS = 1001; public static void retrieveRealPayStatus(final Handler handler, final String[] params) { try { URL url = new URL(GlobalConfig.MSHARE_SERVER_ROOT + GlobalConfig.MSHARE_QUERY_PAY_RESULT); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); conn.setDoInput(true); // 设置输入流采用字节流 conn.setDoOutput(true);// 设置输出流采用字节流 conn.setRequestMethod("POST"); conn.setUseCaches(false); conn.setRequestProperty("ser-Agent", "Fiddler"); conn.setRequestProperty("Content-Type", "application/json"); conn.connect();// 连接既往服务端发送信息 //产生json格式的请求字符串 String str = generateJsonString(params); Log.d(TAG, "run: parmsStr=" + str); OutputStream os = conn.getOutputStream(); os.write(str.getBytes()); os.close(); Log.d(TAG, "run:>>>>>>>>>>>>>>>>>>>>>>>>>> " + conn.getResponseCode()); if (conn.getResponseCode() == 200) { Log.e(TAG, "retrieveRealPayStatus: 服务器正确返回数据"); InputStream in = conn.getInputStream(); int length = conn.getContentLength(); byte[] b = new byte[length]; in.read(b); String s = new String(b); Log.d(TAG, "run: json>>>>>>" + s); Log.d(TAG, "run: contentlength>>>" + length); JSONObject obj = new JSONObject(s); String payStatus = obj.getString("PayStatus");//支付状态:1、支付成功;2、支付取消;3、支付失败;4、准备支付; Message msg = Message.obtain(handler, FLAG_REAL_PAY_STATUS); Log.d(TAG, "run: msg.paystatus>>>>" + Integer.valueOf(payStatus)); msg.arg2 = Integer.valueOf(payStatus); handler.sendMessage(msg); } else { Log.e(TAG, "retrieveRealPayStatus: 服务器没有正确返回数据"); } } catch (IOException | JSONException e) { e.printStackTrace(); Log.d(TAG, "retrieveRealPayStatus: exception!"); } } /** * 产生json格式的请求字符串 */ private static String generateJsonString(String[] params) { //把穿入的strUrl封装成JSON串 JSONObject ClickKey = new JSONObject(); try { for (int i = 0, N = params.length; i < N; i += 2) { if (i + 1 > N) { ClickKey.put(params[i], null); } else { ClickKey.put(params[i], params[i + 1]); } } } catch (JSONException e) { e.printStackTrace(); } return String.valueOf(ClickKey); } /** * 向服务器拉取真实的支付结果,并可能需要更新数据库信息 * 指定出要查询哪个服务 * type 用来标明是进行订金/订单/提现中的哪种 */ public static void openQueryService(Context context, SignedOrderBean orderBean, String type, Class service) { //?是否是出问题在这了? 就在这里: 用户端支付时,应该查询登陆用户的信息,而不是当前正在注册用户的信息! LoginResultBean user = null; if(type.equals("ORDERPAYMENT")||type.equals("WITHDRAW")){ user = UserDao.getDaoInstance(context).query(); }else if(type.equals("DEPOSIT")){ user = Integer.valueOf(GlobalConfig.AppType) == 2 ? UserDao.getDaoInstance(context).queryCurrentProcessingUser():UserDao.getDaoInstance(context).query(); } if (user == null) { Log.d(TAG, "openQueryService: 未进行真实结果查询!!!问题在此"); return; } Log.d(TAG, "openQueryService: 进行真实结果查询!!!问题不在此"); String phoneNumber = user.getPhoneNumber(); Intent intent = new Intent(context, service); intent.putExtra(Constants.PhoneNumber, phoneNumber); System.out.println("=====orderBean===="+orderBean.getPayOrderID()); intent.putExtra(Constants.PayOrderID, orderBean.getPayOrderID()); intent.putExtra(Constants.PayType, orderBean.getPayType());//指明用支付还是微信 intent.putExtra(Constants.Type, type);//指明是押金支付还是业务支付还是提现支付 context.startService(intent);//开启服务,在服务中来获取真实的后台支付结果 } public static void notifyPaymentCancelation(Handler handler,Context ctx,String orderId){ // OkHttpUtils // .post() // .addParams(Constants.AppID,GlobalConfig.AppID) // .url(GlobalConfig.MSHARE_SERVER_ROOT+GlobalConfig.SHARER_CANCEL_ORDER_PAYMENT) // .addParams(Constants.ECID,GlobalConfig.ECID) // .addParams(Constants.PayOrderID,orderId) // .addParams("Status","2")//2、支付取消 // .build() // .execute(new StringCallback() { // @Override // public void onError(Call call, Exception e, int i) { // // } // @Override // public void onResponse(String s, int i) { // // } // });//不处理同步结果 String[] params = {Constants.AppID,GlobalConfig.AppID,Constants.ECID,GlobalConfig.ECID,Constants.PayOrderID,orderId,"Status","2"}; String url = GlobalConfig.MSHARE_SERVER_ROOT + GlobalConfig.SHARER_CANCEL_ORDER_PAYMENT; new HttpUtil().callJson(handler,ctx,url,params); } }