search
HomeBackend DevelopmentPHP TutorialHow to call Alipay interface using struts

一、ACTION类关键代码 没用的包可以干掉

package com.hzdracom.alipay.action;
import it.sauronsoftware.base64.Base64;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.dom4j.Document;
import org.springframework.stereotype.Controller;
import com.alibaba.fastjson.JSON;
import com.hzdracom.action.BaseAction;
import com.hzdracom.config.AlipayConfig;
import com.hzdracom.util.AlipaySubmit;
import com.hzdracom.util.HTTPService;
import com.hzdracom.util.UtilDate;
import com.hzlq.source.security.DESUtil;
/*
 * 支付宝付款接口
 * @author ZhuangZi
 * @Directions 
 * @version $Id: AliPayAction.java,v 0.1 2013-3-27 下午04:49:57 ZhuangZi Exp $
 */
@Controller
public class AliPayAction extends BaseAction {
    private String              phoneCode;
    private String              totalfee;
    /**
     * 调用支付宝接口
     * @author ZhuangZi
     * @class com.hzdracom.alipay.action.AliPayAction
     * @method AliPay
     * @Directions 调用支付宝接口
     * @date 2013-3-27下午04:53:35 void
     */
    public void pay() {
        try {
            /*1****生成支付宝交易号,根据时间到毫秒级别*/
            String out_trade_no = UtilDate.getOrderNum() ;
           /*2*****↓↓↓↓↓↓↓↓↓↓把请求参数打包成数组↓↓↓↓↓↓↓↓↓↓*/
            Map<String, String> sParaTemp = new HashMap<String, String>();
            sParaTemp = getPayPrama(totalfee, out_trade_no);
            /*3*****↓↓↓↓↓↓↓↓↓↓请求支付宝接口↓↓↓↓↓↓↓↓↓↓*/
            String json = AlipaySubmit.buildRequest(sParaTemp, "get", "确认");
            HttpServletResponse response = ServletActionContext.getResponse();
            response.setContentType("text/html");
            response.setCharacterEncoding("utf-8");
            PrintWriter out;
            out = response.getWriter();
            json = JSON.toJSONString(json);
            out.write(json);
            out.flush();
            out.close();
        } catch (IOException e) {
        }
    }
    /**
     * 
     * @author ZhuangZi
     * @class com.hzdracom.alipay.action.AliPayAction
     * @method GetPayPrama
     * @Directions 封装调用支付宝参数
      * @date 2013-4-1下午05:26:11
     * @param totalfee 金额
      * @param out_trade_no  订单编号
      * @return Map<String,String>
     */
    public Map<String, String> getPayPrama(String totalfee, String out_trade_no) {
        Map<String, String> sParaTemp = new HashMap<String, String>();
        sParaTemp.put("service", "create_direct_pay_by_user");
        sParaTemp.put("partner", AlipayConfig.partner);
        sParaTemp.put("_input_charset", AlipayConfig.input_charset);
        sParaTemp.put("payment_type", AlipayConfig.payment_type);
        /*服务器异步通知页面路径//需http://格式的完整路径,不能加?id=123这类自定义参数*/
        sParaTemp.put("notify_url", AlipayConfig.notify_url);
        /*页面跳转同步通知页面路径 //需http://格式的完整路径,不能加?id=123这类自定义参数,不能写成http://localhost/*/
        sParaTemp.put("return_url", AlipayConfig.return_url);
        /*卖家支付宝帐户*/
        sParaTemp.put("seller_email", AlipayConfig.seller_email);
        /*商户订单号*/
        sParaTemp.put("out_trade_no", out_trade_no);
        /*订单名称*/
        sParaTemp.put("subject", AlipayConfig.subject);
        /*付款金额*/
        sParaTemp.put("total_fee", totalfee);
        /*订单描述*/
        sParaTemp.put("body", AlipayConfig.body);
        /*需以http://开头的完整路径,例如:http://www.xxx.com/myorder.html*/
        sParaTemp.put("show_url", AlipayConfig.show_url);
        //防钓鱼时间戳
        sParaTemp.put("anti_phishing_key", AlipayConfig.anti_phishing_key);
        /*客户端的IP地址 非局域网的外网IP地址,如:221.0.0.1*/
        sParaTemp.put("exter_invoke_ip", AlipayConfig.exter_invoke_ip);
        return sParaTemp;
    }
    public String getPhoneCode() {
        return phoneCode;
    }
    public void setPhoneCode(String phoneCode) {
        this.phoneCode = phoneCode;
    }
    public String getTotalfee() {
        return totalfee;
    }
    public void setTotalfee(String totalfee) {
        this.totalfee = totalfee;
    }
}

