Android中怎么實現微信支付功能,相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
成都創(chuàng)新互聯(lián)公司服務項目包括忻州網站建設、忻州網站制作、忻州網頁制作以及忻州網絡營銷策劃等。多年來,我們專注于互聯(lián)網行業(yè),利用自身積累的技術優(yōu)勢、行業(yè)經驗、深度合作伙伴關系等,向廣大中小型企業(yè)、政府機構等提供互聯(lián)網行業(yè)的解決方案,忻州網站推廣取得了明顯的社會效益與經濟效益。目前,我們服務的客戶以成都為中心已經輻射到忻州省份的部分城市,未來相信會繼續(xù)擴大服務區(qū)域并繼續(xù)獲得客戶的支持與信任!
1. 去微信開放平臺申請微信支付服務,綁定自己的應用這里具體不多講,但是一定要申請完成,將會得到是三個參數
//appid 微信分配的公眾賬號ID public static final String APP_ID = ""; //商戶號 微信分配的公眾賬號ID public static final String MCH_ID = ""; // API密鑰,在商戶平臺設置 public static final String API_KEY= "";
**坑點提示:在微信開發(fā)平臺設置包名和簽名。這里的包名一定要和你自己的包名一樣,就是manifest中的package,簽名一定要和你用官方app生成的一樣(https://open.weixin.qq.com/zh_CN/htmledition/res/dev/download/sdk/Gen_Signature_Android.apk)。
微信會根據你的填寫的包名,然后對你的keystore進行一種算法,生成你的簽名。包名和簽名一定要和微信開放平臺的相同。不過這里需要注意的是,如果你發(fā)布的正式版本,需要用官方app重新生成簽名,然后在開放平臺重新設置sign,因為測試版本的keystore與正式版的keystore不一樣??傊褪悄阌玫膋eystore生成的sign要和微信開放平臺的時刻保持一致。**
2. 準備工作做好了,接下來就是開發(fā)了,先下載微信的jar包,導入。
微信支付分為三個步驟
① .生成prepayId
@Override protected Map<String, String> doInBackground(String... params) { // TODO Auto-generated method stub String url=String.format(params[0]); String entity=getProductArgs(); Log.e("Simon",">>>>"+entity); byte[] buf=Util.httpPost(url, entity); String content = new String(buf); Log.e("orion", "----"+content); Map<String,String> xml=decodeXml(content); return xml; }
② .生成簽名參數
private void genPayReq() { req.appId = Constants.APP_ID; req.partnerId = Constants.MCH_ID; if (resultunifiedorder!=null) { req.prepayId = resultunifiedorder.get("prepay_id"); req.packageValue = "prepay_id="+resultunifiedorder.get("prepay_id"); } else { Toast.makeText(MainActivity.this, "prepayid為空", Toast.LENGTH_SHORT).show(); } req.nonceStr = getNonceStr(); req.timeStamp = String.valueOf(genTimeStamp()); List<NameValuePair> signParams = new LinkedList<NameValuePair>(); signParams.add(new BasicNameValuePair("appid", req.appId)); signParams.add(new BasicNameValuePair("noncestr", req.nonceStr)); signParams.add(new BasicNameValuePair("package", req.packageValue)); signParams.add(new BasicNameValuePair("partnerid", req.partnerId)); signParams.add(new BasicNameValuePair("prepayid", req.prepayId)); signParams.add(new BasicNameValuePair("timestamp", req.timeStamp)); req.sign = genAppSign(signParams); sb.append("sign\n"+req.sign+"\n\n"); textView.setText(sb.toString()); Log.e("Simon", "----"+signParams.toString()); }
③ .調起支付
/* * 調起微信支付 */ private void sendPayReq() { msgApi.registerApp(Constants.APP_ID); msgApi.sendReq(req); Log.i(">>>>>", req.partnerId); }
下面給出完整代碼
package com.alpha.live; import java.io.StringReader; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.xmlpull.v1.XmlPullParser; import com.tencent.mm.sdk.modelpay.PayReq; import com.tencent.mm.sdk.openapi.IWXAPI; import com.tencent.mm.sdk.openapi.WXAPIFactory; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.util.Xml; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; /** * Created by Simon on 2016/12/2. */ public class MainActivity extends Activity implements OnClickListener { private Button submitButton; private Button confirmButton; private TextView textView; private StringBuffer sb; private Map<String,String> resultunifiedorder; private PayReq req; private final IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); submitButton=(Button) findViewById(R.id.bt_submit_order); confirmButton=(Button) findViewById(R.id.bt_corfirm); textView=(TextView) findViewById(R.id.tv_prepay_id); submitButton.setOnClickListener(this); confirmButton.setOnClickListener(this); sb=new StringBuffer(); req=new PayReq(); } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.bt_submit_order: String urlString="https://api.mch.weixin.qq.com/pay/unifiedorder"; PrePayIdAsyncTask prePayIdAsyncTask=new PrePayIdAsyncTask(); prePayIdAsyncTask.execute(urlString); //生成prepayId break; case R.id.bt_corfirm: genPayReq();//生成簽名參數 sendPayReq();//調起支付 break; default: break; } } /* * 調起微信支付 */ private void sendPayReq() { msgApi.registerApp(Constants.APP_ID); msgApi.sendReq(req); Log.i(">>>>>", req.partnerId); } private long genTimeStamp() { return System.currentTimeMillis() / 1000; } private void genPayReq() { req.appId = Constants.APP_ID; req.partnerId = Constants.MCH_ID; if (resultunifiedorder!=null) { req.prepayId = resultunifiedorder.get("prepay_id"); req.packageValue = "prepay_id="+resultunifiedorder.get("prepay_id"); } else { Toast.makeText(MainActivity.this, "prepayid為空", Toast.LENGTH_SHORT).show(); } req.nonceStr = getNonceStr(); req.timeStamp = String.valueOf(genTimeStamp()); List<NameValuePair> signParams = new LinkedList<NameValuePair>(); signParams.add(new BasicNameValuePair("appid", req.appId)); signParams.add(new BasicNameValuePair("noncestr", req.nonceStr)); signParams.add(new BasicNameValuePair("package", req.packageValue)); signParams.add(new BasicNameValuePair("partnerid", req.partnerId)); signParams.add(new BasicNameValuePair("prepayid", req.prepayId)); signParams.add(new BasicNameValuePair("timestamp", req.timeStamp)); req.sign = genAppSign(signParams); sb.append("sign\n"+req.sign+"\n\n"); textView.setText(sb.toString()); Log.e("Simon", "----"+signParams.toString()); } private String genAppSign(List<NameValuePair> params) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < params.size(); i++) { sb.append(params.get(i).getName()); sb.append('='); sb.append(params.get(i).getValue()); sb.append('&'); } sb.append("key="); sb.append(Constants.API_KEY); this.sb.append("sign str\n"+sb.toString()+"\n\n"); String appSign = MD5.getMessageDigest(sb.toString().getBytes()); Log.e("Simon","----"+appSign); return appSign; } private class PrePayIdAsyncTask extends AsyncTask<String,Void, Map<String, String>> { private ProgressDialog dialog; @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); dialog = ProgressDialog.show(MainActivity.this, "提示", "正在提交訂單"); } @Override protected Map<String, String> doInBackground(String... params) { // TODO Auto-generated method stub String url=String.format(params[0]); String entity=getProductArgs(); Log.e("Simon",">>>>"+entity); byte[] buf=Util.httpPost(url, entity); String content = new String(buf); Log.e("orion", "----"+content); Map<String,String> xml=decodeXml(content); return xml; } @Override protected void onPostExecute(Map<String, String> result) { // TODO Auto-generated method stub super.onPostExecute(result); if (dialog != null) { dialog.dismiss(); } sb.append("prepay_id\n"+result.get("prepay_id")+"\n\n"); textView.setText(sb.toString()); resultunifiedorder=result; } } public Map<String,String> decodeXml(String content) { try { Map<String, String> xml = new HashMap<String, String>(); XmlPullParser parser = Xml.newPullParser(); parser.setInput(new StringReader(content)); int event = parser.getEventType(); while (event != XmlPullParser.END_DOCUMENT) { String nodeName=parser.getName(); switch (event) { case XmlPullParser.START_DOCUMENT: break; case XmlPullParser.START_TAG: if("xml".equals(nodeName)==false){ //實例化student對象 xml.put(nodeName,parser.nextText()); } break; case XmlPullParser.END_TAG: break; } event = parser.next(); } return xml; } catch (Exception e) { Log.e("Simon","----"+e.toString()); } return null; } private String getProductArgs() { // TODO Auto-generated method stub StringBuffer xml=new StringBuffer(); try { String nonceStr=getNonceStr(); xml.append("<xml>"); List<NameValuePair> packageParams=new LinkedList<NameValuePair>(); packageParams.add(new BasicNameValuePair("appid",Constants.APP_ID)); packageParams.add(new BasicNameValuePair("body", "APP pay test")); packageParams.add(new BasicNameValuePair("mch_id", Constants.MCH_ID)); packageParams.add(new BasicNameValuePair("nonce_str", nonceStr)); packageParams.add(new BasicNameValuePair("notify_url", "https://www.baidu.com"));//寫你們的回調地址 packageParams.add(new BasicNameValuePair("out_trade_no",genOutTradNo())); packageParams.add(new BasicNameValuePair("total_fee", "1")); packageParams.add(new BasicNameValuePair("trade_type", "APP")); 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 genOutTradNo() { Random random = new Random(); // return "dasgfsdg1234"; //訂單號寫死的話只能支付一次,第二次不能生成訂單 return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes()); } //生成隨機號,防重發(fā) private String getNonceStr() { // TODO Auto-generated method stub Random random=new Random(); return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes()); } /** 生成簽名 */ private String getPackageSign(List<NameValuePair> params) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < params.size(); i++) { sb.append(params.get(i).getName()); sb.append('='); sb.append(params.get(i).getValue()); sb.append('&'); } sb.append("key="); sb.append(Constants.API_KEY); String packageSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase(); Log.e("Simon",">>>>"+packageSign); return packageSign; } /* * 轉換成xml */ private String toXml(List<NameValuePair> params) { StringBuilder sb = new StringBuilder(); sb.append("<xml>"); for (int i = 0; i < params.size(); i++) { sb.append("<"+params.get(i).getName()+">"); sb.append(params.get(i).getValue()); sb.append("</"+params.get(i).getName()+">"); } sb.append("</xml>"); Log.e("Simon",">>>>"+sb.toString()); return sb.toString(); } }
看完上述內容,你們掌握Android中怎么實現微信支付功能的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!
文章題目:Android中怎么實現微信支付功能
本文網址:http://jinyejixie.com/article2/ggejic.html
成都網站建設公司_創(chuàng)新互聯(lián),為您提供定制網站、品牌網站設計、移動網站建設、網站內鏈、網站維護、網站策劃
聲明:本網站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)