search
HomeBackend DevelopmentPHP TutorialPHP WeChat red envelope implementation code introduction

This article mainly introduces the implementation method of WeChat red envelopes in PHP WeChat public account development, and analyzes the implementation ideas, steps and specific operation techniques of PHP to implement the red envelope sending function of WeChat public accounts in the form of examples. Friends in need can refer to the following

The example of this article describes the implementation method of WeChat red envelope development in PHP WeChat public account. I share it with you for your reference. The details are as follows:

In the past few days, I met a customer who wanted to add the WeChat cash red envelope function to their WeChat public platform. It is a secondary development function. I just searched it on Baidu and it turned out that it was not complex. Let’s start developing functions. Now I will post the development process and requirements to share:

1. Requirements:

Fans click on their company on the customer’s public platform place an order, and then give the order a cashback of five yuan, which will be sent to the WeChat ID of the order.

2. Development ideas:

#1: First get the openid of following this fan. Openid is the WeChat ID of following a certain public account. , so that this person can be located as the operator of the order.

2: Send xml data to request WeChat server.

The code has two php files

1.oauth2.php


<?php
$code=$_GET[&#39;code&#39;];
$state=$_GET[&#39;state&#39;];
$appid=&#39;XXXX&#39;;
$appsecret=&#39;XXXXXXXX&#39;;//
if (empty($code)) $this->error(&#39;授权失败&#39;);
$token_url=&#39;https://api.weixin.qq.com/sns/oauth2/access_token?appid=&#39;.$appid&#39;&secret=&#39;.$appsecret.&#39;&code=&#39;.$code.&#39;&grant_type=authorization_code&#39;;
$token=json_decode(file_get_contents($token_url));
if (isset($token->errcode)) {
echo &#39;<h1 id="错误">错误1</h1>&#39;.$token->errcode;
echo &#39;<br/><h2 id="错误信息">错误信息1:</h2>&#39;.$token->errmsg;
exit;
}
session_start();
$_SESSION[&#39;openid&#39;]= $token->openid;
header(&#39;location:http://www.XXXXXXX.com/XXXXX/XXXXXX/XXXXXX/hongbao.php&#39;);//要跳转的文件路径
?>

2.hongbao.php


<?php
//XXXXX。。是需要开发者自己填写的内容,注意不要泄密
 // 从session中获取到openid;
$openid=$_SESSION["openid"];
    if(empty($openid))
    {
header(&#39;location:https://open.weixin.qq.com/connect/oauth2/authorize?appid=XXXXXXXX&redirect_uri=http://www.XXXXXXX.com/oauth2.php&respose_type=code&scope=snsapi_base&state=XXXX&connect_redirect=1#wechat_redirect&#39;);
    }
}
// 关键的函数
public function weixin_red_packet(){
  // 请求参数
  // 随机字符串
  $data[&#39;nonce_str&#39;]=$this->get_unique_value();
  //商户号,输入你的商户号
  $data[&#39;mch_id&#39;]="XXXXXXX";
  //商户订单号,可以按要求自己组合28位的商户订单号
  $data[&#39;mch_billno&#39;]=$data[&#39;mch_id&#39;].date("ymd")."XXXXXX".rand(1000,9999);
  //公众帐号appid,输入自己的公众号appid
  $data[&#39;wxappid&#39;]="XXXXXXX";
  //商户名称
  $data[&#39;send_name&#39;]="XXXXX";
  //用户openid,输入待发红包的用户openid
  session_start();
  $data[&#39;re_openid&#39;]=$_SESSION["openid"];
  //付款金额
  $data[&#39;total_amount&#39;]="XXXX";
  //红包发放总人数
  $data[&#39;total_num&#39;]="XXXX";
  //红包祝福语
  $data[&#39;wishing&#39;]="XXXX";
  //IP地址
  $data[&#39;client_ip&#39;]=$_SERVER[&#39;LOCAL_ADDR&#39;];
  //活动名称
  $data[&#39;act_name&#39;]="XXXXX";
  //备注
  $data[&#39;remark&#39;]="XXXXX";
  // 生成签名
  //对数据数组进行处理
  //API密钥,输入自己的K 微信商户号里面的K
  $appsecret="XXXXXXXXXXXXXX"; //
  $data=array_filter($data);
  ksort($data);
  $str="";
  foreach($data as $k=>$v){
    $str.=$k."=".$v."&";
  }
  $str.="key=".$appsecret;
  $data[&#39;sign&#39;]=strtoupper(MD5($str));
  /*
    发红包操作过程:
      1.将请求数据转换成xml
      2.发送请求
      3.将请求结果转换为数组
      4.将请求信息和请求结果录入到数据库中
      4.判断是否通信成功
      5.判断是否转账成功
   */
  //发红包接口地址
  $url="https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
  //将请求数据由数组转换成xml
  $xml=$this->arraytoxml($data);
  //进行请求操作
  $res=$this->curl($xml,$url);
  //将请求结果由xml转换成数组
  $arr=$this->xmltoarray($res);
}
// 生成32位唯一随机字符串
private function get_unique_value(){
  $str=uniqid(mt_rand(),1);
  $str=sha1($str);
  return md5($str);
}
// 将数组转换成xml
private function arraytoxml($arr){
  $xml="<xml>";
  foreach($arr as $k=>$v){
    $xml.="<".$k.">".$v."</".$k.">";
  }
  $xml.="</xml>";
  return $xml;
}
// 将xml转换成数组
private function xmltoarray($xml){
  //禁止引用外部xml实体
  libxml_disable_entity_loader(true);
  $xmlstring=simplexml_load_string($xml,"SimpleXMLElement",LIBXML_NOCDATA);
  $arr=json_decode(json_encode($xmlstring),true);
  return $arr;
}
//进行curl操作
private function curl($param="",$url) {
  $postUrl = $url;
  $curlPost = $param;
  //初始化curl
  $ch = curl_init();
  //抓取指定网页
  curl_setopt($ch, CURLOPT_URL,$postUrl);
  //设置header
  curl_setopt($ch, CURLOPT_HEADER, 0);
  //要求结果为字符串且输出到屏幕上
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  //post提交方式
  curl_setopt($ch, CURLOPT_POST, 1);
  // 增加 HTTP Header(头)里的字段
  curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
  // 终止从服务端进行验证
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  //证书放到网站根目录的cert文件夹底下
  curl_setopt($ch,CURLOPT_SSLCERT,dirname(__FILE__).DIRECTORY_SEPARATOR.
        &#39;cert&#39;.DIRECTORY_SEPARATOR.&#39;apiclient_cert.pem&#39;);
    curl_setopt($ch,CURLOPT_SSLKEY,dirname(__FILE__).DIRECTORY_SEPARATOR.
        &#39;cert&#39;.DIRECTORY_SEPARATOR.&#39;apiient_key.pem&#39;);
    curl_setopt($ch,CURLOPT_CAINFO,dirname(__FILE__).DIRECTORY_SEPARATOR.
        &#39;cert&#39;.DIRECTORY_SEPARATOR.&#39;rootca.pem&#39;);
  //运行curl
  $data = curl_exec($ch);
  //关闭curl
  curl_close($ch);
  return $data;
}
?>

The above is the detailed content of PHP WeChat red envelope implementation code introduction. For more information, please follow other related articles on the PHP Chinese website!

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
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

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.