我是靠谱客的博主 辛勤冰淇淋,最近开发中收集的这篇文章主要介绍android微信支付测试遇到的坑,得不到prepay_id,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

特别注意:spill_create_ip一定要是测试手机的ip,在设置----关于手机----版本信息里面找到ip;

//PayActivity的代码

package com.example.administrator.demopaywx;


import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.util.Locale;

public class PayActivity extends Activity {

   private IWXAPI api;
   Button appayBtn;
   //随机字符串
   static String nonce_str;
   //通知地址
   static String notify_url;
   //商户订单号
   static String out_trade_no;
   //客户端ipv4地址(必须是本机的ip地址)
   String spbill_create_ip = "192.168.2.170";
   //发送的xml字符串
   String entity;
   //商品描述
   String body;
   //事件戳
   String timestamp;
   //总金额(单位分)
   int total_fee;
   //第一次签名
   static String sign;
   //微信统一下单接口
   final String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.pay);
      api = WXAPIFactory.createWXAPI(this, Constants.APP_ID);
      api.registerApp(Constants.APP_ID);
      initReq();
      initView();
   }
   private void initReq() {
      body = "iphone";
      nonce_str = ResourceUtil.createRandomString(32);
      Log.e("==========","======nonce_str======"+nonce_str+"     length="+nonce_str.length());
      notify_url = "http://www.weixin.qq.com/wxpay/pay.php";
      out_trade_no = ResourceUtil.generateOutTradeNo(32);
      Log.e("================","=======out_trade_no========="+out_trade_no+"     length="+out_trade_no.length());
      total_fee = 1;
      timestamp = getTimeStamp();
      Log.e("==============","=====timestamp======"+timestamp+"     length="+timestamp.length());
      String A = "appid=" + Constants.APP_ID +
            "&body=" + body +
            "&mch_id=" + Constants.MCH_ID +
            "&nonce_str=" + nonce_str +
            "&notify_url=" + notify_url +
            "&out_trade_no=" + out_trade_no +
            "&spbill_create_ip=" +spbill_create_ip+
            "&total_fee=" + total_fee +
            "&trade_type=APP" +
            "&key=" + Constants.APP_KEY;
      sign = MD5.getMessageDigest(A.getBytes()).toUpperCase(Locale.getDefault());
      Log.e("===========","=======signsign====="+sign+"     length="+sign.length());
//          参数以xml格式传递
      entity = "<xml>" +
            "<appid>wx78d09351c6c8ec4e</appid>" +
            "<body>" + body + "</body>" +
            "<mch_id>" + Constants.MCH_ID + "</mch_id>" +
            "<nonce_str>" + nonce_str + "</nonce_str>" +
            "<out_trade_no>" + out_trade_no + "</out_trade_no>" +
            "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>" +
            "<total_fee>" + total_fee + "</total_fee>" +
            "<notify_url>" + notify_url + "</notify_url>" +
            "<trade_type>APP</trade_type>" +
            "<sign>" + sign + "</sign>" +
            "</xml>";
   }

   private String getTimeStamp() {
      return String.valueOf(System.currentTimeMillis() / 1000);
   }

   private void initView(){
      TextView tv_thing;
      TextView tv_money;
      TextView tv_from;
      tv_thing = (TextView) findViewById(R.id.pay_thing);
      tv_from = (TextView) findViewById(R.id.pay_from);
      tv_money = (TextView) findViewById(R.id.pay_money);
      tv_thing.setText("商品:"+body);
      tv_money.setText("总金额:"+total_fee+"");
      tv_from.setText("商户"+Constants.MCH_ID);
      appayBtn = (Button) findViewById(R.id.appay_btn);
      appayBtn.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            appayBtn.setEnabled(false);
            Toast.makeText(PayActivity.this, "获取订单中......", Toast.LENGTH_SHORT).show();
            Log.e("==============","==========entity===="+entity);
            new GetPrepayIdTask(api).execute(url,entity);
         }
      });
   }
}

//异步任务进行网络请求,想微信统一下单接口传递XML字符串,获得byte[ ] 数组,转化成字符串,获得xml字符串,解析获得prepay_id值,基本就达到目的了

package com.example.administrator.demopaywx;

import android.os.AsyncTask;
import android.util.Log;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import java.util.Locale;

/**
 * Created by Administrator on 2016/12/13.
 */

public class GetPrepayIdTask extends AsyncTask<String,Void,OrderResult> {


