Java to achieve Alipay payment (backstage)

Source: Internet
Author: User
The framework is using spring boot
Our integrated Alipay payment is also required to provide two interfaces out. One is to give the front end function is to get the request parameter to return to the front end

The front end gets the data we return. The second interface is provided to Alipay's servers to pay for success or failure. The Alipay server will call back our interface. Notify us of payment results asynchronously

Service-side SDK address: https://doc.open.alipay.com/doc2/detail?treeId=54&articleId=103419&docType=1

Front-End integration address: https://doc.open.alipay.com/docs/doc.htm?spm=a219a.7629140.0.0.HwBhZv&treeId=193&articleId= 105296&doctype=1

Public key private key generation address: https://doc.open.alipay.com/docs/doc.htm?spm=a219a.7629140.0.0.STtXnL&treeId=193&articleId= 105310&doctype=1

All right. No more chatter, straight up code: (At this point, the public key private key environment has been well equipped)

@RestController @RequestMapping ("/payment") public class Paymentcontroller {//Alipay important parameter private static String app_id = "
	";
	private static String App_private_key = "";
	private static String CHARSET = "Utf-8";

	private static String Alipay_public_key = ""; /** * Signature of Alipay payment information * * @param info * Data class * @return * @throws alipayapiexception * @throws Unsupp Ortedencodingexception */@PostMapping ("/sign") public Object sign (@RequestBody signinfo info) throws Alipayapiexcepti
		On, unsupportedencodingexception {simpledateformat SDF = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
		String AppID = app_id; String bizcontent = Tojson (info.
		Content);
		String charset = charset;
		String method = "Alipay.trade.app.pay";
		String Signtype = "RSA";
		String timestamp = Sdf.format (new Date ());
		String Version = "1.0"; String Notify_url = "https://pay.ytbapp.com/payment/notify";/increase payment asynchronous notification callback, remember the position of the upper and lower Notify_url, all before sign_type, very important, Not even in the end. String content = "app_id=" +AppID + "&biz_content=" + bizcontent + "&charset=" + CharSet + "&method=" + method + "¬ify_url=" + (notify

		_url) + "&sign_type=" + Signtype + "xtamp=" + timestamp + "&version=" + version;

		String sign = alipaysignature.rsasign (content, App_private_key, CharSet); Return "{\" result\ ": \" app_id= "+ Encode (AppID) +" &biz_content= "+ Encode (bizcontent) +" &charset= "+ Encode (  CharSet) + "&method=" + Encode (method) + "¬ify_url=" + Encode (notify_url) + "&sign_type=" + Encode (Signtype) +
	"xtamp=" + encode (timestamp) + "&version=" + Encode (version) + "&sign=" + Encode (sign) + "\"}; private string encode (string sign) throws Unsupportedencodingexception {return Urlencoder.encode (sign, "Utf-8"). Rep
	Lace ("+", "%20");
		private string Tojson (Bizcontent content) {string context = ' ";  Context + = "{" + "\" timeout_express\ ": \" "+ content.timeout_express +" \ "," + "\" seller_id\ ": \" "+ content.seller_id + "\", "+" \ "ProDuct_code\ ": \" "+ Content.product_code +" \ "" + "\" total_amount\ ": \" "+ Content.total_amount +" \ "," + "\" subject\ ": \ "" + Content.subject + "\", "+" \ "body\": \ "" + Content.body + "\", "+" \ "out_trade_no\": \ "+ Content.out_trade_no +"

		\"}";
	return context; /** * Alipay payment successful. Will callback the interface * * @param request * @return * @throws unsupportedencodingexception * * @PostMappin G ("/notify") public String notify (HttpServletRequest request) throws Unsupportedencodingexception {map<string, stri
		ng> params = new hashmap<string, string> ();
		map<string, string[]> requestparams = Request.getparametermap (); for (iterator<string> iter = Requestparams.keyset (). iterator (); Iter.hasnext ();)
			{String name = Iter.next ();
			String[] values = requestparams.get (name);
			String valuestr = ""; for (int i = 0; i < values.length i++) {valuestr = (i = = values.length-1)? Valuestr + Values[i]: Valuestr + V
			Alues[i] + ","; //garbled resolution, this code in the occurrence of garbled when theUse.
			If MySign and sign are not equal, you can also use this code to convert//valuestr = new String (valuestr.getbytes ("iso-8859-1"), "GBK");
		Params.put (name, VALUESTR);
		String out_trade_no = Request.getparameter ("Out_trade_no");//Merchant Order Number Boolean signverified = false;
		try {signverified = Alipaysignature.rsacheckv1 (params, alipay_public_key, CHARSET);
			catch (Alipayapiexception e) {//TODO auto-generated catch block E.printstacktrace (); Return ("Fail"),//Check out an exception, then go directly back to failure}///Call SDK Verification signature if (signverified) {//TODO verification Successful//In accordance with the description of the payment result asynchronous notification, to the business in the payment result
			The content carries on the 1\2\3\4 two times check, after the verification succeeds returns success in the response, the checksum failure returns failure String result = Updatealipayorderstatus (out_trade_no);
			System.out.println ("Verify successful, go update status \ t order Number:" + Out_trade_no + "from Alipay payment, update result:" + results);
			Baseresponse baseresponse = Gsonutils.getgson (). Fromjson (result, baseresponse.class);
			if (null!= baseresponse && baseresponse.issucceeded) {return ("success"); else {return (' fail ')//update status failed}} else {//TODO verification failedThe Exception log is logged and failure is returned in response.
			SYSTEM.OUT.PRINTLN ("Validation fails, no update status");
		Return ("fail"); }
	}
}
to two related model

Signinfo:

public class Signinfo
{public
    bizcontent Content;
}

Bizcontent:

public class Bizcontent
{public
    String body = ' ";
    Public String subject = "";
    Public String out_trade_no = "";
    Public String timeout_express = "";
    Public String Total_amount = "";
    Public String seller_id = "";
    Public String product_code = "";
}


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.