二、AlipayConfig 类是封装支付宝接口参数

package com.hzdracom.config;
import com.hzdracom.util.UtilDate;
/* *
 *类名:AlipayConfig
 *功能:基础配置类
 *详细:设置帐户有关信息及返回路径
 *版本:3.3
 *日期:2012-08-10
 *说明:
 *以下代码只是为了方便商户测试而提供的样例代码,商户可以根据自己网站的需要,按照技术文档编写,并非一定要使用该代码。
 *该代码仅供学习和研究支付宝接口使用,只是提供一个参考。

 *提示:如何获取安全校验码和合作身份者ID
 *1.用您的签约支付宝账号登录支付宝网站(www.alipay.com)
 *2.点击“商家服务”(https://b.alipay.com/order/myOrder.htm)
 *3.点击“查询合作者身份(PID)”、“查询安全校验码(Key)”
 *安全校验码查看时,输入支付密码后,页面呈灰色的现象,怎么办?
 *解决方法:
 *1、检查浏览器配置,不让浏览器做弹框屏蔽设置
 *2、更换浏览器或电脑,重新登录查询。
 */
public class AlipayConfig {

 //↓↓↓↓↓↓↓↓↓↓请在这里配置您的基本信息↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
 // 合作身份者ID,以2088开头由16位纯数字组成的字符串
 public static String partner = "2088001466494907";
 // 商户的私钥
 public static String key = "fb30213vjc4k4oabt7z4q9e07sfmlmzr";
 //↑↑↑↑↑↑↑↑↑↑请在这里配置您的基本信息↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑

 // 调试用,创建TXT日志文件夹路径
 public static String log_path = "D:\\";
 // 字符编码格式 目前支持 gbk 或 utf-8
 public static String input_charset = "utf-8";

 // 签名方式 不需修改
 public static String sign_type = "MD5";

 public static String payment_type = "1";
    //必填,不能修改
    //服务器异步通知页面路径
 public static  String notify_url = "notify_url.jsp";
    //需http://格式的完整路径,不能加?id=123这类自定义参数

    //页面跳转同步通知页面路径
 public static  String return_url = "return_url.jsp";
    //需http://格式的完整路径,不能加?id=123这类自定义参数,不能写成http://localhost/
    //卖家支付宝帐户
 public static   String seller_email = "jjj@hzdracom.com";
    //必填
    //商户订单号
 public static  String out_trade_no =UtilDate.getOrderNum();
    //商户网站订单系统中唯一订单号,必填
    //订单名称
 public static String subject = "隐号充值";
    //必填
    //订单描述
 public static  String body = "隐号充值";
    //商品展示地址

 public static String show_url ="";
  //防钓鱼时间戳
 public static String anti_phishing_key="";
 /*客户端的IP地址 非局域网的外网IP地址,如:221.0.0.1*/
 public static String exter_invoke_ip="";
}

三、strut配置文件


 

以上属于关键代码部分,需要注意的事项有 :

1.需要把支付宝提供的接口的几个类引入到你的项目中,包括架包

2.notify_url.jsp和return_url.jsp地址要做好些成外网地址的全路径

3.你自己的业务处理写notify_url.jsp这个里面,也可以直接写个接口给支付宝接口调用

更多如何用struts调用支付宝接口相关文章请关注PHP中文网!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
11 Best PHP URL Shortener Scripts (Free and Premium)11 Best PHP URL Shortener Scripts (Free and Premium)Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram APIIntroduction to the Instagram APIMar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, ReactBuild a React App With a Laravel Back End: Part 2, ReactMar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation SurveyAnnouncement of 2025 PHP Situation SurveyMar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment