如何在Android App中接入微信支付

本篇簡單介紹Android App中接入微信支付,包括App內支付和掃碼支付。分享+支付 pofei

微信支付

wechat 官方接入文檔

App內支付

源碼下載

主要流程:

1.微信支付平臺註冊賬號​

註:註冊並申請成功以後,需要在API安全中設置你的API密鑰 32個字符。建議使用 MD5加密 ,並且需要妥善的保存。因為無法查看。

2.生成預支付訂單

3.生成簽名參數

4.調起微信,完成支付

掃碼支付

掃碼支付使用的是微信統一下單API ,使用的是模式二,模式一 一直說URL參數錯誤,完全按照官方文檔來的 令人費解。

統一下單API

統一下單API
在上面的基礎上,修改

 private String getProductArgs() {
    // TODO Auto-generated method stub
    StringBuffer xml=new StringBuffer();
    try {
      String nonceStr=getNonceStr();
      currentOrderId = getOutTrade();
      xml.append("<xml>");
      List<NameValuePair> packageParams=new LinkedList<NameValuePair>();
      packageParams.add(new BasicNameValuePair("appid", WXConstants.APP_ID));
      packageParams.add(new BasicNameValuePair("body", "APP pay test"));
      packageParams.add(new BasicNameValuePair("mch_id", WXConstants.MCH_ID));
      packageParams.add(new BasicNameValuePair("nonce_str", nonceStr));
			// 回調 URL 地址,這裡是第三方
      packageParams.add(new BasicNameValuePair("notify_url", "http://www.weixunyunduan.com/yunduanwx/wxpay/getpackage"));
			// 商戶系統內部訂單號,要求32個字符 且同個商戶下唯一
      packageParams.add(new BasicNameValuePair("out_trade_no", getNonceStr()));
			// APP和網頁支付提交用戶端,Native支付填調用微信支付API的機器IP
      packageParams.add(new BasicNameValuePair("spbill_create_ip", "192.168.0.1"));
      packageParams.add(new BasicNameValuePair("total_fee", "1"));
			// Native支付
      packageParams.add(new BasicNameValuePair("trade_type", "NATIVE"));

      String sign=getPackageSign(packageParams);
      packageParams.add(new BasicNameValuePair("sign", sign));
      String xmlString=toXml(packageParams);

      return xmlString;


    } catch (Exception e) {
      // TODO: handle exception
      return null;
    }
  }
	
	
	 private String getOutTrade(){
    return UUID.randomUUID().toString().replace("-", "");
  }

NATIVE請求返回值如下:

