1. Appliquer d'abord pour le développement et l'application sur la plate-forme Open WeChat. La plate-forme WECHAT Open générera l'identification unique de l'application de l'application. Étant donné que la garantie de paiement est requise, le nom du package d'application marchande et la signature de l'application doivent être liés sur la plate-forme ouverte, et le paiement ne peut être lancé normalement qu'après l'avoir configuré.
2. Enregistrer l'apprid (cela peut être placé dans l'application du projet)
Le package de pot WeChat est introduit dans le projet d'application marchande. Avant d'appeler l'API, vous devez enregistrer votre appid avec WeChat. Le code est le suivant:
final iwxapi msgapi = wxapifactory.createwxapi (context, null); // enregistrez l'application sur wechat msgapi.registerApp ("wxd930ea5d5a258f4f"); 3. Appelez l'API unique unifiée pour générer une commande de prépaiement. Après avoir obtenu le prépayé_ID, signez les paramètres et transmettez-les à l'application pour lancer le paiement.
exemple:
Le numéro de commande dans le code suivant doit être généré en arrière-plan
String url = "https://api.mch.weixin.qq.com/pay/UnifiedOrder"; Wxprepost post = new wxprepost (); poster.appid = "Votre appid"; post.mch_id = "Votre numéro de marchand"; post.NONCE_STR = StringUtils.GennonCestR (); // String aléatoire ** 1 post.body = "Nom du produit"; poster.detail = "Description du produit"; post.out_trade_no = out_trade_no; // Numéro de commande du marchand ** 2 post.total_fee = "Commodity Price"; // L'unité est divisée en post.spbill_create_ip = getLocalipaddress (); // adresse IP ** 3 post.notify_url = ""; // Ceci est l'adresse URL pour le backend pour accepter la notification de résultat post.trade_type = "app"; post.sign = genPackageSign (post); // signature ** 4 liste <nameValuepair> FirstSignParams = getFirstSignParams (post); String xml = TOXML (FIRSTSIGNPARAMS); String Entity = NULL; try {Entity = new String (xml.getBytes (), "ISO8859-1"); octet [] buf = util.httppost (URL, entité); if (buf! = null) {String Content = new String (buf); Map <string, string> map = decodexml (contenu); if (map! = null) {// Signer à nouveau (les champs participant à la signature sont: appid PartnerId prepayid non-thorymatelm package) string appid = ""; String prepayId = ""; String noncestr = ""; for (map.entry <string, string> entry: map.entryset ()) {if ("appid" .equals (entry.getKey ())) {appid = entry.getValue (); } else if ("prepay_id" .equals (entry.getKey ())) {prepayId = entry.getValue (); } else if ("nonce_str" .equals (entry.getKey ()))) {noncestr = entry.getValue (); }} Log.d (tag, "run ::" + appid + "/" + prepayid + "/" + noncestr + "/"); String TimeStamp = String.ValueOf (GentimeStamp ()); // OK Obtenez la chaîne de signature secondaire SecondPackageSign = GenseConDPackageSign (getSecondSignParams (appid, prepayid, noncestr, horodatamp)); PayReq req = new PayReq (); req.appid = appid; req.partnerid = "Numéro de marchand"; req.prepayId = prepayid; req.Noncestr = nonCest; req.timestamp = horodatage; req.packageValue = "signe = wxpay"; req.sign = secondPackagesign; req.extData = "application data"; // Facultatif // System.out.println ("GenPackagesIgn3:" + post.getSign () + "/" + secondPackageSign); // Avant le paiement, si la demande n'est pas enregistrée auprès de WeChat, vous devez d'abord appeler IWXMSG.RegisterApp pour enregistrer la demande sur WeChat Mapi.Sendreq (REQ); Log.d (tag, "run:" + appid + "/" + prepayid + "/" + noncestr + "/" + timestamp + "/" + secondpackagesign); }}} catch (exception e) {} BYTE STATIQUE PUBLIQUE [] HTTPPOST (URL de chaîne, entité de chaîne) {if (url == null || url.length () == 0) {log.e (tag, "httppost, url est null"); retourner null; } HttpClient httpClient = getNewHttpClient (); HTTPPOST HTTPPOST = NOUVEAU HTTPPOST (URL); essayez {httppost.SetEntity (new StronEntity (entité)); httppost.sethEader ("accepter", "application / json"); httppost.sethEader ("contenu-type", "application / json"); HttpResponse resp = httpclient.execute (httppost); if (resp.getStatusline (). getStaturScode ()! = httpstatus.sc_ok) {log.e (tag, "httpget fail, status code =" + resp.getStatusline (). getSaturScode ()); retourner null; } return EntityUtils.ToByTearray (resp.getEntity ()); } catch (exception e) {log.e (tag, "exception httppost, e =" + e.getMessage ()); e.printStackTrace (); retourner null; }} // Méthode pour obtenir une chaîne aléatoire publique statique String GenNoncestr () {Random Random = new Random (); return md5.getMessagediGest (string.valueof (random.nextint (10000)). GetBytes ()); } String privé toxml (list <nameValuepair> params) {StringBuilder sb = new StringBuilder (); sb.append ("<xml>"); pour (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>"); return sb.toString (); } public map <string, string> decodexml (String Content) {try {map <string, string> xml = new hashmap <> (); XmlPullParser parser = xml.newpullParser (); parser.setInput (new StringReader (contenu)); int event = parser.getEventType (); while (event! = xmlpullParser.end_Document) {String nodeName = parser.getName (); switch (event) {case xmlpullParser.Start_Document: Break; cas xmlpullParser.start_tag: if (! "xml" .equals (nodeName)) {xml.put (nodeName, parser.nextText ()); } casser; cas xmlpullparser.end_tag: break; } event = parser.next (); } return xml; } catch (exception e) {} return null; } @Nonnull Private List <NameValuePair> GetFirstSignParams (WXPRepost Params) {List <NameValuePair> packageParams = new LinkedList <> (); packageParams.add (new BasicNameValuepair ("appid", "appid")); packageParams.add (new BasicNameValuePair ("Body", params.body)); packageParams.add (nouveau BasicNameValuePair ("Détail", params.detail)); packageParams.add (new BasicNameValuepair ("mch_id", "numéro de marchand")); packageParams.add (new BasicNameValuePair ("nonce_str", params.Nonce_str)); packageParams.add (new BasicNameValuepair ("notify_url", params.notify_url)); packageParams.add (new BasicNameValuePair ("out_trade_no", params.out_trade_no)); packageParams.add (new BasicNameValuePair ("SPBill_create_ip", params.spbill_create_ip)); packageParams.add (new BasicNameValuePair ("total_fee", params.total_fee + "")); packageParams.add (new BasicNameValuePair ("Trade_type", params.trade_type)); packageParams.Add (new BasicNameValuePair ("Sign", params.Sign)); return packageParams; } classe publique wxprepost {// les paramètres qui doivent être apportés avec la chaîne publique appid; // Application AppID approuvée par WeChat Open Platform Public String MCH_ID; // Le numéro de marchand attribué par WeChat Pay Public String NONCE_STR; // chaîne aléatoire, pas plus de 32 chiffres. Algorithme de génération de nombres aléatoires recommandés Signe de chaîne publique; // Signature, voir l'algorithme de génération de signature Body String Body; // DESCRIPTION DU PRODUIT Le format de champ de transaction est conformément au format suivant en fonction de différents scénarios d'application: application - Nom de l'application qui doit être transmis sur le marché des applications - Nom du produit réel, Tiantian Aiying Eliminate - Game Recharge. String public out_trade_no; // Le numéro de commande à l'intérieur du système marchand, qui peut contenir des lettres dans les 32 caractères. Pour d'autres instructions, consultez le numéro de commande du marchand public int total_fee; // Le montant total de la commande est dans le centime. Pour plus de détails, consultez le montant du paiement public SPBill_create_ip; // la chaîne publique IP réelle notify_url; // L'adresse de rappel pour recevoir des notifications asynchrones de paiement WeChat, l'URL de notification doit être une URL directement accessible et ne peut pas transporter de paramètres. (Fourni en arrière-plan) public String Trade_type; // Type de paiement // Paramètres qui ne doivent pas être transportés de chaîne publique device_info; // Numéro de périphérique de terminal (numéro de stockage ou ID de dispositif de caissier), veuillez passer "Web" par défaut; // Détails du nom du produit Public String attach; // Données supplémentaires, renvoyées comme dans l'API de requête et la notification de paiement. Ce champ est principalement utilisé pour les données personnalisées des marchands transportant des commandes publiques Fee_Type; // Code de lettre à trois chiffres conforme à la norme ISO 4217, par défaut RMB: CNY, voir le type de devise pour d'autres listes de valeur pour plus de détails // Public String Time_Start; // L'heure de génération des commandes est yyyymmddhhmms, comme indiqué en 20091225091010, comme indiqué en 20091225091010. Pour d'autres détails, voir les règles de temps // public string time_expire; // Commandez le temps d'expiration, le format est yyymmddhhmms, comme indiqué en 20091227091010 à 9h10 le 27 décembre 2009. Veuillez vous référer aux règles de temps pour d'autres détails. Remarque: L'intervalle de temps d'expiration minimum doit être supérieur à 5 minutes. Public String Goods_tag; // Paramètres des étiquettes de produit, des bons ou des remises de réduction. Pour plus de détails, veuillez consulter les bons ou les réductions de réduction. // public String limit_pay; // no_credit - spécifiez que vous ne pouvez pas utiliser une carte de crédit pour payer la chaîne publique getAppid () {return appID; } public void setAppid (String AppID) {this.appid = appid; } public String getmch_id () {return mch_id; } public void setmch_id (String mch_id) {this.mch_id = mch_id; } public String getNONCE_STR () {return nonce_str; } public void setNonce_str (string nonce_str) {this.Nonce_str = nonce_str; } public String getSign () {return signe; } public void setSign (string signe) {this.sign = signe; } public String getBody () {return body; } public void setBody (String body) {this.body = body; } public String getout_trade_no () {return out_trade_no; } public void setout_trade_no (String out_trade_no) {this.out_trade_no = out_trade_no; } public int getTotal_fee () {return total_fee; } public void Settotal_Fee (int total_fee) {this.total_fee = total_fee; } public String getSpbill_create_ip () {return spbill_create_ip; } public void setSpBill_create_ip (String SPBill_create_ip) {this.spbill_create_ip = spbill_create_ip; } public String getNotify_url () {return notify_url; } public void setnotify_url (String notify_url) {this.notify_url = notify_url; } public String getTrade_type () {return prorade_type; } public void SetTrade_type (String Trade_Type) {this.trade_type = Trade_type; } public String getdevice_info () {return device_info; } public void setdevice_info (string device_info) {this.device_info = device_info; } public String getDetail () {return Detail; } public void setDetail (String Detail) {this.detail = détail; } public String getattach () {return attach; } public void setAttach (String attach) {this.attach = attach; } public String getFee_Type () {return fee_type; } public void setfee_type (String Fee_Type) {this.fee_type = fee_type; } public String gettime_start () {return time_start; } public void setTime_start (String time_start) {this.time_start = time_start; } public String gettime_expire () {return time_expire; } public void setTime_Expire (String time_expire) {this.time_expire = time_expire; } public String getGoods_tag () {return boots_tag; } public void setgoods_tag (String goods_tag) {this.goods_tag = bandoulière_tag; } public String getLIMIT_PAY () {return limit_pay; } public void setlimit_pay (string limit_pay) {this.limit_pay = limite_pay; }}Les paramètres donnés ici peuvent être obtenus par le terminal mobile eux-mêmes. Bien sûr, il est préférable de nous fournir les antécédents pour des raisons de sécurité.
Une fois le paiement terminé, WeChat rappellera WXPayentryActivity. Je n'entrerai pas dans les détails ici. Le document WeChat indique clairement que les résultats du paiement WECHAT renvoyés dans l'onSp () de WxpayentryActivity (Remarque: Ce résultat ne peut pas être le résultat de la réussite du produit. Nous devons utiliser le rappel WeChat au détroit de Taiwan et ensuite retourner au détroit de Taiwan pour nous dire le résultat du paiement).
if (resp.getType () == constantsapi.command_pay_by_wx) {int code = resp.errcode; switch (code) {case 0: log.d (tag, "onPayFinish, errCode =" + "Pay Success"); // Après le paiement de WeChat réussi, accédez à l'arrière-plan, le résultat de paiement renvoyé par arrière-plan est la base. // Ceci est le rappel une fois le paiement WeChat terminé. Voici une demande de contexte et lui demander de nous dire si le paiement réussit. casser; cas -1: toast.makeText (this, "Pay a échoué 1", toast.length_short) .show (); Log.d (tag, "onPayFinish, errcode =" + "Pay a échoué 1"); finition(); casser; Case -2: toast.makeText (this, "Pay annuler", toast.length_short) .show (); Log.d (tag, "onPayFinish, errcode =" + "payer annuler"); finition(); casser; par défaut: // toast.makeText (this, "Pay a échoué 2", toast.length_short) .show (); Log.d (tag, "onPayFinish, errcode =" + "Pay a échoué 2"); setResult (result_ok); finition(); casser; }}Ce qui précède est tout le contenu de cet article. J'espère que cela sera utile à l'apprentissage de tous et j'espère que tout le monde soutiendra davantage Wulin.com.