Android-based on the WeChat Open Platform v3SDK, develop the WeChat payment solution ., Androidv3sdk

Source: Internet
Author: User
Tags email account

Android-based on the open platform v3SDK, the development and payment are completed ., Androidv3sdk

I have heard that this is a pitfall before I come into contact with payment. I have prepared for it... I thought that I could have jumped into it. I didn't want to fill it out. After the call was successful, I felt that all my colleagues in the company were beautiful, the smog in Beijing seems to have seen the sun ~~~ Okay. The installation is over... Enter the subject

Development preparation:

1. Apply for an account on the Open Platform

2. After the application is created successfully, it is to fill in some official and very serious materials... (It may take about 7 days to review your app. If there is no accident, your app will be successfully reviewed the next day. Is it so happy? With appid, can I call the micro-mail payment ???? ------- Think too much, really)

3. payment requires additional application: data review, Account Verification, agreement signing, and other steps. (I remember, there are a lot of materials to be filled in for review ,,, account Verification means that after your review is successful, you will send an email to the email account you registered at the time of registration, which contains a random amount for Account Verification, agreement signing, slightly, too simple) be sure to read all the information in your email. Because some details are wrong, you may enter the mail for a long time ......

Formal development phase:

Question 1:

The official SDK can only be called once successfully and cannot be called during the next payment.

Solution:

It doesn't seem to be a serious method: Managing apps in mobile phone settings, clearing data, caching, and re-clicking can definitely be called (of course it's just one time ....)

Continue:

I think you should pay for it. I only read the document that calls the payment interface:

Later, I found that the required parameter prepayid could not be found. Later I found that this prepayid is a warm alternative when I call the "unified order" interface, however, the official SDK does not have the uniform order code. Pitfall ???

Therefore, you must first read the unified order document.

1. when you use your APP to call WXPayEntryActivity from the SDK down from the official website, copy it to your project. The package name must be. wxapi (I copied the package together ....)

2. In the project list file, enter:

 

3. Copy the AppRegister file in the SDK, replace it with your own appid, and then register it in the project list.

 

 

4. The point is, the activity for which your APP calls the payment. This is also called PayActivity.

To activate the payment page, register your app in this activity

 

Next, call the unified order to obtain the prepayid. The parameter is in xml format! We have to send the xml format!

 

When you call this method, the return value of this method is transmitted as the parameter. Wait for success to be returned !..

I encountered an error: Signature Error

My reason is that the parameter ConfigUtil. policy_url is an empty string.

It is also because the debug version is running without packaging.

After the return is successful, you can call the payment interface.

 

Don't forget to jump to the interface in this step ,,,,,

Not redirected to payment may be the debug version you run, and no package .....

The complete code of my PayActivity is as follows:

Package com. example. taijiapp. ui; import java. io. stringReader; import java.net. inetAddress; import java.net. networkInterface; import java.net. socketException; import java. util. enumeration; import java. util. hashMap; import java. util. using list; 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. x Mlpull. v1.XmlPullParser; import com. example. taijiapp. r; import com. example. taijiapp. util. constants; import com. example. taijiapp. util. MD5; import com. example. taijiapp. util. t; import com. example. taijiapp. util. util; import com. example. taijiapp. utils. configUtil; import com. tencent. mm. sdk. modelpay. payReq; import com. tencent. mm. sdk. openapi. IWXAPI; import com. tencent. mm. sdk. openapi. wxapifacloud; import android. app. Activity; import android. app. progressDialog; import android. content. context; import android.net. wifi. wifiInfo; import android.net. wifi. wifiManager; import android. OS. asyncTask; import android. OS. bundle; import android. util. log; import android. util. xml; import android. view. view; import android. widget. button; public class PayActivity extends Activity {PayReq req; private IWXAPI msgApi; Map <String, String> resul Tunifiedorder; StringBuffer sb; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. pay); req = new PayReq (); sb = new StringBuffer (); msgApi = wxapifacloud. createWXAPI (this, Constants. APP_ID);/*** register the app to */boolean registerApp = msgApi. registerApp (Constants. APP_ID); T. show (this, "register ========" + registerApp + ""); Button appayBtn = (Button) FindViewById (R. id. appay_btn); Button check_pay_btn = (Button) findViewById (R. id. check_pay_btn); appayBtn. setOnClickListener (new View. onClickListener () {@ Overridepublic void onClick (View v) {GetPrepayIdTask getPrepayId = new getprepayidtask(response response getprepayid.exe cute ();}}); /*** register the app to */check_pay_btn.setOnClickListener (new View. onClickListener () {@ Overridepublic void onClick (View v) {genPayReq (); sendPa YReq () ;}}); // generate the signature parameter // Button appay_pre_btn = (Button) findViewById (R. id. appay_pre_btn); // appay_pre_btn.setOnClickListener (new View. onClickListener () {// @ Override // public void onClick (View v) {// genPayReq ();//}//});} /*** generate the signature */private String genPackageSign (List <NameValuePair> params) {StringBuilder sb = new StringBuilder (); for (int I = 0; I <params. size (); I ++) {sb. append (params. get (I ). getNa Me (); sb. append ('='); sb. append (params. get (I ). getValue (); sb. append ('&');} sb. append ("key ="); sb. append (Constants. KEY); Log. e ("splicing ====", sb. toString (); String packageSign = MD5.getMessageDigest (sb. toString (). getBytes ()). toUpperCase (); Log. e ("orion generate signature ===", packageSign); return packageSign ;} /*** signature tool does not include merchant keys-do not need to temporarily = * encoding format UTF-8 = * @ return */public static String createSignNoKey (List <NameValuePair> param S) {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 ('&');} String signStr = sb. toString (); String subStr = signStr. substring (0, signStr. length ()-1); // note that sign is converted to uppercase return MD5.getMessageDigest (subStr. getBytes ()). toUpperCase ();} private String genAppSign (List <NameValuePair> par Ams) {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. KEY); this. sb. append ("sign str \ n" + sb. toString () + "\ n"); String appSign = MD5.getMessageDigest (sb. toString (). getBytes (); Log. e ("orion", appSign); return appSign;} private Str Ing 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 ("orion", sb. toString (); return sb. toString ();} private class GetPrepayIdTask extends AsyncTask <Void, Void, Map <String, String >>{ private ProgressDialog dialog; @ Overrideprotected void onPreExecute () {dialog = ProgressDialog. show (PayActivity. this, getString (R. string. app_tip), getString (R. string. getting_prepayid) ;}@ Overrideprotected void onPostExecute (Map <String, String> result) {if (dialog! = Null) {dialog. dismiss ();} sb. append ("prepay_id \ n" + result. get ("prepay_id") + "\ n"); resultunifiedorder = result;} @ Overrideprotected void onCancelled () {super. onCancelled () ;}@ Overrideprotected Map <String, String> doInBackground (Void... params) {String url = String. format ("https://api.mch.weixin.qq.com/pay/unifiedorder"); String entity = genProductArgs (); Log. e ("orion = sent in the Past", entity); byte [] buf = U Til. httpPost (url, entity); String content = new String (buf); Log. e ("orion", content); Map <String, String> xml = decodeXml (content); return xml ;}} 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) {// instantiate the student object 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;}/*** generate a random number * @ ret Urn */private String genNonceStr () {Random random = new Random (); return MD5.getMessageDigest (String. valueOf (random. nextInt (10000 )). getBytes ();}/*** timestamp * @ return */private long genTimeStamp () {return System. currentTimeMillis ()/1000;}/*** Random Number * @ return */private String genOutTradNo () {random Random = new Random (); return MD5.getMessageDigest (String. valueOf (random. nextInt (10000 )). getBytes ());} /*** Get the IP address of the device * @ return */public String getLocalIpAddress () {try {for (Enumeration <NetworkInterface> en = NetworkInterface. getNetworkInterfaces (); en. hasMoreElements ();) {NetworkInterface intf = en. nextElement (); for (Enumeration <InetAddress> enumIpAddr = intf. getInetAddresses (); enumIpAddr. hasMoreElements ();) {InetAddress inetAddress = enumIpAddr. nextElement (); if (! InetAddress. isLoopbackAddress () {return inetAddress. getHostAddress (). toString () ;}}} catch (SocketException ex) {} return null;} private String getWifiIp () {// get wifi service WifiManager wifiManager = (WifiManager) getSystemService (Context. WIFI_SERVICE); // determines whether wifi is enabled if (! WifiManager. isWifiEnabled () {wifiManager. setWifiEnabled (true);} WifiInfo wifiInfo = wifiManager. getConnectionInfo (); int ipAddress = wifiInfo. getIpAddress (); String ip = intToIp (ipAddress); return ip ;} /*** convert to the IP address format * @ param I * @ return */private String intToIp (int I) {return (I & 0xFF) + ". "+ (I> 8) & 0xFF) + ". "+ (I> 16) & 0xFF) + ". "+ (I> 24 & 0xFF);} private String genProductArgs () {StringBuffer xml = new StringBuffer (); String ip = getWifiIp (); if (ip = "" & ip = "") {ip = getLocalIpAddress ();} try {String nonceStr = genNonceStr (); xml. append ("</xml>"); List <NameValuePair> packageParams = new queue List <NameValuePair> (); packageParams. add (new BasicNameValuePair ("appid", Constants. APP_ID); packageParams. add (new BasicNameValuePair ("body", "APPtest"); packageParams. add (new BasicNameValuePair ("mch_id", Constants. MCH_ID); packageParams. add (new BasicNameValuePair ("nonce_str", nonceStr); packageParams. add (new BasicNameValuePair ("notify_url", ConfigUtil. NOTIFY_URL); packageParams. add (new BasicNameValuePair ("out_trade_no", genOutTradNo (); packageParams. add (new BasicNameValuePair ("spbill_create_ip", ip); packageParams. add (new BasicNameValuePair ("total_fee", "100"); packageParams. add (new BasicNameValuePair ("trade_type", "APP"); String sign = genPackageSign (packageParams); packageParams. add (new BasicNameValuePair ("sign", sign); String xmlstring = toXml (packageParams); return xmlstring;} catch (Exception e) {Log. e ("TAG", "fail, ex =" + e. getMessage (); return null ;}} private void genPayReq () {req. appId = Constants. APP_ID; req. partnerId = Constants. 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 <NameValuePair> signParams = new partition List <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"); Log. e ("orion = genPayReq ==================", signParams. toString ();} private void sendPayReq () {boolean sendReq = msgApi. sendReq (req); T. show (this, "Jump ====" + sendReq + "");}}

There is no class, NA: http://download.csdn.net/detail/meijuanyou/9571223 to download a copy of your own...

Refer to blog https://pay.weixin.qq.com/wiki/doc/api/app/app.php? Chapter = 9_1

I hope it will help you...

 

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.