<xml>
<return_code><![CDATA[SUCCESS]]></return_code>
<return_msg><![CDATA[OK]]></return_msg>
<appid><![CDATA[]]></appid>
<mch_id><![CDATA[]]></mch_id>
<nonce_str><![CDATA[]]></nonce_str>
<sign><![CDATA[]]></sign>
<result_code><![CDATA[SUCCESS]]></result_code>
<prepay_id><![CDATA[]]></prepay_id>
<trade_type><![CDATA[NATIVE]]></trade_type>
<code_url><![CDATA[weixin://wxpay/bizpayurl?pr=]></code_url>
</xml>

獲取code_url,並使用第三方二維碼生成庫 如ZXing 生成二維碼。

ZXingUtils

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PointF;
import android.view.Gravity;
import android.view.View.MeasureSpec;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import java.util.Hashtable;

/** 
*
* 	生成條形碼和二維碼的工具
*/
public class ZXingUtils {
	/**
	 * 生成二維碼 要轉換的地址或字符串,可以是中文
	 * 
	 * @param url
	 * @param width
	 * @param height
	 * @return
	 */
	public static Bitmap createQRImage(String url, final int width, final int height) {
		try {
			// 判斷URL合法性
			if (url == null || "".equals(url) || url.length() < 1) {
				return null;
			}
			Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
			hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
			// 圖像數據轉換,使用瞭矩陣轉換
			BitMatrix bitMatrix = new QRCodeWriter().encode(url,
					BarcodeFormat.QR_CODE, width, height, hints);
			int[] pixels = new int[width * height];
			// 下面這裡按照二維碼的算法,逐個生成二維碼的圖片,
			// 兩個for循環是圖片橫列掃描的結果
			for (int y = 0; y < height; y++) {
				for (int x = 0; x < width; x++) {
					if (bitMatrix.get(x, y)) {
						pixels[y * width + x] = 0xff000000;
					} else {
						pixels[y * width + x] = 0xffffffff;
					}
				}
			}
			// 生成二維碼圖片的格式,使用ARGB_8888
			Bitmap bitmap = Bitmap.createBitmap(width, height,
					Bitmap.Config.ARGB_8888);
			bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
			return bitmap;
		} catch (WriterException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 生成條形碼
	 *
	 * @param context
	 * @param contents
	 *      需要生成的內容
	 * @param desiredWidth
	 *      生成條形碼的寬帶
	 * @param desiredHeight
	 *      生成條形碼的高度
	 * @param displayCode
	 *      是否在條形碼下方顯示內容
	 * @return
	 */
	public static Bitmap creatBarcode(Context context, String contents,
									 int desiredWidth, int desiredHeight, boolean displayCode) {
		Bitmap ruseltBitmap = null;
		/**
		 * 圖片兩端所保留的空白的寬度
		 */
		int marginW = 20;
		/**
		 * 條形碼的編碼類型
		 */
		BarcodeFormat barcodeFormat = BarcodeFormat.CODE_128;

		if (displayCode) {
			Bitmap barcodeBitmap = encodeAsBitmap(contents, barcodeFormat,
					desiredWidth, desiredHeight);
			Bitmap codeBitmap = creatCodeBitmap(contents, desiredWidth + 2
					* marginW, desiredHeight, context);
			ruseltBitmap = mixtureBitmap(barcodeBitmap, codeBitmap, new PointF(
					0, desiredHeight));
		} else {
			ruseltBitmap = encodeAsBitmap(contents, barcodeFormat,
					desiredWidth, desiredHeight);
		}

		return ruseltBitmap;
	}

	/**
	 * 生成條形碼的Bitmap
	 *
	 * @param contents
	 *      需要生成的內容
	 * @param format
	 *      編碼格式
	 * @param desiredWidth
	 * @param desiredHeight
	 * @return
	 * @throws WriterException
	 */
	protected static Bitmap encodeAsBitmap(String contents,
										  BarcodeFormat format, int desiredWidth, int desiredHeight) {
		final int WHITE = 0xFFFFFFFF;
		final int BLACK = 0xFF000000;

		MultiFormatWriter writer = new MultiFormatWriter();
		BitMatrix result = null;
		try {
			result = writer.encode(contents, format, desiredWidth,
					desiredHeight, null);
		} catch (WriterException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		int width = result.getWidth();
		int height = result.getHeight();
		int[] pixels = new int[width * height];
		// All are 0, or black, by default
		for (int y = 0; y < height; y++) {
			int offset = y * width;
			for (int x = 0; x < width; x++) {
				pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
			}
		}

		Bitmap bitmap = Bitmap.createBitmap(width, height,
				Bitmap.Config.ARGB_8888);
		bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
		return bitmap;
	}

	/**
	 * 生成顯示編碼的Bitmap
	 *
	 * @param contents
	 * @param width
	 * @param height
	 * @param context
	 * @return
	 */
	protected static Bitmap creatCodeBitmap(String contents, int width,
											int height, Context context) {
		TextView tv = new TextView(context);
		LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		tv.setLayoutParams(layoutParams);
		tv.setText(contents);
		tv.setHeight(height);
		tv.setGravity(Gravity.CENTER_HORIZONTAL);
		tv.setWidth(width);
		tv.setDrawingCacheEnabled(true);
		tv.setTextColor(Color.BLACK);
		tv.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
				MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
		tv.layout(0, 0, tv.getMeasuredWidth(), tv.getMeasuredHeight());

		tv.buildDrawingCache();
		Bitmap bitmapCode = tv.getDrawingCache();
		return bitmapCode;
	}

	/**
	 * 將兩個Bitmap合並成一個
	 * 
	 * @param first
	 * @param second
	 * @param fromPoint
	 *      第二個Bitmap開始繪制的起始位置(相對於第一個Bitmap)
	 * @return
	 */
	protected static Bitmap mixtureBitmap(Bitmap first, Bitmap second,
										 PointF fromPoint) {
		if (first == null || second == null || fromPoint == null) {
			return null;
		}
		int marginW = 20;
		Bitmap newBitmap = Bitmap.createBitmap(
				first.getWidth() + second.getWidth() + marginW,
				first.getHeight() + second.getHeight(), Config.ARGB_4444);
		Canvas cv = new Canvas(newBitmap);
		cv.drawBitmap(first, marginW, 0, null);
		cv.drawBitmap(second, fromPoint.x, fromPoint.y, null);
		cv.save(Canvas.ALL_SAVE_FLAG);
		cv.restore();

		return newBitmap;
	}

}
Bitmap bitmap = ZXingUtils.createQRImage(wxUrl,200,200);

code_url為微信可以識別的短鏈。

用戶掃描便可在手機上支付。

查詢訂單API

獲取支付回調,使用查詢訂單API

查詢訂單API

String urlString="https://api.mch.weixin.qq.com/pay/orderquery";
        CheckAsyncTask checkAsyncTask = new CheckAsyncTask();
        checkAsyncTask.execute(urlString);

private class CheckAsyncTask extends AsyncTask<String,Void, Map<String, String>>
  {
    private ProgressDialog dialog;
    @Override
    protected void onPreExecute() {
      // TODO Auto-generated method stub
      super.onPreExecute();
      dialog = ProgressDialog.show(PayActivity.this, "提示", "正在查看訂單狀態!");

    }
    @Override
    protected Map<String, String> doInBackground(String... params) {
      // TODO Auto-generated method stub
      String url=String.format(params[0]);
      String entity=getProductCheckArgs();
      byte[] buf= wxUtils.httpPost(url, entity);
      String content = new String(buf);
      Map<String,String> xml=decodeXml(content);
      // 可以通過 xml.get("trade_state"); 獲取訂單的狀態
      return xml;
    }

    @Override
    protected void onPostExecute(Map<String, String> result) {
      // TODO Auto-generated method stub
      super.onPostExecute(result);
      if (dialog != null) {
        dialog.dismiss();
      }
    }
  }

以上就是如何在Android App中接入微信支付的詳細內容,更多關於在Android App中接入微信支付的資料請關註WalkonNet其它相關文章!

推薦閱讀: