Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to integrate WeChat Pay in Android

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

How to integrate WeChat Pay in Android? for this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible way.

Note: in order to inherit the functions of WeChat Pay and Alipay, you must have the following configuration information. The secret key of WeChat Pay and Alipay payment application is provided to the developer (of course, you can also apply for it yourself). The configuration information has been uniformly used (for security reasons, Wechat Alipay recommends these data in the service)

Public class ParameterConfig {public static final String GANHOST = "http://101.226.197.11"; / / server address ip (based on your replacement) / * Wechat * / appid public static final String WX_APP_ID ="; / / fill in the / / merchant number of your own project public static final String WX_MCH_ID =" / / fill in the / / API key of your own project, and set public static final String WX_API_KEY = "" on the merchant platform; / / fill in the / / server callback API public static final String WX_notifyUrl = GANHOST+ "/ service/orderComplete" of your own project. / / for WeChat Pay's successful callback (fill in according to your own needs) / * * Alipay * / / merchant PID public static final String PARTNER = ""; / / fill in your own project / / merchant collection account public static final String SELLER = ""; / / fill in your own project / / merchant private key, pkcs8 format public static final String RSA_PRIVATE = "" / / fill in the public static final String aliPay_notifyURL of your own project = GANHOST+ "/ service/alipay/orderComplete"; / / successful callback of Alipay}

1. The prerequisite for WeChat Pay integration (1) is to import the Wechat .jar package, which can be downloaded from the development platform, and then placed on the libs folder. (2) mainfest needs to be configured

B.activity configuration, where com.gan.mypay is changed to its own package name (if your package name is different from the package name under src, what you want here is the name configured in manifest. You also need to establish a package with your package name as the path in src. Make sure you have this activity.) this activity is the activty to be called back by WeChat Pay.

Android:name= "com.gan.mypay.wxapi.WXPayEntryActivity" android:exported= "true" android:launchMode= "singleTop" / >

two。 Code inheritance (1) first of all, there must be a product page MainActivity, which is used to collect product information. Here, we need to generate an order interactively in the background. We make a fake order here. MainActivity.java (xutils injection is used here)

@ ContentView (R.layout.activity_main) public class MainActivity extends Activity {private Goods goods; private String username; private String mobile; private String adress; private int count; @ ViewInject (R.id.product_ordsubmit_username) private TextView usernameTV; @ ViewInject (R.id.product_ordsubmit_phone) private TextView phoneTV; @ ViewInject (R.id.product_ordsubmit_adress) private TextView adressTV; @ ViewInject (R.id.product_ordsubmit_desc) private TextView descTV @ ViewInject (R.id.product_ordsubmit_price) private TextView priceTV; @ ViewInject (R.id.product_ordsubmit_intg) private TextView intgTV; @ ViewInject (R.id.product_ordsubmit_count1) private TextView countTV1; @ ViewInject (R.id.product_ordsubmit_count) private TextView countTV; @ ViewInject (R.id.product_ordsubmit_intgtotal1) private TextView intgtotal1TV; @ ViewInject (R.id.product_ordsubmit_intgtotal2) private TextView intgtotal2TV @ ViewInject (R.id.product_ordsubmit_pricetotal1) private TextView pricetotal1TV; @ ViewInject (R.id.product_ordsubmit_pricetotal2) private TextView pricetotal2TV; @ ViewInject (R.id.product_ordsubmit_counttotal) private TextView counttotalTV; @ ViewInject (R.id.product_ordsubmit_ok) private Button okBtn; @ ViewInject (R.id.product_ordsubmit_say_et) private TextView sayEt; @ ViewInject (R.id.product_ordsubmit_img) private ImageView img @ Override protected void onCreate (Bundle savedInstanceState) {super.onCreate (savedInstanceState); ViewUtils.inject (this); goods = new Goods (); goods.costprice=100; goods.productid=692356222; goods.producttypeid=11; goods.productname= "Test goods"; goods.discountprice=0.01; goods.productdescription= "Product description"; goods.companydesc= "Test Merchant brief description" Goods.comanyadress= "Merchant address unknown"; goods.companyname= "Test Merchant"; goods.score=1; goods.status=1; goods.stock=300; count=1; initData (); initView ();} private void initData () {username = "customer name"; mobile = "13800380038"; adress= "customer address" } private void initView () {usernameTV.setText ("consignee:" + username); phoneTV.setText (mobile+ "); adressTV.setText (adress); descTV.setText (goods.productdescription); priceTV.setText (" ¥"+ goods.discountprice); intgTV.setText (" Credit: "+ goods.score); countTV1.setText (" X "+ count) CountTV.setText (count+ "); intgtotal1TV.setText (" get "+ count*goods.score+" points "); intgtotal2TV.setText (" points: "+ count*goods.score); counttotalTV.setText (" Total "+ count+" pieces "); pricetotal1TV.setText (" ¥"+ Arith.mul (goods.discountprice, count)); pricetotal2TV.setText (" ¥"+ Arith.mul (goods.discountprice, count)) / / ImageLoader.getInstance () .displayImage (goods.pic1, img);} / * * increase the number * @ param v * / @ OnClick (R.id.product_ordsubmit_count_add) public void add (View v) {count++; countTV1.setText ("X" + count); countTV.setText (count+ "") Intgtotal1TV.setText ("total" + count*goods.score+ "points"); intgtotal2TV.setText ("points: + count*goods.score"); counttotalTV.setText ("total" + count+ "pieces"); pricetotal1TV.setText ("¥" + Arith.mul (goods.discountprice, count)); pricetotal2TV.setText ("¥" + Arith.mul (goods.discountprice, count)) } / * * reduce the number * @ param v * / @ OnClick (R.id.product_ordsubmit_count_sub) public void sub (View v) {if (count > 1) {count--; countTV1.setText ("X" + count); countTV.setText (count+ "") Intgtotal1TV.setText ("total" + count*goods.score+ "points"); intgtotal2TV.setText ("points: + count*goods.score"); counttotalTV.setText ("total" + count+ "pieces"); pricetotal1TV.setText ("¥" + Arith.mul (goods.discountprice, count)); pricetotal2TV.setText ("¥" + Arith.mul (goods.discountprice, count)) Submit order * @ param v * / @ OnClick (R.id.product_ordsubmit_ok) public void submit (View v) {final OrderInfo orderInfo=new OrderInfo (); orderInfo.userid=13752; orderInfo.areacode=23; orderInfo.buildno= "10"; orderInfo.roomno= "1001"; orderInfo.producttypeid=goods.producttypeid; orderInfo.productid=goods.productid OrderInfo.amount=goods.discountprice;// unit price orderInfo.account=count;// quantity orderInfo.totalamount=Arith.mul (goods.discountprice, count); / / double offsetamount;// deduction amount orderInfo.score=count*goods.score; / / int assessitem;// evaluation item / / int assesslevel;// evaluation level / / String assesscontent;// evaluation content / / long payid= / / payment No. OrderInfo.status=2;// payment status orderInfo.type=11;// Commodity orderInfo.usermemo = sayEt.getText (). ToString (); / / owner's Note orderInfo.address = adress; orderInfo.productname = goods.productname;// orderInfo.desccontext = goods.productdescription;// orderInfo.outtradeno=System.currentTimeMillis () + "+ orderInfo.userid; orderInfo.merchantid=goods.companyid; submitorder (orderInfo) } / * order submitted successfully, enter the payment interface * @ param orderInfo * @ return * / private void submitorder (OrderInfo orderInfo) {Intent intent=new Intent (this, SelectPayTypeActivity.class); intent.putExtra ("data", orderInfo); startActivity (intent);}}

(2) Click the confirm button in mainactivty to call the payment method selection page SelectPayTypeActivity, which is used to initiate payment selection. (3) call Wechat (WXpayUtil) according to the payment method.

Public class WXpayUtil {private IWXAPI api; private OrderInfo order; private Context context; private PayReq req; private Map resultunifiedorder; private static final String TAG = "ewuye.online.SelectPayTypeActivity"; public WXpayUtil (Context mcontext,OrderInfo order) {/ / initialize WeChat Pay this.order=order; this.context=mcontext If (TextUtils.isEmpty (ParameterConfig.WX_APP_ID) | | TextUtils.isEmpty (ParameterConfig.WX_MCH_ID) | | TextUtils.isEmpty (ParameterConfig.WX_API_KEY)) {new AlertDialog.Builder (context) .setTitle ("warning") .setMessage ("need to configure WX_APP_ID | WX_MCH_ID | WX_API_KEY\ nPlease configure it in ParameterConfig.java") .setPositiveButton ("OK" New DialogInterface.OnClickListener () {public void onClick (DialogInterface dialoginterface, int I) {/ / (Activity) context) .finish () ). Show (); return;} api = WXAPIFactory.createWXAPI (context, null); req = new PayReq (); / / generate prepay_id GetPrepayIdTask getPrepayId = new GetPrepayIdTask (); getPrepayId.execute () } / * is used to obtain * @ author 95 * * / private class GetPrepayIdTask extends AsyncTask > {private ProgressDialog dialog; @ Override protected void onPreExecute () {dialog = ProgressDialog.show (context, "prompt", "getting prepaid order...") } @ Override protected void onPostExecute (Map result) {if (dialog! = null) {dialog.dismiss ();} resultunifiedorder=result; genPayReq ();} @ Override protected void onCancelled () {super.onCancelled ();} @ Override protected Map doInBackground (Void... Params) {String url = String.format ("https://api.mch.weixin.qq.com/pay/unifiedorder"); String entity = genProductArgs (); Log.e (" orion ", entity); byte [] buf = httpPost (url, entity); String content = new String (buf); Log.e (" orion ", content); Map xml=decodeXml (content) Return xml;}} private void genPayReq () {req.appId = ParameterConfig.WX_APP_ID; req.partnerId = ParameterConfig.WX_MCH_ID; req.prepayId = resultunifiedorder.get ("prepay_id"); req.packageValue = "prepay_id=" + resultunifiedorder.get ("prepay_id"); req.nonceStr = genNonceStr (); 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); Log.e ("orion", signParams.toString ()); sendPayReq ();} private void sendPayReq () {api.registerApp (ParameterConfig.WX_APP_ID); api.sendReq (req);} private String genProductArgs () {StringBuffer xml = new StringBuffer () Try {String nonceStr = genNonceStr (); xml.append ("); List packageParams = new LinkedList (); packageParams.add (new BasicNameValuePair (" appid ", ParameterConfig.WX_APP_ID)); packageParams.add (new BasicNameValuePair (" body ", order.productname)); packageParams.add (new BasicNameValuePair (" mch_id ", ParameterConfig.WX_MCH_ID)) PackageParams.add (new BasicNameValuePair ("nonce_str", nonceStr)); packageParams.add (new BasicNameValuePair ("notify_url", ParameterConfig.WX_notifyUrl)); packageParams.add (new BasicNameValuePair ("out_trade_no", genOutTradNo ()); packageParams.add (new BasicNameValuePair ("spbill_create_ip", "127.0.0.1")) PackageParams.add (new BasicNameValuePair ("total_fee", (int) (order.totalamount*100) + ")); packageParams.add (new BasicNameValuePair (" trade_type "," APP ")); String sign = genPackageSign (packageParams); packageParams.add (new BasicNameValuePair (" sign ", sign)); String xmlstring = toXml (packageParams) Return new String (xmlstring.toString (). GetBytes (), "ISO8859-1"); / / return xmlstring;} catch (Exception e) {Log.e (TAG, "genProductArgs fail, ex =" + e.getMessage ()); return null;} 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(ParameterConfig.WX_API_KEY); String appSign = getMessageDigest(sb.toString().getBytes()); Log.e("orion",appSign); return appSign; } private HttpClient getNewHttpClient() { try { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sf, 443)); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); return new DefaultHttpClient(ccm, params); } catch (Exception e) { return new DefaultHttpClient(); } } private class SSLSocketFactoryEx extends SSLSocketFactory { SSLContext sslContext = SSLContext.getInstance("TLS"); public SSLSocketFactoryEx(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { super(truststore); TrustManager tm = new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws java.security.cert.CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws java.security.cert.CertificateException { } }; sslContext.init(null, new TrustManager[] { tm }, null); } @Override public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException { return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose); } @Override public Socket createSocket() throws IOException { return sslContext.getSocketFactory().createSocket(); } } public byte[] httpPost(String url, String entity) { if (url == null || url.length() == 0) { Log.e(TAG, "httpPost, url is null"); return null; } HttpClient httpClient = getNewHttpClient(); HttpPost httpPost = new HttpPost(url); try { httpPost.setEntity(new StringEntity(entity)); httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-type", "application/json"); HttpResponse resp = httpClient.execute(httpPost); if (resp.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { Log.e(TAG, "httpGet fail, status code = " + resp.getStatusLine().getStatusCode()); return null; } return EntityUtils.toByteArray(resp.getEntity()); } catch (Exception e) { Log.e(TAG, "httpPost exception, e = " + e.getMessage()); e.printStackTrace(); return null; } } private String genOutTradNo() { Random random = new Random(); return getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes()); } 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("orion",e.toString()); } return null; } private String genNonceStr() { Random random = new Random(); return getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes()); } private long genTimeStamp() { return System.currentTimeMillis() / 1000; } public String getMessageDigest(byte[] buffer) { char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; try { MessageDigest mdTemp = MessageDigest.getInstance("MD5"); mdTemp.update(buffer); byte[] md = mdTemp.digest(); int j = md.length; char str[] = new char[j * 2]; int k = 0; for (int i = 0; i < j; i++) { byte byte0 = md[i]; str[k++] = hexDigits[byte0 >

> 4 & 0xf]; str [knot +] = hexDigits [byte0 & 0xf];} return new String (str);} catch (Exception e) {return null;}} / * * generate signature * / private String genPackageSign (List params) {StringBuilder sb = new StringBuilder (); for (int I = 0 I < params.size (); getName +) {sb.append (params.get (I). GetName ()); sb.append ('='); sb.append (params.get (I). GetValue ()); sb.append ('&');} sb.append ("key="); sb.append (ParameterConfig.WX_API_KEY) String packageSign = getMessageDigest (sb.toString (). GetBytes ()). ToUpperCase (); Log.e ("orion", packageSign); return packageSign;} private String toXml (List params) {StringBuilder sb = new StringBuilder (); sb.append (""); for (int I = 0; I < params.size (); iTunes +) {sb.append ("") Sb.append (params.get (I). GetValue ()); sb.append ("");} sb.append (""); Log.e ("orion", sb.toString ()); return sb.toString ();}}

Activity of Wechat callback

Package com.gan.mypay.wxapi;import com.gan.mypay.ParameterConfig;import com.gan.mypay.R;import com.gan.mypay.SelectPayTypeActivity;import com.tencent.mm.sdk.constants.ConstantsAPI;import com.tencent.mm.sdk.modelbase.BaseReq;import com.tencent.mm.sdk.modelbase.BaseResp;import com.tencent.mm.sdk.openapi.IWXAPI;import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;import com.tencent.mm.sdk.openapi.WXAPIFactory;import android.app.Activity;import android.app.AlertDialog Import android.content.Intent;import android.os.Bundle;import android.util.Log;import android.widget.Toast;public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {private static final String TAG = "MicroMsg.SDKSample.WXPayEntryActivity"; private IWXAPI api; / / private TextView reulttv; @ Override public void onCreate (Bundle savedInstanceState) {super.onCreate (savedInstanceState); setContentView (R.layout.wx_pay_result); api = WXAPIFactory.createWXAPI (this, ParameterConfig.WX_APP_ID) Api.handleIntent (getIntent (), this);} @ Override protected void onNewIntent (Intent intent) {super.onNewIntent (intent); setIntent (intent); api.handleIntent (intent, this);} @ Override public void onReq (BaseReq req) {} @ Override public void onResp (BaseResp resp) {Log.d (TAG, "onPayFinish, errCode =" + resp.errCode) If (resp.getType () = = ConstantsAPI.COMMAND_PAY_BY_WX) {AlertDialog.Builder builder = new AlertDialog.Builder (this); builder.setTitle ("prompt"); / / builder.setMessage (getString (R.string.pay_result_callback_msg, String.valueOf (resp.errCode)); builder.show (); Intent intent; int code = resp.errCode Switch (code) {case 0: Toast.makeText (this, "payment succeeded", 0). Show (); intent=new Intent (this,SelectPayTypeActivity.class); intent.putExtra ("result", 0); startActivity (intent); finish (); break Case-1: Toast.makeText (this, "payment failed", 0). Show (); intent=new Intent (this,SelectPayTypeActivity.class); intent.putExtra ("result",-1); startActivity (intent); finish (); break Case-2: Toast.makeText (this, "payment cancellation", 0). Show (); intent=new Intent (this,SelectPayTypeActivity.class); intent.putExtra ("result",-2); startActivity (intent); finish (); break; default: break This is the answer to the question about how to integrate WeChat Pay in Android. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report