Android中怎么实现微信支付功能
Android中怎么实现微信支付功能,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
成都创新互联公司服务项目包括忻州网站建设、忻州网站制作、忻州网页制作以及忻州网络营销策划等。多年来,我们专注于互联网行业,利用自身积累的技术优势、行业经验、深度合作伙伴关系等,向广大中小型企业、政府机构等提供互联网行业的解决方案,忻州网站推广取得了明显的社会效益与经济效益。目前,我们服务的客户以成都为中心已经辐射到忻州省份的部分城市,未来相信会继续扩大服务区域并继续获得客户的支持与信任!
1. 去微信开放平台申请微信支付服务,绑定自己的应用这里具体不多讲,但是一定要申请完成,将会得到是三个参数
//appid 微信分配的公众账号ID public static final String APP_ID = ""; //商户号 微信分配的公众账号ID public static final String MCH_ID = ""; // API密钥,在商户平台设置 public static final String API_KEY= "";
**坑点提示:在微信开发平台设置包名和签名。这里的包名一定要和你自己的包名一样,就是manifest中的package,签名一定要和你用官方app生成的一样(https://open.weixin.qq.com/zh_CN/htmledition/res/dev/download/sdk/Gen_Signature_Android.apk)。
微信会根据你的填写的包名,然后对你的keystore进行一种算法,生成你的签名。包名和签名一定要和微信开放平台的相同。不过这里需要注意的是,如果你发布的正式版本,需要用官方app重新生成签名,然后在开放平台重新设置sign,因为测试版本的keystore与正式版的keystore不一样。总之,就是你用的keystore生成的sign要和微信开放平台的时刻保持一致。**
2. 准备工作做好了,接下来就是开发了,先下载微信的jar包,导入。
微信支付分为三个步骤
① .生成prepayId
@Override protected MapdoInBackground(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 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()); ListsignParams = new LinkedList (); 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 Mapresultunifiedorder; 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 signParams = new LinkedList (); 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 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 > { private ProgressDialog dialog; @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); dialog = ProgressDialog.show(MainActivity.this, "提示", "正在提交订单"); } @Override protected Map 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 xml=decodeXml(content); return xml; } @Override protected void onPostExecute(Map 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 decodeXml(String content) { try { Map xml = new HashMap (); 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(" "); List packageParams=new LinkedList (); 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()); } //生成随机号,防重发 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 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 params) { StringBuilder sb = new StringBuilder(); sb.append(" "); 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(" "); Log.e("Simon",">>>>"+sb.toString()); return sb.toString(); } }
看完上述内容,你们掌握Android中怎么实现微信支付功能的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注创新互联行业资讯频道,感谢各位的阅读!
文章名称:Android中怎么实现微信支付功能
当前网址:http://azwzsj.com/article/ggejic.html