C # version of the example _c# of micro-scan code payment on PC side tutorial

Source: Internet
Author: User
Tags datetime openid throw exception server port

After a long time, the micro-letter official finally released the. NET Demo.

Main code:

/** * Generate direct Payment URL, payment URL is valid for 2 hours, Mode II * @param productId Commodity ID * @return mode two URL/public string Getpayurl (String Pro Ductid, string body, string attach, int total_fee, string goods_tag) {Log.info (this. GetType ().

   ToString (), "Native pay Mode 2 URL is producing ...");
   Wxpaydata data = new Wxpaydata (); Data. SetValue ("Body", body);//Product description data. SetValue ("Attach", attach)//Append data. SetValue ("Out_trade_no", productId);//random string data. SetValue ("Total_fee", total_fee);//Total amount data. SetValue ("Time_start", DateTime.Now.ToString ("YYYYMMDDHHMMSS"))//Transaction start time data. SetValue ("Time_expire", DateTime.Now.AddMinutes (10). ToString ("YYYYMMDDHHMMSS"))//Transaction end time data. SetValue ("Goods_tag", Goods_tag)//merchandise mark data. SetValue ("Trade_type", "NATIVE");//transaction type data. SetValue ("product_id", productId);//Product ID wxpaydata result = wxpayapi.unifiedorder (data);//Call Uniform down-interface String url = Res Ult. GetValue ("Code_url"). ToString ()//Gets the two-dimensional Code link log.info (this. GetType (). ToString (), "Get NATIve pay mode 2 URL: "+ URL);
  return URL;

 }

Configuration information:

public class Config {//======= "Basic information Settings" =====================================/* Micro-information configuration * APPID: Binding paid APPID (must be configured) * Mchid: Merchant Number (must be configured) * Key: Merchant payment key, refer to account opening mail settings (must be configured) * Appsecret: Public account Secert (only JSAPI payment needs to be configured) *
  PID = "Your micro-letter public number AppID";
  Public Const String Mchid = "Merchant Number of your micro-trust number";
  Public Const String key = "Your micro-trust merchant payment key";

  Public Const string Appsecret = "Appsecret of your micro-trust"; ======= "Certificate path Settings" =====================================/* certification path, note that the absolute path should be filled (only refund, order required)/Public const string Sslce
  Rt_path = "CERT/APICLIENT_CERT.P12";



  Public Const string Sslcert_password = "1233410002"; ======= "pay result notification URL" =====================================/* payment result notification callback URL for merchant to receive payment result/Public const string Notify_u

  RL = "http://your website/pay/resultnotifypage.aspx"; ======= "Merchant System background Machine IP" =====================================/* This parameter can be manually configured or automatically obtained in the program/Public const string IP = "Your server


  IP "; ======= "Proxy server Settings" ===================================/* Default IP andPort number is 0.0.0.0 and 0, at this time does not open the agent (if necessary to set up)/Public const string proxy_url = ""; ======= "Escalation Information Configuration" ===================================/* Speed report level, 0. Close the report; 1. Reporting only when errors are reported;

  2. Full report * * Public const int REPORT_LEVENL = 1; ======= "Log Level" ===================================/* log level, 0. Do not output log; 1. Output only error messages; 2. Output error and normal information;
 3. Output error message, normal information and debugging information * * Public const int LOG_LEVENL = 0;

 }

Do not use proxies to annotate the following code for post and get methods inside HttpService.cs:

Set Proxy Server
    //webproxy proxy = new WebProxy ();       Defines a Gateway object
    //proxy. Address = new Uri (config.proxy_url);    Gateway server port: Port
    //request. Proxy = proxy;

Unify the order:

/** * * @param wxpaydata Inputobj submitted to unified Single API parameters * @param int timeOut Timeout * @throws wxpayexception * @return return when successful, other throw exception/public static Wxpaydata Unifiedorder (wxpaydata inputobj, int timeOut = 6) {String url = "
   Https://api.mch.weixin.qq.com/pay/unifiedorder "; Detection required parameter if (!inputobj.isset ("Out_trade_no")) {throw new Wxpayexception ("Missing uniform payment interface required Parameters out_trade_no!
   "); else if (!inputobj.isset ("body") {throw new Wxpayexception ("Missing uniform payment interface required Parameters body!
   "); else if (!inputobj.isset ("Total_fee")) {throw new Wxpayexception ("Missing uniform payment interface required Parameters total_fee!
   "); else if (!inputobj.isset ("Trade_type")) {throw new Wxpayexception ("Missing uniform payment interface required Parameters trade_type!
   "); }//association parameter if (inputobj.getvalue ("Trade_type"). ToString () = = "Jsapi" &&!inputobj.isset ("OpenID")) {throw new Wxpayexception ("in the unified payment interface, missing required parameters openid! Trade_type for Jsapi, OpenID is required to fill the parameters!
   "); } if (Inputobj.getvalue ("Trade_type"). ToString () = "NATIVE" &&!inputobj.isset ("product_id")) {throw new Wxpayexception ("Unified payment interface, missing required parameters product_id! When Trade_type is Jsapi, product_id is a required parameter!
   "); The///asynchronous notification URL is not set, then use the URL if (!inputobj.isset ("Notify_url")) in the configuration file {inputobj.setvalue ("Notify_url"), Config.noti Fy_url)//Asynchronous Notification URL} inputobj.setvalue ("AppID", config.appid);//Public Account ID inputobj.setvalue ("mch_id", Config.mchid); Merchant number Inputobj.setvalue ("Spbill_create_ip", CONFIG.IP)//terminal IP inputobj.setvalue ("Nonce_str", Generatenoncestr ())
   ;//random string//Signature Inputobj.setvalue ("sign", inputobj.makesign ());

   string xml = Inputobj.toxml ();

   var start = DateTime.Now;
   Log.debug ("Wxpayapi", "Unfiedorder Request:" + XML);
   String response = Httpservice.post (XML, URL, False, TimeOut);

   Log.debug ("Wxpayapi", "Unfiedorder response:" + response);
   var end = DateTime.Now; int timecost = (int) (End-start).

   TotalMilliseconds);
   Wxpaydata result = new Wxpaydata (); Result.

   FromXml (response); Reportcosttime(URL, timecost, result);//speed report return result;

 }

Look at my invocation example:

Makeqrcode.aspx page Copy:

public partial class Pay_MakeQRCode:System.Web.UI.Page
{
 protected void Page_Load (object sender, EventArgs e) c3/>{
  if (!string. IsNullOrEmpty (base. request.querystring["Data"])
  {
   string str = base. request.querystring["Data"];
   Bitmap image = new Qrcodeencoder
   {
    Qrcodeencodemode = Qrcodeencoder.encode_mode. BYTE,
    qrcodeerrorcorrect = qrcodeencoder.error_correction. M,
    qrcodeversion = 0,
    Qrcodescale = 4
   }. Encode (str, encoding.default);
   MemoryStream ms = new MemoryStream ();
   Image. Save (MS, imageformat.png);
   Base. Response.BinaryWrite (Ms. GetBuffer ());
   Base. Response.End ();}}

This page is used to generate two-dimensional code and requires the introduction of ThoughtWorks.QRCode.dll components.

I use mode two, the callback page is resultnotifypage.aspx, the callback page that is filled in with the configuration information.

protected void Page_Load (object sender, EventArgs e) {resultnotify resultnotify = new Resultnotify (this);
  Wxpaydata res = resultnotify.processnotify2 (); if (res. GetValue ("return_code") = = "SUCCESS") {//Enquiry Micro-letter Order information String paysignkey = configurationmanager.appsettings["Paysignke" Y "].
   ToString (); String mch_id = configurationmanager.appsettings["mch_id"].
   ToString (); String appId = configurationmanager.appsettings["AppId"].

   ToString ();
   Queryorder Queryorder = new Queryorder ();
   Queryorder.appid = AppID;
   queryorder.mch_id = mch_id; queryorder.transaction_id = Res. GetValue ("transaction_id").
   ToString ();
   Queryorder.out_trade_no = "";

   Queryorder.nonce_str = Tenpayutil.getnoncestr ();
   Tenpayutil Tenpay = new Tenpayutil ();
   OrderDetail orderdeatil = Tenpay.getorderdetail (Queryorder, Paysignkey); Write a micro-letter record (new Vinson ()).
   Writereturnwxdetail (Orderdeatil);
  Write a Recharge record filliedonline (ORDERDEATIL.OUT_TRADE_NO); } Response.Write (Res.
  TOXML ()); ResponSe.
 End ();

 }

  Sweep code after the success of the payment will be asynchronous to this page to execute code, our own business logic will be written here. Using the Processnotify () function is not a good way to do this, but we'll just have to change it a little bit. Add ProcessNotify2 function:
 

Public Wxpaydata ProcessNotify2 () {Wxpaydata notifydata = Getnotifydata (); Check the payment result for transaction_id existence if (!notifydata.isset ("transaction_id")) {//If transaction_id does not exist, return the result immediately to the micro-letter payment background W
    Xpaydata res = new Wxpaydata (); Res.
    SetValue ("transaction_id", ""); Res.
    SetValue ("Return_code", "FAIL"); Res.
    SetValue ("Return_msg", "The result of the payment of the micro-letter order number does not exist");
   return res; String transaction_id = Notifydata.getvalue ("transaction_id").

   ToString (); Check the order to determine the authenticity of the order if (!
    Queryorder (transaction_id)) {//If the order query fails, return the result immediately to the micro-letter payment background Wxpaydata res = new Wxpaydata (); Res.
    SetValue ("transaction_id", transaction_id); Res.
    SetValue ("Return_code", "FAIL"); Res.
    SetValue ("Return_msg", "Order query failed");
   return res;
    //Query Order success Else {Wxpaydata res = new Wxpaydata (); Res.
    SetValue ("transaction_id", transaction_id); Res.
    SetValue ("Return_code", "SUCCESS"); Res.
    SetValue ("Return_msg", "OK");
   return res;

 }
  }

Returns the Wxpaydata object, such a judgment

if (res. GetValue ("return_code") = = "SUCCESS")

If payment is successful, we can enter our business logic.

Then we also need to check the order, to obtain information about the order, before the micro-letter was not out of the demo when I wrote a check, it is directly used, the key Wxpaydata object will return the micro-letter order Number: Res.getvalue ("transaction_id"). ToString ().

After you have to send the message back to the micro-letter, notify the micro-letter background do not continue to send asynchronous requests:

 Response.Write (Res. TOXML ());
  Response.End ();

This code is more important.

Again, the page where the two-dimensional code is placed:

<div class= "G-body" > <div class= "g-wrap" > <div class= "m-weixin" > <div class= "M-weixin-header" &
    Gt <p><strong> please make payment in time so that the order can be processed ASAP! Order Number: <asp:label id= "Trade_no" runat= "Server" text= "Label" ></asp:Label></strong></p> <p > Please pay within 1 hours after you submit your order, otherwise the order will be canceled automatically. </p> </div> <div class= "M-weixin-main" > 

Write a JS check sheet payment situation to display:

$ (function () {
  var success = "<%=success%>";
  if (Success = = "Error") {
   $ (". G-body"). Hide ();
  }
 })

 var icount = setinterval (check, 2000); Perform a check function every 2 seconds.

 function Check () {
  $.ajax ({
   contentType: "Application/json",
   URL: "/webservice/vinson.asmx/ Queryweixin ",
   data:" {OrderID: ' "+ $ (" #trade_no "). Text () +" '} ",
   type:" POST ",
   dataType:" JSON ",
   Success:function (JSON) {
    json = eval ("+ JSON.D +"));
    if (json.success = = "Success") {
     clearinterval (icount);
     $ (". M-weixin-money font"). HTML ("successful payment");
     $ ("#payQRImg"). Remove ();
     $ (". M-weixin-demo"). Before ('  ");
     $ (". M-weixin-demo"). Next (). remove ();
     $ ("#we_ok"). Show ();
    }
   ,
   error:function (err, ex) {
   }}
  );
 

Yes, I wrote a search function queryweixin for Ajax.

I'm here to generate orders and two-dimensional code:
Well, what else, eh, look at the effect of it:

After successful payment:

Original link: http://www.cnblogs.com/vinsonLu/p/5166214.html

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.