Call the interface to step on a pile of traps and methods to fill holes, a pile

Source: Internet
Author: User

Call the interface to step on a pile of traps and methods to fill holes, a pile

Most programmers who have written interfaces know that interface interconnection between different projects often step on various pitfalls, especially those with old frameworks that have not been maintained for a long time.

The principle of an order interface I wrote before is very simple. I embedded a mall into a point management project, bought items in the mall, and paid for items in another point project, there are 5 Data interactions in the middle, and the data is sent to each other in the form of interfaces. The most common method is curl. The general interaction principle is as follows:

I will not draw any picture. I will give a rough description that the merchant is the marketplace party and the platform is the credit payment party.

Step 1: The Merchant places an order (background Interface) to the platform. The transaction data of the merchant is submitted to the platform in json format. The platform processes the data in real time and returns the data to the merchant system, the Platform stores the received data in the database as the order information.

Step 2: The Merchant initiates a payment request to the platform. The order information (Order Number, transaction flow, etc.) is sent to the platform side in the form of curl. The platform side obtains the transaction information based on the order number sent (the first step has been stored in the database ), then, the platform deducts points or calls the payment interface. Record to the database for verification.

Step 3: The transaction result notification (platform-> merchant background) platform will return the transaction result. If the deduction is successful or the balance is insufficient, the result will be sent to the merchant platform.

Step 4: The transaction result notification (platform> merchant's front-end) is the same as the result notification returned at the front-end, and the background result notification is saved in the database, prevent front-end result notifications from failing to return correct results due to server concurrency or network problems. In this case, it passes the background transaction result verification.

Step 5: refund. Similarly.

The above process has basically been familiar with the interface. The interface call is actually very simple, and the most troublesome thing is the connection between the merchant and the platform. This connection has encountered several problems, it is not difficult to solve the problem, but it is very troublesome and affects the thinking.

1. The code for curl access failure is as follows:

Private static function get_interface_result ($ data, $ url ){
$ Sign = ChengE: get_cashier_data_sign ($ data );
$ Data ["sign"] = $ sign;
$ Json_data = json_encode ($ data );
Log: write ("Order url:". $ url );
Log: write ("place an order in json_data:". $ json_data );
ChengE: insert_interface_res_log ($ url, $ json_data, $ log_id );
$ Ch = curl_init ();
$ Timeout = 30;
Curl_setopt ($ ch, CURLOPT_URL, $ url );
Curl_setopt ($ ch, CURLOPT_HTTPHEADER, array ('content-type: application/json '));
Curl_setopt ($ ch, CURLOPT_POSTFIELDS, $ json_data );
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, true );
Curl_setopt ($ ch, CURLOPT_USERAGENT, "jb51.net's CURL Example beta ");
Curl_setopt ($ ch, CURLOPT_CONNECTTIMEOUT, $ timeout );
Curl_setopt ($ ch, CURLOPT_FOLLOWLOCATION, 1 );

Log: write ("interface [". $ url ."]");
$ File_contents = curl_exec ($ ch );
$ File_contents = json_decode ($ file_contents, true );
$ Http_code = 0;
If (! Curl_errno ($ ch )){
$ Http_code = curl_getinfo ($ ch, CURLINFO_HTTP_CODE );
If ($ http_code = 200)
{
$ Result = json_decode ($ file_contents, true );
$ ResultCode = $ result ['code'];
$ ResultMessage = $ result ['msg '];
}
}
Log: write ("interface [". $ url. "] http_code:". $ http_code );
Curl_close ($ ch );
ChengE: update_interface_res_log ($ log_id, $ file_contents, $ http_code, $ resultCode, $ resultMessage );
Return $ file_contents;
}

There are multiple causes of failure. Generally, curl access is basically a set of templates and there will be no major problems. What is hard to find is basically an environmental problem.

The first problem is the server environment. I use nginx5.6, and the response data received by curl is empty !!! Open the test and report the following error: Automatically populating $ HTTP_RAW_POST_DATA is deprecated and will be removed in a future version. It is not difficult to solve this problem, mainly because version 5.6 is not supported. In the configuration file php. ini, set 'always _ populate_raw_post_data 'to-1.

After configuration, although no error is reported, the request times out. The response results cannot be returned, and the page cannot be refreshed during the test. In fact, this is also a problem with the nginx environment.

Because both my platform and the merchant's code are deployed on the same server, and the nginx environment is the only thing that will not die. The nginx environment does not support curl access to the local domain name. To solve this problem, you can configure two different servers (if there are Redundant servers), and then use the apache environment in the same environment, apache supports curl local access. The simplest is to modify the nginx configuration and install a dependency package. Modify the configuration as follows,

Nginx. conf file

Server {listen 80; server_name 127.0.0.1; location ~ \. Php ($ |/) {root Project address fastcgi_pass 127.0.0.1: 9000;} php. INI file: set PHP_FCGI_MAX_REQUESTS = 1000 echo Starting PHP FastCGI... runHiddenConsole D:/wnmp/php-5.6.27/php-cgi.exe-B 127.0.0.1: 9000-c D:/wnmp/php-5.6.279/php. iniRunHiddenConsole D:/wnmp/php-5.6.27/php-cgi.exe-B 127.0.0.1: 9090-c D:/wnmp/php-5.6.27/php. iniecho Starting nginx... runHiddenConsole D:/wnmp/nginx-1.7.7/nginx.exe-p D:/wnmp/nginx-1 7.7 2. In order to prevent others from tampering with data in the interface signature issue during value transfer, the request data is often signed and authenticated using asymmetric encryption. The Code is as follows: public static function login_validate_sign ($ queryStr ){
Parse_str ($ queryStr, $ get_param_array );
$ Ori_array = array (
ExToken => $ get_param_array ['extoken'],
Mobile => $ get_param_array ['mobile'],
ReqParty => ChengE: REQPARTY,
Timestamp => $ get_param_array ['timestamp'],
);
Ksort ($ ori_array );
$ Ori_str = http_build_query ($ ori_array). "& key =". ChengE: LOGIN_KEY;
$ Sign_str = md5 ($ ori_str );
$ Ori_sign = $ get_param_array ['sign'];
// Pass the signature
If ($ sign_str = $ ori_sign ){
Return true;
}
Else {
Return false;
}
}
In different nginx versions, some encryption results are different. Using debug, you can easily find out the cause. If you want to solve this problem, do not rewrite an encryption algorithm.
Or the two versions of the algorithm are unified, and the most direct is to directly write a dependency processing class:
DES algorithm:
Class DES {var $ key; function DES ($ key) {$ this-> key = $ key;} function encrypt ($ input) {$ size = mcrypt_get_block_size ('des ', 'ecb '); $ input = $ this-> pkcs5_pad ($ input, $ size); $ key = 'x8thts9j1dpcw10vba4opm4c'; $ td = mcrypt_module_open ('des ','', 'ecb ', ''); $ iv = @ mcrypt_create_iv (mcrypt_enc_get_iv_size ($ td), MCRYPT_RAND); @ mcrypt_generic_init ($ td, $ key, $ iv ); $ data = mcrypt_generic ($ td, $ input); Mcrypt_generic_deinit ($ td); mcrypt_module_close ($ td); $ data = base64_encode ($ data); return $ data;} function decrypt ($ encrypted) {$ encrypted = base64_decode ($ encrypted); $ key = 'x8thts9j1dpcw10vba4opm4c '; $ td = mcrypt_module_open ('des', '', 'ecb ',''); // use the MCRYPT_DES algorithm. The cbc mode $ iv = @ mcrypt_create_iv (encrypt ($ td), MCRYPT_RAND); $ ks = mcrypt_enc_get_key_size ($ td); @ mcrypt_generic_init ($ Td, $ key, $ iv); // initial processing $ decrypted = mdecrypt_generic ($ td, $ encrypted); // decrypt mcrypt_generic_deinit ($ td ); // end mcrypt_module_close ($ td); $ y = $ this-> pkcs5_unpad ($ decrypted); return $ y;} function pkcs5_pad ($ text, $ blocksize) {$ pad = $ blocksize-(strlen ($ text) % $ blocksize); return $ text. str_repeat (chr ($ pad), $ pad);} function pkcs5_unpad ($ text) {$ pad = ord ($ text {strlen ($ text)-1 }); if ($ pad> st Rlen ($ text) return false; if (strspn ($ text, chr ($ pad), strlen ($ text)-$ pad )! = $ Pad) return false; return substr ($ text, 0,-1 * $ pad );}}

3. for routing problems, if the curl access path is the address after the route is rewritten, the access may fail, so it is best to configure the route. For example, in the vhost file:
Server {listen 80; server_name www.xfl.com phpStudy.net; root "E:/phpstudy/WWW/xfl"; location/{index index.html index.htm index. php; # autoindex on;} location ~ \. Php (. *) $ {fastcgi_pass 127.0.0.1: 9000; fastcgi_index index. php; fastcgi_split_path_info ^ ((? U). + \. php )(/?. +) $; Fastcgi_param SCRIPT_FILENAME $ document_root $ fastcgi_script_name; fastcgi_param PATH_INFO $ response; fastcgi_param PATH_TRANSLATED $ document_root $ response; include fastcgi_params ;}}

The above are some traps I have encountered. More traps will be shared next time, especially new handwriting interfaces. It is best to ask your project manager to avoid these pitfalls!
 

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.