    public static final String TAG = "GetPrepayIdTask";
    private IWXAPI api;

    public GetPrepayIdTask(IWXAPI api) {
        this.api = api;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected OrderResult doInBackground(String... strings) {
        Log.e("============","=========doInBackground============");
        OrderResult result;
        String url = String.format(strings[0]);
        byte[] buf = Util.httpPost(url,strings[1]);
        String content =  new String(buf);
        Log.e("========","=========content========="+content);
        result = DecodeXmlUtil.decodeXML(content);
        return result;
    }

    @Override
    protected void onPostExecute(OrderResult orderResult) {
        sendPayReq(orderResult);
    }

    private void sendPayReq(OrderResult result) {
        String prepare_id = result.getPrepayId();
        Log.e("============","=====result====="+result.toString());
        Log.e("==========","========prepare_id==========="+prepare_id);
        Log.d(TAG, "sendPayReq, prepare_id = " + prepare_id + ", sign = " + result.getSign());

        if (prepare_id == null || prepare_id.length() == 0) {
            Log.e("==========","======================================");
            Log.e(TAG, "sendPayReq fail, prepare_id is empty");
        }

//        result = orderResult;
        PayReq req = new PayReq();
        req.appId = result.getAppId();
        req.nonceStr = result.getNonceStr();//随机字符串
        req.partnerId = result.getMchId();//商户号
        req.prepayId = result.getPrepayId();
        req.timeStamp = getTimeStamp();//时间戳
        req.packageValue = "Sign=WXPay";//固定字符串
        req.sign = SignUtil.signByMD5("appid=" + Constants.APP_ID +
                "&noncestr=" + req.nonceStr +
                "&package=Sign=WXPay" +
                "&partnerid=" + req.partnerId +
                "&prepayid=" + req.prepayId +
                "&timestamp=" + req.timeStamp +
                "&key=" + Constants.APP_KEY).toUpperCase(Locale.getDefault());//签名

        // 在支付之前,如果应用没有注册到微信,应该先调用IWXMsg.registerApp将应用注册到微信
        api.sendReq(req);
    }

    private String getTimeStamp() {
        return String.valueOf(System.currentTimeMillis() / 1000);
    }

    private static OrderResult orderResult = new OrderResult(
            "success","success","001","0","012adfjmgoaalmaoisja3456",
            Constants.APP_ID,Constants.MCH_ID,PayActivity.sign,"APP",PayActivity.nonce_str);

}
//一下是转载的签名算法以及xml解析方法

package com.example.administrator.demopaywx;

import android.util.Log;
import android.util.Xml;

import org.xmlpull.v1.XmlPullParser;

import java.io.StringReader;

/**
 * Created by Administrator on 2016/12/13.
 */

public class DecodeXmlUtil {
    public static OrderResult decodeXML(String content) {
        XmlPullParser parser = Xml.newPullParser();
        OrderResult bean = new OrderResult();
        try {
            parser.setInput(new StringReader(content));
            int event = parser.getEventType();
            while (event != XmlPullParser.END_DOCUMENT) {
                switch (event) {
                    case XmlPullParser.START_DOCUMENT:
                        break;
                    case XmlPullParser.START_TAG:
                        if ("return_code".equals(parser.getName())) {
                            parser.next();
                            bean.setReturnCode(parser.getText().toString());
                        } else if ("return_msg".equals(parser.getName())) {
                            parser.next();
                            bean.setReturnMsg(parser.getText().toString());
                        }else if ("appid".equals(parser.getName())) {
                            parser.next();
                            bean.setAppId(parser.getText().toString());
                           Log.e("=========","======parser.getText()=="+parser.getText());
                        }else if ("mch_id".equals(parser.getName())) {
                            parser.next();
                            bean.setMchId(parser.getText().toString());
                           Log.e("=========","======setMchId=="+parser.getText());
                        }else if ("nonce_str".equals(parser.getName())) {
                            parser.next();
                            bean.setNonceStr(parser.getText().toString());
                           Log.e("=========","======etNonceSt=="+parser.getText());
                        }else if ("sign".equals(parser.getName())) {
                            parser.next();
                            bean.setSign(parser.getText().toString());
                           Log.e("=========","======setSign=="+parser.getText());
                        }else if ("result_code".equals(parser.getName())) {
                            parser.next();
                            bean.setResultCode(parser.getText().toString());
                           Log.e("=========","======setResultCode=="+parser.getText());
                        }else if ("prepay_id".equals(parser.getName())) {
                            parser.next();
                            bean.setPrepayId(parser.getText().toString());
                           Log.e("=========","======setPrepayId=="+parser.getText());
                        }else if ("trade_type".equals(parser.getName())) {
                            parser.next();
                            bean.setTradeType(parser.getText().toString());
                           Log.e("=========","======parser.setTradeType()=="+parser.getText());
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        break;
                }
                event = parser.next();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bean;
    }
}


package com.example.administrator.demopaywx;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by Administrator on 2016/12/11.
 */

public class SignUtil {
    public static String signByMD5(String source) {
        byte[] bytes = null;
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(source.getBytes());  //更新摘要

            bytes = digest.digest(); //再通过执行诸如填充之类的最终操作完成哈希计算。在调用此方法之后,摘要被重置。
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        StringBuilder builder = new StringBuilder(bytes.length * 2);
        for (byte b : bytes) {
            /**
             * 0xFF默认是整形,一个byte跟0xFF相与会先将那个byte转化成整形运算
             */
            if ((b & 0xFF) < 0x10) {  //如果为1位 前面补个0
                builder.append("0");
            }

            builder.append(Integer.toHexString(b & 0xFF));
        }

        return builder.toString();
    }
}


//保存所有信息的自定义类

package com.example.administrator.demopaywx;

/**
 * Created by Administrator on 2016/12/11.
 */

public class OrderResult {
    public OrderResult(String returnCode, String returnMsg, String resultCode, String errorDesc, String prepayId, String appId, String mchId, String sign, String tradeType, String nonceStr) {
        this.returnCode = returnCode;
        this.returnMsg = returnMsg;
        this.resultCode = resultCode;
        this.errorDesc = errorDesc;
        this.prepayId = prepayId;
        this.appId = appId;
        this.mchId = mchId;
        this.sign = sign;
        this.tradeType = tradeType;
        this.nonceStr = nonceStr;
    }

    public OrderResult() {
    }

    public String getReturnCode() {
        return returnCode;
    }

    public void setReturnCode(String returnCode) {
        this.returnCode = returnCode;
    }

    public String getReturnMsg() {
        return returnMsg;
    }

    public void setReturnMsg(String returnMsg) {
        this.returnMsg = returnMsg;
    }

    public String getResultCode() {
        return resultCode;
    }

    public void setResultCode(String resultCode) {
        this.resultCode = resultCode;
    }

    public String getErrorDesc() {
        return errorDesc;
    }

    public void setErrorDesc(String errorDesc) {
        this.errorDesc = errorDesc;
    }

    public String getPrepayId() {
        return prepayId;
    }

    public void setPrepayId(String prepareId) {
        this.prepayId = prepareId;
    }

    @Override
    public String toString() {
        return "OrderResult{" +
                "returnCode='" + returnCode + ''' +
                ", returnMsg='" + returnMsg + ''' +
                ", resultCode='" + resultCode + ''' +
                ", errorDesc='" + errorDesc + ''' +
                ", prepayId='" + prepayId + ''' +
                ", appId='" + appId + ''' +
                ", mchId='" + mchId + ''' +
                ", sign='" + sign + ''' +
                ", tradeType='" + tradeType + ''' +
                ", nonceStr='" + nonceStr + ''' +
                '}';
    }

    String returnCode;
    String returnMsg;
    String resultCode;
    String errorDesc;
    String prepayId;
    String appId;
    String mchId;
    String sign;
    String tradeType;
    String nonceStr;

    public String getAppId() {
        return appId;
    }

    public void setAppId(String appId) {
        this.appId = appId;
    }

    public String getMchId() {
        return mchId;
    }

    public void setMchId(String mchId) {
        this.mchId = mchId;
    }

    public String getSign() {
        return sign;
    }

    public void setSign(String sign) {
        this.sign = sign;
    }

    public String getTradeType() {
        return tradeType;
    }

    public void setTradeType(String tradeType) {
        this.tradeType = tradeType;
    }

    public String getNonceStr() {
        return nonceStr;
    }

    public void setNonceStr(String nonceStr) {
        this.nonceStr = nonceStr;
    }
}

最后

以上就是辛勤冰淇淋为你收集整理的android微信支付测试遇到的坑,得不到prepay_id的全部内容,希望文章能够帮你解决android微信支付测试遇到的坑,得不到prepay_id所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(58)

评论列表共有 0 条评论

立即
投稿
返回
顶部