Browse Source

feat:对接微信、邮箱、钉钉接口封装

Cheng Jian 3 years ago
parent
commit
6502f9c369
52 changed files with 6929 additions and 211 deletions
  1. 292 4
      doc/.back_订单全流程管理平台/订单全流程管理平台-backup-202322090012.pdma.json
  2. 429 5
      doc/.back_订单全流程管理平台/订单全流程管理平台-backup-202322090015.pdma.json
  3. 428 4
      doc/.back_订单全流程管理平台/订单全流程管理平台-backup-202322090341.pdma.json
  4. 1227 198
      doc/订单全流程管理平台.pdma.json
  5. 33 0
      opms_libary/micro_srv/micro_srv_test.go
  6. 120 0
      opms_libary/plugin/dingtalk/base/base.go
  7. 58 0
      opms_libary/plugin/dingtalk/client.go
  8. 12 0
      opms_libary/plugin/dingtalk/client_test.go
  9. 11 0
      opms_libary/plugin/dingtalk/context/config.go
  10. 82 0
      opms_libary/plugin/dingtalk/context/context.go
  11. 280 0
      opms_libary/plugin/dingtalk/workflow/entity.go
  12. 54 0
      opms_libary/plugin/dingtalk/workflow/workflow.go
  13. 49 0
      opms_libary/plugin/email/auth.go
  14. 9 0
      opms_libary/plugin/email/config.go
  15. 220 0
      opms_libary/plugin/email/example_test.go
  16. 322 0
      opms_libary/plugin/email/message.go
  17. 22 0
      opms_libary/plugin/email/mime.go
  18. 116 0
      opms_libary/plugin/email/send.go
  19. 213 0
      opms_libary/plugin/email/smtp.go
  20. 306 0
      opms_libary/plugin/email/writeto.go
  21. 77 0
      opms_libary/plugin/wechat/client.go
  22. 38 0
      opms_libary/plugin/wechat/client_test.go
  23. 75 0
      opms_libary/plugin/wechat/context/access_token.go
  24. 12 0
      opms_libary/plugin/wechat/context/config.go
  25. 86 0
      opms_libary/plugin/wechat/context/context.go
  26. 183 0
      opms_libary/plugin/wechat/context/crypto.go
  27. 39 0
      opms_libary/plugin/wechat/context/error.go
  28. 18 0
      opms_libary/plugin/wechat/context/sign.go
  29. 77 0
      opms_libary/plugin/wechat/media.go
  30. 3 0
      opms_libary/plugin/wechat/mp/README.md
  31. 171 0
      opms_libary/plugin/wechat/mp/account/qrcode.go
  32. 87 0
      opms_libary/plugin/wechat/mp/base/base.go
  33. 0 0
      opms_libary/plugin/wechat/mp/bridge/README.md
  34. 235 0
      opms_libary/plugin/wechat/mp/bridge/msg_handler.go
  35. 108 0
      opms_libary/plugin/wechat/mp/bridge/page_auth_handler.go
  36. 120 0
      opms_libary/plugin/wechat/mp/jssdk/jssdk.go
  37. 178 0
      opms_libary/plugin/wechat/mp/material/material.go
  38. 112 0
      opms_libary/plugin/wechat/mp/material/media.go
  39. 142 0
      opms_libary/plugin/wechat/mp/menu/button.go
  40. 199 0
      opms_libary/plugin/wechat/mp/menu/menu.go
  41. 17 0
      opms_libary/plugin/wechat/mp/message/image.go
  42. 158 0
      opms_libary/plugin/wechat/mp/message/message.go
  43. 24 0
      opms_libary/plugin/wechat/mp/message/music.go
  44. 35 0
      opms_libary/plugin/wechat/mp/message/news.go
  45. 24 0
      opms_libary/plugin/wechat/mp/message/ransfer_customer.go
  46. 15 0
      opms_libary/plugin/wechat/mp/message/reply.go
  47. 14 0
      opms_libary/plugin/wechat/mp/message/text.go
  48. 21 0
      opms_libary/plugin/wechat/mp/message/video.go
  49. 17 0
      opms_libary/plugin/wechat/mp/message/voice.go
  50. 145 0
      opms_libary/plugin/wechat/mp/oauth/oauth.go
  51. 148 0
      opms_libary/plugin/wechat/mp/template/template.go
  52. 68 0
      opms_libary/plugin/wechat/mp/user/user.go

+ 292 - 4
doc/.back_订单全流程管理平台/订单全流程管理平台-backup-2023113180219.pdma.json → doc/.back_订单全流程管理平台/订单全流程管理平台-backup-202322090012.pdma.json

@@ -4,7 +4,7 @@
   "avatar": "",
   "version": "4.2.0",
   "createdTime": "2023-1-6 11:43:05",
-  "updatedTime": "2023-1-13 18:02:09",
+  "updatedTime": "2023-1-13 18:02:19",
   "dbConns": [],
   "profile": {
     "default": {
@@ -5057,7 +5057,24 @@
           "id": "D8FD5645-CA6F-416A-95C3-B1105B561000"
         },
         {
-          "defKey": "signatory",
+          "defKey": "signatory_id",
+          "defName": "公司签约人ID",
+          "comment": "",
+          "type": "",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": false,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "refDict": "",
+          "extProps": {},
+          "domain": "16120F75-6AA7-4483-868D-F07F511BB081",
+          "id": "828878A8-8FA2-4D63-9B5B-B8B9E81BCE10"
+        },
+        {
+          "defKey": "signatory_name",
           "defName": "公司签约人",
           "comment": "",
           "type": "",
@@ -5071,7 +5088,41 @@
           "refDict": "",
           "extProps": {},
           "domain": "54611CCC-CA4B-42E1-9F32-4944C85B85A6",
-          "id": "828878A8-8FA2-4D63-9B5B-B8B9E81BCE10"
+          "id": "D693E3DC-7F6F-4F87-98BF-9A636749A32C"
+        },
+        {
+          "defKey": "cust_signatory_id",
+          "defName": "客户签约人ID",
+          "comment": "",
+          "type": "",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": false,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "refDict": "",
+          "extProps": {},
+          "domain": "16120F75-6AA7-4483-868D-F07F511BB081",
+          "id": "E6ADDCB1-33EB-4A32-BEB4-D8D65116DC1E"
+        },
+        {
+          "defKey": "cust_signatory_name",
+          "defName": "客户签约人",
+          "comment": "",
+          "type": "",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": false,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "refDict": "",
+          "extProps": {},
+          "domain": "54611CCC-CA4B-42E1-9F32-4944C85B85A6",
+          "id": "2C3BC908-62FB-4784-91D1-0B721C514EFC"
         },
         {
           "defKey": "distributor_id",
@@ -15102,6 +15153,242 @@
       ],
       "correlations": [],
       "indexes": []
+    },
+    {
+      "id": "75444F74-D732-47FD-BCBD-ECCEC6D646D7",
+      "env": {
+        "base": {
+          "nameSpace": "",
+          "codeRoot": ""
+        }
+      },
+      "defKey": "te_",
+      "defName": "",
+      "comment": "",
+      "properties": {
+        "partitioned by": "(date string)",
+        "row format delimited": "",
+        "fields terminated by ','": "",
+        "collection items terminated by '-'": "",
+        "map keys terminated by ':'": "",
+        "store as textfile;": ""
+      },
+      "nameTemplate": "{defKey}[{defName}]",
+      "notes": {},
+      "headers": [
+        {
+          "refKey": "hideInGraph",
+          "hideInGraph": true
+        },
+        {
+          "refKey": "defKey",
+          "hideInGraph": false
+        },
+        {
+          "refKey": "defName",
+          "hideInGraph": false
+        },
+        {
+          "refKey": "primaryKey",
+          "hideInGraph": false
+        },
+        {
+          "refKey": "notNull",
+          "hideInGraph": true
+        },
+        {
+          "refKey": "autoIncrement",
+          "hideInGraph": true
+        },
+        {
+          "refKey": "domain",
+          "hideInGraph": true
+        },
+        {
+          "refKey": "type",
+          "hideInGraph": false
+        },
+        {
+          "refKey": "len",
+          "hideInGraph": false
+        },
+        {
+          "refKey": "scale",
+          "hideInGraph": false
+        },
+        {
+          "refKey": "comment",
+          "hideInGraph": true
+        },
+        {
+          "refKey": "refDict",
+          "hideInGraph": true
+        },
+        {
+          "refKey": "defaultValue",
+          "hideInGraph": true
+        },
+        {
+          "refKey": "isStandard",
+          "hideInGraph": false
+        },
+        {
+          "refKey": "uiHint",
+          "hideInGraph": true
+        },
+        {
+          "refKey": "extProps",
+          "hideInGraph": true
+        }
+      ],
+      "fields": [
+        {
+          "defKey": "remark",
+          "defName": "备注",
+          "comment": "",
+          "type": "",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": false,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "domain": "3E948CEC-3070-472C-AF92-F3CA11EC9D15",
+          "refDict": "",
+          "extProps": {},
+          "notes": {},
+          "id": "9911A908-9DB3-4B7C-9C1E-E26D7E67FB22"
+        },
+        {
+          "defKey": "created_by",
+          "defName": "创建者",
+          "comment": "",
+          "type": "",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": true,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "domain": "16120F75-6AA7-4483-868D-F07F511BB081",
+          "refDict": "",
+          "extProps": {},
+          "notes": {},
+          "id": "82E4C293-ED47-459B-B91E-FFFC6ADA1ABE"
+        },
+        {
+          "defKey": "created_name",
+          "defName": "创建人",
+          "comment": "",
+          "type": "VARCHAR",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": true,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "domain": "54611CCC-CA4B-42E1-9F32-4944C85B85A6",
+          "refDict": "",
+          "extProps": {},
+          "notes": {},
+          "id": "6DE6596B-C645-46E1-BF45-348480533B08"
+        },
+        {
+          "defKey": "created_time",
+          "defName": "创建时间",
+          "comment": "",
+          "type": "DATETIME",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": true,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "domain": "7CFFA0D3-6A93-4DDC-BC10-DF21211064DC",
+          "refDict": "",
+          "extProps": {},
+          "notes": {},
+          "id": "1D13D2F1-A56D-462F-8FDE-9448161EC00A"
+        },
+        {
+          "defKey": "updated_by",
+          "defName": "更新者",
+          "comment": "",
+          "type": "",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": false,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "domain": "16120F75-6AA7-4483-868D-F07F511BB081",
+          "refDict": "",
+          "extProps": {},
+          "notes": {},
+          "id": "3B132286-21A5-4A5D-8B86-CC677D5C24BA"
+        },
+        {
+          "defKey": "updated_name",
+          "defName": "更新人",
+          "comment": "",
+          "type": "VARCHAR",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": false,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "domain": "54611CCC-CA4B-42E1-9F32-4944C85B85A6",
+          "refDict": "",
+          "extProps": {},
+          "notes": {},
+          "id": "74CCDFF5-F059-4B40-9446-D84C5F22FA4F"
+        },
+        {
+          "defKey": "updated_time",
+          "defName": "更新时间",
+          "comment": "",
+          "type": "DATETIME",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": false,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "domain": "7CFFA0D3-6A93-4DDC-BC10-DF21211064DC",
+          "refDict": "",
+          "extProps": {},
+          "notes": {},
+          "id": "6AB44087-58CD-4E3F-AD0A-0FDDF0B55561"
+        },
+        {
+          "defKey": "deleted_time",
+          "defName": "删除时间",
+          "comment": "",
+          "type": "DATETIME",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": false,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "domain": "7CFFA0D3-6A93-4DDC-BC10-DF21211064DC",
+          "refDict": "",
+          "extProps": {},
+          "notes": {},
+          "id": "11812C55-0571-4710-8061-6B1AF4247E22"
+        }
+      ],
+      "correlations": [],
+      "indexes": []
     }
   ],
   "views": [],
@@ -15567,7 +15854,8 @@
       "refEntities": [
         "430AA523-31EE-486D-81FC-77A94743FDC0",
         "A2C395A0-17EC-4229-BDBE-D699C4AA139D",
-        "723E395F-D263-4431-96CE-D10B17FCD2DE"
+        "723E395F-D263-4431-96CE-D10B17FCD2DE",
+        "75444F74-D732-47FD-BCBD-ECCEC6D646D7"
       ],
       "refViews": [],
       "refDiagrams": [],

+ 429 - 5
doc/.back_订单全流程管理平台/订单全流程管理平台-backup-2023113174948.pdma.json → doc/.back_订单全流程管理平台/订单全流程管理平台-backup-202322090015.pdma.json

@@ -4,7 +4,7 @@
   "avatar": "",
   "version": "4.2.0",
   "createdTime": "2023-1-6 11:43:05",
-  "updatedTime": "2023-1-13 17:49:43",
+  "updatedTime": "2023-2-2 09:00:12",
   "dbConns": [],
   "profile": {
     "default": {
@@ -5057,7 +5057,24 @@
           "id": "D8FD5645-CA6F-416A-95C3-B1105B561000"
         },
         {
-          "defKey": "signatory",
+          "defKey": "signatory_id",
+          "defName": "公司签约人ID",
+          "comment": "",
+          "type": "",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": false,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "refDict": "",
+          "extProps": {},
+          "domain": "16120F75-6AA7-4483-868D-F07F511BB081",
+          "id": "828878A8-8FA2-4D63-9B5B-B8B9E81BCE10"
+        },
+        {
+          "defKey": "signatory_name",
           "defName": "公司签约人",
           "comment": "",
           "type": "",
@@ -5071,7 +5088,41 @@
           "refDict": "",
           "extProps": {},
           "domain": "54611CCC-CA4B-42E1-9F32-4944C85B85A6",
-          "id": "828878A8-8FA2-4D63-9B5B-B8B9E81BCE10"
+          "id": "D693E3DC-7F6F-4F87-98BF-9A636749A32C"
+        },
+        {
+          "defKey": "cust_signatory_id",
+          "defName": "客户签约人ID",
+          "comment": "",
+          "type": "",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": false,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "refDict": "",
+          "extProps": {},
+          "domain": "16120F75-6AA7-4483-868D-F07F511BB081",
+          "id": "E6ADDCB1-33EB-4A32-BEB4-D8D65116DC1E"
+        },
+        {
+          "defKey": "cust_signatory_name",
+          "defName": "客户签约人",
+          "comment": "",
+          "type": "",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": false,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "refDict": "",
+          "extProps": {},
+          "domain": "54611CCC-CA4B-42E1-9F32-4944C85B85A6",
+          "id": "2C3BC908-62FB-4784-91D1-0B721C514EFC"
         },
         {
           "defKey": "distributor_id",
@@ -14895,6 +14946,57 @@
           "len": "",
           "scale": "",
           "primaryKey": false,
+          "notNull": true,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "refDict": "",
+          "extProps": {},
+          "domain": "73FD2BAD-2358-4336-B96D-45DC897BD792",
+          "id": "E9AB6B30-E977-4765-A2AE-2AB6430D970E"
+        },
+        {
+          "defKey": "is_loop",
+          "defName": "是否循环",
+          "comment": "",
+          "type": "",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": true,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "refDict": "",
+          "extProps": {},
+          "domain": "6F7C1C5C-D159-41E6-BF9D-54DEEFA79AFF",
+          "id": "06F3988E-70C5-439E-B2A7-9D862A0B48A0"
+        },
+        {
+          "defKey": "cycle_type",
+          "defName": "周期类型",
+          "comment": "",
+          "type": "",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": false,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "refDict": "",
+          "extProps": {},
+          "domain": "73FD2BAD-2358-4336-B96D-45DC897BD792",
+          "id": "58A3DDD1-C6D2-446A-B396-AA8B0EB07102"
+        },
+        {
+          "defKey": "cycle_setup",
+          "defName": "周期设置",
+          "comment": "",
+          "type": "",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
           "notNull": false,
           "autoIncrement": false,
           "defaultValue": "",
@@ -14902,7 +15004,7 @@
           "refDict": "",
           "extProps": {},
           "domain": "9092C4E0-1A54-4859-ABBB-5B62DBC27573",
-          "id": "E9AB6B30-E977-4765-A2AE-2AB6430D970E"
+          "id": "9C42E592-1505-4B4A-A7FC-473FB1F7DF1A"
         },
         {
           "defKey": "remark",
@@ -15051,6 +15153,327 @@
       ],
       "correlations": [],
       "indexes": []
+    },
+    {
+      "id": "75444F74-D732-47FD-BCBD-ECCEC6D646D7",
+      "env": {
+        "base": {
+          "nameSpace": "",
+          "codeRoot": ""
+        }
+      },
+      "defKey": "te_course_material",
+      "defName": "课程资料",
+      "comment": "",
+      "properties": {
+        "partitioned by": "(date string)",
+        "row format delimited": "",
+        "fields terminated by ','": "",
+        "collection items terminated by '-'": "",
+        "map keys terminated by ':'": "",
+        "store as textfile;": ""
+      },
+      "nameTemplate": "{defKey}[{defName}]",
+      "notes": {},
+      "headers": [
+        {
+          "refKey": "hideInGraph",
+          "hideInGraph": true
+        },
+        {
+          "refKey": "defKey",
+          "hideInGraph": false
+        },
+        {
+          "refKey": "defName",
+          "hideInGraph": false
+        },
+        {
+          "refKey": "primaryKey",
+          "hideInGraph": false
+        },
+        {
+          "refKey": "notNull",
+          "hideInGraph": true
+        },
+        {
+          "refKey": "autoIncrement",
+          "hideInGraph": true
+        },
+        {
+          "refKey": "domain",
+          "hideInGraph": true
+        },
+        {
+          "refKey": "type",
+          "hideInGraph": false
+        },
+        {
+          "refKey": "len",
+          "hideInGraph": false
+        },
+        {
+          "refKey": "scale",
+          "hideInGraph": false
+        },
+        {
+          "refKey": "comment",
+          "hideInGraph": true
+        },
+        {
+          "refKey": "refDict",
+          "hideInGraph": true
+        },
+        {
+          "refKey": "defaultValue",
+          "hideInGraph": true
+        },
+        {
+          "refKey": "isStandard",
+          "hideInGraph": false
+        },
+        {
+          "refKey": "uiHint",
+          "hideInGraph": true
+        },
+        {
+          "refKey": "extProps",
+          "hideInGraph": true
+        }
+      ],
+      "fields": [
+        {
+          "defKey": "id",
+          "defName": "主键",
+          "comment": "",
+          "type": "",
+          "len": "",
+          "scale": "",
+          "primaryKey": true,
+          "notNull": true,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "refDict": "",
+          "extProps": {},
+          "domain": "16120F75-6AA7-4483-868D-F07F511BB081",
+          "id": "468BB827-45DC-47C4-904D-9F2E2990C535"
+        },
+        {
+          "defKey": "cor_name",
+          "defName": "课件名称",
+          "comment": "",
+          "type": "",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": true,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "refDict": "",
+          "extProps": {},
+          "domain": "54611CCC-CA4B-42E1-9F32-4944C85B85A6",
+          "id": "648E3CA2-98CF-442A-83D1-3221A51F2817"
+        },
+        {
+          "defKey": "cor_type",
+          "defName": "课件类型",
+          "comment": "",
+          "type": "",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": true,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "refDict": "",
+          "extProps": {},
+          "domain": "73FD2BAD-2358-4336-B96D-45DC897BD792",
+          "id": "A23E3543-16E5-458E-BD99-797C20C0FAAD"
+        },
+        {
+          "defKey": "cor_lable",
+          "defName": "课件标签",
+          "comment": "",
+          "type": "",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": false,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "refDict": "",
+          "extProps": {},
+          "domain": "9092C4E0-1A54-4859-ABBB-5B62DBC27573",
+          "id": "43D3375C-8535-40A2-AD2E-13F419CD55CC"
+        },
+        {
+          "defKey": "cor_url",
+          "defName": "课件地址",
+          "comment": "",
+          "type": "",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": false,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "refDict": "",
+          "extProps": {},
+          "domain": "9092C4E0-1A54-4859-ABBB-5B62DBC27573",
+          "id": "43ABFDE0-5C0E-46A0-A48D-B75ACBE32D52"
+        },
+        {
+          "defKey": "remark",
+          "defName": "备注",
+          "comment": "",
+          "type": "",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": false,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "domain": "3E948CEC-3070-472C-AF92-F3CA11EC9D15",
+          "refDict": "",
+          "extProps": {},
+          "notes": {},
+          "id": "9911A908-9DB3-4B7C-9C1E-E26D7E67FB22"
+        },
+        {
+          "defKey": "created_by",
+          "defName": "创建者",
+          "comment": "",
+          "type": "",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": true,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "domain": "16120F75-6AA7-4483-868D-F07F511BB081",
+          "refDict": "",
+          "extProps": {},
+          "notes": {},
+          "id": "82E4C293-ED47-459B-B91E-FFFC6ADA1ABE"
+        },
+        {
+          "defKey": "created_name",
+          "defName": "创建人",
+          "comment": "",
+          "type": "VARCHAR",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": true,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "domain": "54611CCC-CA4B-42E1-9F32-4944C85B85A6",
+          "refDict": "",
+          "extProps": {},
+          "notes": {},
+          "id": "6DE6596B-C645-46E1-BF45-348480533B08"
+        },
+        {
+          "defKey": "created_time",
+          "defName": "创建时间",
+          "comment": "",
+          "type": "DATETIME",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": true,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "domain": "7CFFA0D3-6A93-4DDC-BC10-DF21211064DC",
+          "refDict": "",
+          "extProps": {},
+          "notes": {},
+          "id": "1D13D2F1-A56D-462F-8FDE-9448161EC00A"
+        },
+        {
+          "defKey": "updated_by",
+          "defName": "更新者",
+          "comment": "",
+          "type": "",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": false,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "domain": "16120F75-6AA7-4483-868D-F07F511BB081",
+          "refDict": "",
+          "extProps": {},
+          "notes": {},
+          "id": "3B132286-21A5-4A5D-8B86-CC677D5C24BA"
+        },
+        {
+          "defKey": "updated_name",
+          "defName": "更新人",
+          "comment": "",
+          "type": "VARCHAR",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": false,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "domain": "54611CCC-CA4B-42E1-9F32-4944C85B85A6",
+          "refDict": "",
+          "extProps": {},
+          "notes": {},
+          "id": "74CCDFF5-F059-4B40-9446-D84C5F22FA4F"
+        },
+        {
+          "defKey": "updated_time",
+          "defName": "更新时间",
+          "comment": "",
+          "type": "DATETIME",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": false,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "domain": "7CFFA0D3-6A93-4DDC-BC10-DF21211064DC",
+          "refDict": "",
+          "extProps": {},
+          "notes": {},
+          "id": "6AB44087-58CD-4E3F-AD0A-0FDDF0B55561"
+        },
+        {
+          "defKey": "deleted_time",
+          "defName": "删除时间",
+          "comment": "",
+          "type": "DATETIME",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": false,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "domain": "7CFFA0D3-6A93-4DDC-BC10-DF21211064DC",
+          "refDict": "",
+          "extProps": {},
+          "notes": {},
+          "id": "11812C55-0571-4710-8061-6B1AF4247E22"
+        }
+      ],
+      "correlations": [],
+      "indexes": []
     }
   ],
   "views": [],
@@ -15516,7 +15939,8 @@
       "refEntities": [
         "430AA523-31EE-486D-81FC-77A94743FDC0",
         "A2C395A0-17EC-4229-BDBE-D699C4AA139D",
-        "723E395F-D263-4431-96CE-D10B17FCD2DE"
+        "723E395F-D263-4431-96CE-D10B17FCD2DE",
+        "75444F74-D732-47FD-BCBD-ECCEC6D646D7"
       ],
       "refViews": [],
       "refDiagrams": [],

+ 428 - 4
doc/.back_订单全流程管理平台/订单全流程管理平台-backup-2023113180209.pdma.json → doc/.back_订单全流程管理平台/订单全流程管理平台-backup-202322090341.pdma.json

@@ -4,7 +4,7 @@
   "avatar": "",
   "version": "4.2.0",
   "createdTime": "2023-1-6 11:43:05",
-  "updatedTime": "2023-1-13 17:49:48",
+  "updatedTime": "2023-2-2 09:00:15",
   "dbConns": [],
   "profile": {
     "default": {
@@ -5057,7 +5057,24 @@
           "id": "D8FD5645-CA6F-416A-95C3-B1105B561000"
         },
         {
-          "defKey": "signatory",
+          "defKey": "signatory_id",
+          "defName": "公司签约人ID",
+          "comment": "",
+          "type": "",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": false,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "refDict": "",
+          "extProps": {},
+          "domain": "16120F75-6AA7-4483-868D-F07F511BB081",
+          "id": "828878A8-8FA2-4D63-9B5B-B8B9E81BCE10"
+        },
+        {
+          "defKey": "signatory_name",
           "defName": "公司签约人",
           "comment": "",
           "type": "",
@@ -5071,7 +5088,41 @@
           "refDict": "",
           "extProps": {},
           "domain": "54611CCC-CA4B-42E1-9F32-4944C85B85A6",
-          "id": "828878A8-8FA2-4D63-9B5B-B8B9E81BCE10"
+          "id": "D693E3DC-7F6F-4F87-98BF-9A636749A32C"
+        },
+        {
+          "defKey": "cust_signatory_id",
+          "defName": "客户签约人ID",
+          "comment": "",
+          "type": "",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": false,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "refDict": "",
+          "extProps": {},
+          "domain": "16120F75-6AA7-4483-868D-F07F511BB081",
+          "id": "E6ADDCB1-33EB-4A32-BEB4-D8D65116DC1E"
+        },
+        {
+          "defKey": "cust_signatory_name",
+          "defName": "客户签约人",
+          "comment": "",
+          "type": "",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": false,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "refDict": "",
+          "extProps": {},
+          "domain": "54611CCC-CA4B-42E1-9F32-4944C85B85A6",
+          "id": "2C3BC908-62FB-4784-91D1-0B721C514EFC"
         },
         {
           "defKey": "distributor_id",
@@ -14904,6 +14955,57 @@
           "domain": "73FD2BAD-2358-4336-B96D-45DC897BD792",
           "id": "E9AB6B30-E977-4765-A2AE-2AB6430D970E"
         },
+        {
+          "defKey": "is_loop",
+          "defName": "是否循环",
+          "comment": "",
+          "type": "",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": true,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "refDict": "",
+          "extProps": {},
+          "domain": "6F7C1C5C-D159-41E6-BF9D-54DEEFA79AFF",
+          "id": "06F3988E-70C5-439E-B2A7-9D862A0B48A0"
+        },
+        {
+          "defKey": "cycle_type",
+          "defName": "周期类型",
+          "comment": "",
+          "type": "",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": false,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "refDict": "",
+          "extProps": {},
+          "domain": "73FD2BAD-2358-4336-B96D-45DC897BD792",
+          "id": "58A3DDD1-C6D2-446A-B396-AA8B0EB07102"
+        },
+        {
+          "defKey": "cycle_setup",
+          "defName": "周期设置",
+          "comment": "",
+          "type": "",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": false,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "refDict": "",
+          "extProps": {},
+          "domain": "9092C4E0-1A54-4859-ABBB-5B62DBC27573",
+          "id": "9C42E592-1505-4B4A-A7FC-473FB1F7DF1A"
+        },
         {
           "defKey": "remark",
           "defName": "备注",
@@ -15051,6 +15153,327 @@
       ],
       "correlations": [],
       "indexes": []
+    },
+    {
+      "id": "75444F74-D732-47FD-BCBD-ECCEC6D646D7",
+      "env": {
+        "base": {
+          "nameSpace": "",
+          "codeRoot": ""
+        }
+      },
+      "defKey": "te_course_material",
+      "defName": "课程资料",
+      "comment": "",
+      "properties": {
+        "partitioned by": "(date string)",
+        "row format delimited": "",
+        "fields terminated by ','": "",
+        "collection items terminated by '-'": "",
+        "map keys terminated by ':'": "",
+        "store as textfile;": ""
+      },
+      "nameTemplate": "{defKey}[{defName}]",
+      "notes": {},
+      "headers": [
+        {
+          "refKey": "hideInGraph",
+          "hideInGraph": true
+        },
+        {
+          "refKey": "defKey",
+          "hideInGraph": false
+        },
+        {
+          "refKey": "defName",
+          "hideInGraph": false
+        },
+        {
+          "refKey": "primaryKey",
+          "hideInGraph": false
+        },
+        {
+          "refKey": "notNull",
+          "hideInGraph": true
+        },
+        {
+          "refKey": "autoIncrement",
+          "hideInGraph": true
+        },
+        {
+          "refKey": "domain",
+          "hideInGraph": true
+        },
+        {
+          "refKey": "type",
+          "hideInGraph": false
+        },
+        {
+          "refKey": "len",
+          "hideInGraph": false
+        },
+        {
+          "refKey": "scale",
+          "hideInGraph": false
+        },
+        {
+          "refKey": "comment",
+          "hideInGraph": true
+        },
+        {
+          "refKey": "refDict",
+          "hideInGraph": true
+        },
+        {
+          "refKey": "defaultValue",
+          "hideInGraph": true
+        },
+        {
+          "refKey": "isStandard",
+          "hideInGraph": false
+        },
+        {
+          "refKey": "uiHint",
+          "hideInGraph": true
+        },
+        {
+          "refKey": "extProps",
+          "hideInGraph": true
+        }
+      ],
+      "fields": [
+        {
+          "defKey": "id",
+          "defName": "主键",
+          "comment": "",
+          "type": "",
+          "len": "",
+          "scale": "",
+          "primaryKey": true,
+          "notNull": true,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "refDict": "",
+          "extProps": {},
+          "domain": "16120F75-6AA7-4483-868D-F07F511BB081",
+          "id": "468BB827-45DC-47C4-904D-9F2E2990C535"
+        },
+        {
+          "defKey": "cor_name",
+          "defName": "课件名称",
+          "comment": "",
+          "type": "",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": true,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "refDict": "",
+          "extProps": {},
+          "domain": "54611CCC-CA4B-42E1-9F32-4944C85B85A6",
+          "id": "648E3CA2-98CF-442A-83D1-3221A51F2817"
+        },
+        {
+          "defKey": "cor_type",
+          "defName": "课件类型",
+          "comment": "",
+          "type": "",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": true,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "refDict": "",
+          "extProps": {},
+          "domain": "73FD2BAD-2358-4336-B96D-45DC897BD792",
+          "id": "A23E3543-16E5-458E-BD99-797C20C0FAAD"
+        },
+        {
+          "defKey": "cor_lable",
+          "defName": "课件标签",
+          "comment": "",
+          "type": "",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": false,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "refDict": "",
+          "extProps": {},
+          "domain": "9092C4E0-1A54-4859-ABBB-5B62DBC27573",
+          "id": "43D3375C-8535-40A2-AD2E-13F419CD55CC"
+        },
+        {
+          "defKey": "cor_url",
+          "defName": "课件地址",
+          "comment": "",
+          "type": "",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": true,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "refDict": "",
+          "extProps": {},
+          "domain": "9092C4E0-1A54-4859-ABBB-5B62DBC27573",
+          "id": "43ABFDE0-5C0E-46A0-A48D-B75ACBE32D52"
+        },
+        {
+          "defKey": "remark",
+          "defName": "备注",
+          "comment": "",
+          "type": "",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": false,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "domain": "3E948CEC-3070-472C-AF92-F3CA11EC9D15",
+          "refDict": "",
+          "extProps": {},
+          "notes": {},
+          "id": "9911A908-9DB3-4B7C-9C1E-E26D7E67FB22"
+        },
+        {
+          "defKey": "created_by",
+          "defName": "创建者",
+          "comment": "",
+          "type": "",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": true,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "domain": "16120F75-6AA7-4483-868D-F07F511BB081",
+          "refDict": "",
+          "extProps": {},
+          "notes": {},
+          "id": "82E4C293-ED47-459B-B91E-FFFC6ADA1ABE"
+        },
+        {
+          "defKey": "created_name",
+          "defName": "创建人",
+          "comment": "",
+          "type": "VARCHAR",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": true,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "domain": "54611CCC-CA4B-42E1-9F32-4944C85B85A6",
+          "refDict": "",
+          "extProps": {},
+          "notes": {},
+          "id": "6DE6596B-C645-46E1-BF45-348480533B08"
+        },
+        {
+          "defKey": "created_time",
+          "defName": "创建时间",
+          "comment": "",
+          "type": "DATETIME",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": true,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "domain": "7CFFA0D3-6A93-4DDC-BC10-DF21211064DC",
+          "refDict": "",
+          "extProps": {},
+          "notes": {},
+          "id": "1D13D2F1-A56D-462F-8FDE-9448161EC00A"
+        },
+        {
+          "defKey": "updated_by",
+          "defName": "更新者",
+          "comment": "",
+          "type": "",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": false,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "domain": "16120F75-6AA7-4483-868D-F07F511BB081",
+          "refDict": "",
+          "extProps": {},
+          "notes": {},
+          "id": "3B132286-21A5-4A5D-8B86-CC677D5C24BA"
+        },
+        {
+          "defKey": "updated_name",
+          "defName": "更新人",
+          "comment": "",
+          "type": "VARCHAR",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": false,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "domain": "54611CCC-CA4B-42E1-9F32-4944C85B85A6",
+          "refDict": "",
+          "extProps": {},
+          "notes": {},
+          "id": "74CCDFF5-F059-4B40-9446-D84C5F22FA4F"
+        },
+        {
+          "defKey": "updated_time",
+          "defName": "更新时间",
+          "comment": "",
+          "type": "DATETIME",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": false,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "domain": "7CFFA0D3-6A93-4DDC-BC10-DF21211064DC",
+          "refDict": "",
+          "extProps": {},
+          "notes": {},
+          "id": "6AB44087-58CD-4E3F-AD0A-0FDDF0B55561"
+        },
+        {
+          "defKey": "deleted_time",
+          "defName": "删除时间",
+          "comment": "",
+          "type": "DATETIME",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": false,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "domain": "7CFFA0D3-6A93-4DDC-BC10-DF21211064DC",
+          "refDict": "",
+          "extProps": {},
+          "notes": {},
+          "id": "11812C55-0571-4710-8061-6B1AF4247E22"
+        }
+      ],
+      "correlations": [],
+      "indexes": []
     }
   ],
   "views": [],
@@ -15516,7 +15939,8 @@
       "refEntities": [
         "430AA523-31EE-486D-81FC-77A94743FDC0",
         "A2C395A0-17EC-4229-BDBE-D699C4AA139D",
-        "723E395F-D263-4431-96CE-D10B17FCD2DE"
+        "723E395F-D263-4431-96CE-D10B17FCD2DE",
+        "75444F74-D732-47FD-BCBD-ECCEC6D646D7"
       ],
       "refViews": [],
       "refDiagrams": [],

File diff suppressed because it is too large
+ 1227 - 198
doc/订单全流程管理平台.pdma.json


+ 33 - 0
opms_libary/micro_srv/micro_srv_test.go

@@ -0,0 +1,33 @@
+package micro_srv
+
+import (
+	"context"
+	"dashoo.cn/common_definition/auth"
+	"dashoo.cn/opms_libary/gtoken"
+	"fmt"
+	"github.com/gogf/gf/frame/g"
+	"github.com/smallnest/rpcx/client"
+	"testing"
+)
+
+func TestName(t *testing.T) {
+
+	grsp := gtoken.Resp{}
+
+	d, _ := client.NewPeer2PeerDiscovery("tcp@127.0.0.1:8888", "")
+	authService := client.NewXClient("Auth", client.Failtry, client.RandomSelect, d, client.DefaultOption)
+
+	defer authService.Close()
+	rsp := &auth.Response{}
+	err := authService.Call(context.TODO(), "ValidToken", "+MFidQBXtaeIxZ3ZJI72ze6jX+mR47ZekWzzNu8HWrewJoDjs1Bf9t1+7lKapDr2", rsp)
+	if err != nil {
+		g.Log().Error(err)
+		grsp.Code = 401
+
+	}
+	grsp.Code = int(rsp.Code)
+	grsp.Msg = rsp.Msg
+	grsp.Data = rsp.Data
+	fmt.Println(grsp)
+
+}

+ 120 - 0
opms_libary/plugin/dingtalk/base/base.go

@@ -0,0 +1,120 @@
+package base
+
+import (
+	"bytes"
+	"dashoo.cn/opms_libary/plugin/dingtalk/context"
+	"encoding/json"
+	"fmt"
+	"io/ioutil"
+	"net/http"
+	"strings"
+)
+
+const BaseApiUrl = "https://api.dingtalk.com"
+
+//Base 微信公众平台,基本类
+type Base struct {
+	*context.Context
+}
+
+//HTTPGetWithAccessToken 自动加上access_token变量的GET调用,
+//如果失败,会清空AccessToken cache, 再试一次
+func (c *Base) HTTPGetWithAccessToken(url string, param map[string]interface{}) (resp []byte, err error) {
+	retry := 1
+Do:
+	var accessToken string
+	accessToken, err = c.GetAccessToken()
+	if err != nil {
+		return
+	}
+	var target = ""
+	if strings.Contains(url, "?") {
+		target = fmt.Sprintf("%s%s&x-acs-dingtalk-access-token=%s", BaseApiUrl, url, accessToken)
+	} else {
+		target = fmt.Sprintf("%s%s?x-acs-dingtalk-access-token=%s", BaseApiUrl, url, accessToken)
+	}
+	//双重for-range
+	for k, v := range param {
+		target = fmt.Sprintf("%s&%s=%v", target, k, v)
+	}
+
+	var response *http.Response
+	response, err = http.Get(target)
+	if err != nil {
+		return
+	}
+	defer response.Body.Close()
+
+	resp, err = ioutil.ReadAll(response.Body)
+
+	if err != nil {
+		if retry > 0 {
+			retry--
+			c.CleanAccessTokenCache()
+			goto Do
+		}
+		return
+	}
+	return
+}
+
+//HTTPPostJSONWithAccessToken post json 自动加上access token, 并retry
+func (c *Base) HTTPPostJSONWithAccessToken(url string, obj interface{}) (resp []byte, err error) {
+	retry := 1
+Do:
+	var accessToken string
+	accessToken, err = c.GetAccessToken()
+	if err != nil {
+		return
+	}
+
+	var target = ""
+	if strings.Contains(url, "?") {
+		target = fmt.Sprintf("%s%s", BaseApiUrl, url)
+	} else {
+		target = fmt.Sprintf("%s%s", BaseApiUrl, url)
+	}
+	fmt.Println(accessToken)
+	resp, err = PostJSON(target, obj, accessToken)
+
+	if err != nil {
+		if retry > 0 {
+			retry--
+			c.CleanAccessTokenCache()
+			goto Do
+		}
+		return
+	}
+	return
+}
+
+//PostJSON post json 数据请求
+func PostJSON(url string, obj interface{}, token string) ([]byte, error) {
+	jsonData, err := json.Marshal(obj)
+	if err != nil {
+		return nil, err
+	}
+
+	jsonData = bytes.Replace(jsonData, []byte("\\u003c"), []byte("<"), -1)
+	jsonData = bytes.Replace(jsonData, []byte("\\u003e"), []byte(">"), -1)
+	jsonData = bytes.Replace(jsonData, []byte("\\u0026"), []byte("&"), -1)
+
+	body := bytes.NewBuffer(jsonData)
+
+	req, _ := http.NewRequest("POST", url, body)
+	// 比如说设置个token
+	req.Header.Set("x-acs-dingtalk-access-token", token)
+	// 再设置个json
+	req.Header.Set("Content-Type", "application/json")
+
+	response, err := (&http.Client{}).Do(req)
+	if err != nil {
+		return nil, err
+	}
+	defer response.Body.Close()
+
+	if response.StatusCode != http.StatusOK {
+		return nil, fmt.Errorf("http get error : uri=%v , statusCode=%v", url, response.StatusCode)
+	}
+	return ioutil.ReadAll(response.Body)
+}

+ 58 - 0
opms_libary/plugin/dingtalk/client.go

@@ -0,0 +1,58 @@
+package dingtalk
+
+import (
+	"dashoo.cn/opms_libary/plugin/dingtalk/context"
+	"dashoo.cn/opms_libary/plugin/dingtalk/workflow"
+	"github.com/gogf/gf/os/gcache"
+	"sync"
+)
+
+var Client *ClientImpl
+
+var memCache *gcache.Cache
+
+// ClientImpl struct
+type ClientImpl struct {
+	Context *context.Context
+}
+
+func init() {
+	Client = NewClient()
+}
+
+func NewClient() *ClientImpl {
+	var config = context.Config{
+		//微信公众平台,需要填写的信息
+		AppKey:    "dinguytykawticadfoht",                                             //g.Config().GetString("dingtalk.app-key"),     //"your app id",
+		AppSecret: "zPlj4ZpITsUbeq2C0GrwJ78-e8knH_kIeyvznaNQacqtrSb9zbeZcOajgBKdolky", //g.Config().GetString("dingtalk.app-secret"), //"your app secret",
+	}
+	return newClient(config)
+}
+
+func newClient(cfg context.Config) *ClientImpl {
+	context := new(context.Context)
+	initContext(&cfg, context)
+	return &ClientImpl{context}
+}
+
+func initContext(cfg *context.Config, context *context.Context) {
+	if cfg.Cache == nil {
+		if memCache == nil {
+			memCache = gcache.New()
+		}
+		cfg.Cache = memCache
+	}
+	context.Config = cfg
+
+	context.SetAccessTokenLock(new(sync.RWMutex))
+}
+
+//GetAccessToken 获取access_token
+func (c *ClientImpl) GetAccessToken() (string, error) {
+	return c.Context.GetAccessToken()
+}
+
+//GetWorkflow OA审批
+func (c *ClientImpl) GetWorkflow() *workflow.Workflow {
+	return workflow.NewWorkflow(c.Context)
+}

+ 12 - 0
opms_libary/plugin/dingtalk/client_test.go

@@ -0,0 +1,12 @@
+package dingtalk
+
+import (
+	"testing"
+)
+
+func TestSendMsg(t *testing.T) {
+	client := NewClient()
+	w := client.GetWorkflow()
+	//w.GetFormSchema("PROC-7A5F6215-A8CF-4DD1-AB2C-5B1AB84C4E19")
+	w.CreateProcessInstance("47073111989114", "PROC-7A5F6215-A8CF-4DD1-AB2C-5B1AB84C4E19", 435711466)
+}

+ 11 - 0
opms_libary/plugin/dingtalk/context/config.go

@@ -0,0 +1,11 @@
+package context
+
+import "github.com/gogf/gf/os/gcache"
+
+// Config for user
+type Config struct {
+	AppKey    string
+	AppSecret string
+	Token     string
+	Cache     *gcache.Cache
+}

+ 82 - 0
opms_libary/plugin/dingtalk/context/context.go

@@ -0,0 +1,82 @@
+package context
+
+import (
+	"encoding/json"
+	"fmt"
+	"github.com/gogf/gf/frame/g"
+	"sync"
+	"time"
+)
+
+const (
+	//AccessTokenURL 获取access_token的接口
+	AccessTokenURL = "https://oapi.dingtalk.com/gettoken"
+)
+
+//ResAccessToken 结构体
+type ResAccessToken struct {
+	AccessToken string `json:"access_token"`
+	ExpiresIn   int64  `json:"expires_in"`
+	Code        int64  `json:"errcode"`
+	Msg         string `json:"errmsg"`
+}
+
+type Context struct {
+	*Config
+
+	//accessTokenLock 读写锁 同一个AppKey一个
+	accessTokenLock *sync.RWMutex
+}
+
+//SetAccessTokenLock 设置读写锁(一个appID一个读写锁)
+func (ctx *Context) SetAccessTokenLock(l *sync.RWMutex) {
+	ctx.accessTokenLock = l
+}
+
+//GetAccessToken 获取access_token
+func (ctx *Context) GetAccessToken() (accessToken string, err error) {
+	ctx.accessTokenLock.Lock()
+	defer ctx.accessTokenLock.Unlock()
+
+	accessTokenCacheKey := fmt.Sprintf("access_token_%s", ctx.AppKey)
+	val, _ := ctx.Cache.Get(accessTokenCacheKey)
+	if val != nil {
+		accessToken = val.(string)
+		return
+	}
+
+	//从钉钉服务器获取
+	var resAccessToken ResAccessToken
+	resAccessToken, err = ctx.GetAccessTokenFromServer()
+	if err != nil {
+		return
+	}
+
+	accessToken = resAccessToken.AccessToken
+	return
+}
+
+//CleanAccessTokenCache clean cache
+func (ctx *Context) CleanAccessTokenCache() {
+	accessTokenCacheKey := fmt.Sprintf("access_token_%s", ctx.AppKey)
+	ctx.Cache.Remove(accessTokenCacheKey)
+}
+
+//GetAccessTokenFromServer 强制从服务器获取token
+func (ctx *Context) GetAccessTokenFromServer() (token ResAccessToken, err error) {
+	url := fmt.Sprintf("%s?appkey=%s&appsecret=%s", AccessTokenURL, ctx.AppKey, ctx.AppSecret)
+	body := g.Client().GetBytes(url)
+	err = json.Unmarshal(body, &token)
+	if err != nil {
+		return
+	}
+	if token.Code != 0 {
+		err = fmt.Errorf("get access_token error : errcode=%v , errormsg=%v", token.Code, token.Msg)
+		return
+	}
+
+	accessTokenCacheKey := fmt.Sprintf("access_token_%s", ctx.AppKey)
+	expires := token.ExpiresIn - 1500
+	err = ctx.Cache.Set(accessTokenCacheKey, token.AccessToken, time.Duration(expires)*time.Second)
+	return
+}

+ 280 - 0
opms_libary/plugin/dingtalk/workflow/entity.go

@@ -0,0 +1,280 @@
+package workflow
+
+// Schema 审批流表单信息
+type Schema struct {
+	// 表单类型。
+	AppType *int32 `json:"appType,omitempty" xml:"appType,omitempty"`
+	// 表单应用 uuid 或者 corpId。
+	AppUuid *string `json:"appUuid,omitempty" xml:"appUuid,omitempty"`
+	// 代表表单业务含义的类型。
+	BizType *string `json:"bizType,omitempty" xml:"bizType,omitempty"`
+	// 创建人 userId。
+	CreatorUserId *string `json:"creatorUserId,omitempty" xml:"creatorUserId,omitempty"`
+	// 业务自定义设置数据。
+	CustomSetting *string `json:"customSetting,omitempty" xml:"customSetting,omitempty"`
+	// 引擎类型,表单:0,页面:1
+	EngineType *int32 `json:"engineType,omitempty" xml:"engineType,omitempty"`
+	// 表单的唯一码。
+	FormCode *string `json:"formCode,omitempty" xml:"formCode,omitempty"`
+	// 表单 uuid。
+	FormUuid *string `json:"formUuid,omitempty" xml:"formUuid,omitempty"`
+	// 创建时间的时间戳。
+	GmtCreate *string `json:"gmtCreate,omitempty" xml:"gmtCreate,omitempty"`
+	// 修改时间的时间戳。
+	GmtModified *string `json:"gmtModified,omitempty" xml:"gmtModified,omitempty"`
+	// 图标。
+	Icon *string `json:"icon,omitempty" xml:"icon,omitempty"`
+	// 排序 id。
+	ListOrder *int32 `json:"listOrder,omitempty" xml:"listOrder,omitempty"`
+	// 说明文案。
+	Memo *string `json:"memo,omitempty" xml:"memo,omitempty"`
+	// 表单名称。
+	Name *string `json:"name,omitempty" xml:"name,omitempty"`
+	// 数据归属者的 id 类型。企业(orgId), 群(cid), 人(uid)。
+	OwnerIdType *string `json:"ownerIdType,omitempty" xml:"ownerIdType,omitempty"`
+	// 目标类型: inner, outer, customer。
+	ProcType *string `json:"procType,omitempty" xml:"procType,omitempty"`
+	// 表单 schema 详情。
+	SchemaContent *SchemaContent `json:"schemaContent,omitempty" xml:"schemaContent,omitempty" type:"Struct"`
+	// 状态, PUBLISHED(启用), INVALID(停用), SAVED(草稿)
+	Status *string `json:"status,omitempty" xml:"status,omitempty"`
+	// 可见范围类型。
+	VisibleRange *string `json:"visibleRange,omitempty" xml:"visibleRange,omitempty"`
+}
+
+type SchemaContent struct {
+	// 图标
+	Icon *string `json:"icon,omitempty" xml:"icon,omitempty"`
+	// 控件列表
+	Items []*SchemaContentItems `json:"items,omitempty" xml:"items,omitempty" type:"Repeated"`
+	// 表单名称。
+	Title *string `json:"title,omitempty" xml:"title,omitempty"`
+}
+
+type SchemaContentItems struct {
+	// 子控件列表
+	Children []*SchemaContentItemsChildren `json:"children,omitempty" xml:"children,omitempty" type:"Repeated"`
+	// 控件类型,取值:
+	ComponentName *string `json:"componentName,omitempty" xml:"componentName,omitempty"`
+	// 控件属性。
+	Props *SchemaContentItemsProps `json:"props,omitempty" xml:"props,omitempty" type:"Struct"`
+}
+
+type SchemaContentItemsChildren struct {
+	// 控件类型
+	ComponentName *string `json:"componentName,omitempty" xml:"componentName,omitempty"`
+	// 子控件属性
+	Props *SchemaContentItemsProps `json:"props,omitempty" xml:"props,omitempty" type:"Struct"`
+}
+
+type SchemaContentItemsProps struct {
+	// 加班套件4.0新增 加班明细名称。
+	ActionName *string `json:"actionName,omitempty" xml:"actionName,omitempty"`
+	// textnote的样式,top|middle|bottom。
+	Align *string `json:"align,omitempty" xml:"align,omitempty"`
+	// ISV 微应用 appId,用于ISV身份权限识别,ISV可获得相应数据。
+	AppId *int64 `json:"appId,omitempty" xml:"appId,omitempty"`
+	// 套件是否开启异步获取分条件规则,true:开启;false:不开启。
+	AsyncCondition *bool `json:"asyncCondition,omitempty" xml:"asyncCondition,omitempty"`
+	// 请假、出差、外出、加班类型标签。
+	AttendTypeLabel *string `json:"attendTypeLabel,omitempty" xml:"attendTypeLabel,omitempty"`
+	// 表单关联控件列表。
+	BehaviorLinkage []*SchemaContentItemsPropsBehaviorLinkage `json:"behaviorLinkage,omitempty" xml:"behaviorLinkage,omitempty" type:"Repeated"`
+	// 控件业务自定义别名。
+	BizAlias *string `json:"bizAlias,omitempty" xml:"bizAlias,omitempty"`
+	// 业务套件类型。
+	BizType *string `json:"bizType,omitempty" xml:"bizType,omitempty"`
+	// 套件内子组件可见性
+	ChildFieldVisible map[string]*bool `json:"childFieldVisible,omitempty" xml:"childFieldVisible,omitempty"`
+	// 内部联系人choice,1表示多选,0表示单选。
+	Choice *int32 `json:"choice,omitempty" xml:"choice,omitempty"`
+	// common field的commonBizType。
+	CommonBizType *string `json:"commonBizType,omitempty" xml:"commonBizType,omitempty"`
+	// 是否可编辑。
+	Disabled *bool `json:"disabled,omitempty" xml:"disabled,omitempty"`
+	// 是否自动计算时长。
+	Duration *bool `json:"duration,omitempty" xml:"duration,omitempty"`
+	// 兼容字段。
+	DurationLabel *string `json:"durationLabel,omitempty" xml:"durationLabel,omitempty"`
+	// e签宝专用标识。
+	ESign *bool `json:"eSign,omitempty" xml:"eSign,omitempty"`
+	// 套件值是否打平
+	Extract *bool `json:"extract,omitempty" xml:"extract,omitempty"`
+	// 关联表单中的fields存储
+	FieldsInfo *string `json:"fieldsInfo,omitempty" xml:"fieldsInfo,omitempty"`
+	// 时间格式(DDDateField和DDDateRangeField)。
+	Format *string `json:"format,omitempty" xml:"format,omitempty"`
+	// 公式。
+	Formula *string `json:"formula,omitempty" xml:"formula,omitempty"`
+	// 加班套件4.0新增 加班明细是否隐藏。
+	Hidden *bool `json:"hidden,omitempty" xml:"hidden,omitempty"`
+	// textnote在详情页是否隐藏,true隐藏, false不隐藏
+	HiddenInApprovalDetail *bool `json:"hiddenInApprovalDetail,omitempty" xml:"hiddenInApprovalDetail,omitempty"`
+	// 加班套件4.0新增 加班明细是否隐藏标签。
+	HideLabel *bool `json:"hideLabel,omitempty" xml:"hideLabel,omitempty"`
+	// 兼容出勤套件类型。
+	HolidayOptions []map[string]*string `json:"holidayOptions,omitempty" xml:"holidayOptions,omitempty" type:"Repeated"`
+	// 控件 id。
+	Id *string `json:"id,omitempty" xml:"id,omitempty"`
+	// 控件名称。
+	Label *string `json:"label,omitempty" xml:"label,omitempty"`
+	// label是否可修改 true:不可修改。
+	LabelEditableFreeze *bool `json:"labelEditableFreeze,omitempty" xml:"labelEditableFreeze,omitempty"`
+	// 说明文案的链接地址。
+	Link *string `json:"link,omitempty" xml:"link,omitempty"`
+	// 加班套件4.0新增 加班明细描述。
+	MainTitle *string `json:"mainTitle,omitempty" xml:"mainTitle,omitempty"`
+	// 是否参与打印(1表示不打印, 0表示打印)。
+	NotPrint *string `json:"notPrint,omitempty" xml:"notPrint,omitempty"`
+	// 是否需要大写 默认是需要; 1:不需要大写, 空或者0:需要大写。
+	NotUpper *string `json:"notUpper,omitempty" xml:"notUpper,omitempty"`
+	// 选项内容列表,提供给业务方更多的选择器操作。
+	ObjOptions []*SchemaContentItemsPropsObjOptions `json:"objOptions,omitempty" xml:"objOptions,omitempty" type:"Repeated"`
+	// 单选框选项列表。
+	Options []*string `json:"options,omitempty" xml:"options,omitempty" type:"Repeated"`
+	// 是否有支付属性。
+	PayEnable *bool `json:"payEnable,omitempty" xml:"payEnable,omitempty"`
+	// 占位符。
+	Placeholder *string `json:"placeholder,omitempty" xml:"placeholder,omitempty"`
+	// 同步到考勤, 表示是否设置为员工状态。
+	Push *SchemaContentItemsPropsPush `json:"push,omitempty" xml:"push,omitempty" type:"Struct"`
+	// 推送到考勤, 子类型(DDSelectField)。
+	PushToAttendance *bool `json:"pushToAttendance,omitempty" xml:"pushToAttendance,omitempty"`
+	// 是否推送管理日历(DDDateRangeField, 1表示推送, 0表示不推送, 该属性为兼容保留)。
+	PushToCalendar *int32 `json:"pushToCalendar,omitempty" xml:"pushToCalendar,omitempty"`
+	// 是否必填。
+	Required *bool `json:"required,omitempty" xml:"required,omitempty"`
+	// 必填是否可修改 true:不可修改。
+	RequiredEditableFreeze *bool `json:"requiredEditableFreeze,omitempty" xml:"requiredEditableFreeze,omitempty"`
+	// 兼容出勤套件类型。
+	ShowAttendOptions *bool `json:"showAttendOptions,omitempty" xml:"showAttendOptions,omitempty"`
+	// 是否开启员工状态。
+	StaffStatusEnabled *bool `json:"staffStatusEnabled,omitempty" xml:"staffStatusEnabled,omitempty"`
+	// 需要计算总和的明细组件
+	StatField []*SchemaContentItemsPropsStatField `json:"statField,omitempty" xml:"statField,omitempty" type:"Repeated"`
+	// 数字组件/日期区间组件单位属性。
+	Unit *string `json:"unit,omitempty" xml:"unit,omitempty"`
+	// 是否使用考勤日历。
+	UseCalendar *bool `json:"useCalendar,omitempty" xml:"useCalendar,omitempty"`
+	// 明细打印排版方式 false:横向 true:纵向。
+	VerticalPrint *bool `json:"verticalPrint,omitempty" xml:"verticalPrint,omitempty"`
+}
+
+type SchemaContentItemsPropsBehaviorLinkage struct {
+	// 关联控件列表。
+	Targets []*SchemaContentItemsPropsBehaviorLinkageTargets `json:"targets,omitempty" xml:"targets,omitempty" type:"Repeated"`
+	// 控件值。
+	Value *string `json:"value,omitempty" xml:"value,omitempty"`
+}
+
+type SchemaContentItemsPropsBehaviorLinkageTargets struct {
+	// 行为。
+	Behavior *string `json:"behavior,omitempty" xml:"behavior,omitempty"`
+	// 字段 id。
+	FieldId *string `json:"fieldId,omitempty" xml:"fieldId,omitempty"`
+}
+
+type SchemaContentItemsPropsObjOptions struct {
+	Value *string `json:"value,omitempty" xml:"value,omitempty"`
+}
+
+type SchemaContentItemsPropsPush struct {
+	// 考勤类型(1表示请假, 2表示出差, 3表示加班, 4表示外出)
+	AttendanceRule *int32 `json:"attendanceRule,omitempty" xml:"attendanceRule,omitempty"`
+	// 开启状态(1表示开启, 0表示关闭)
+	PushSwitch *int32 `json:"pushSwitch,omitempty" xml:"pushSwitch,omitempty"`
+	// 状态显示名称
+	PushTag *string `json:"pushTag,omitempty" xml:"pushTag,omitempty"`
+}
+
+type SchemaContentItemsPropsStatField struct {
+	// id 值。
+	Id *string `json:"id,omitempty" xml:"id,omitempty"`
+	// 名称。
+	Label *string `json:"label,omitempty" xml:"label,omitempty"`
+	// 单位。
+	Unit *string `json:"unit,omitempty" xml:"unit,omitempty"`
+	// 大写。
+	Upper *bool `json:"upper,omitempty" xml:"upper,omitempty"`
+}
+
+// StartProcessInstanceRequest 启动审批流
+type StartProcessInstanceRequest struct {
+	// 不使用审批流模板时,直接指定审批人列表
+	Approvers []*StartProcessInstanceRequestApprovers `json:"approvers,omitempty" xml:"approvers,omitempty" type:"Repeated"`
+	// 抄送人userId列表
+	CcList []*string `json:"ccList,omitempty" xml:"ccList,omitempty" type:"Repeated"`
+	// 抄送时间
+	CcPosition *string `json:"ccPosition,omitempty" xml:"ccPosition,omitempty"`
+	// 部门ID
+	DeptId *int64 `json:"deptId,omitempty" xml:"deptId,omitempty"`
+	// 表单数据内容,控件列表
+	FormComponentValues []*StartProcessInstanceRequestFormComponentValues `json:"formComponentValues,omitempty" xml:"formComponentValues,omitempty" type:"Repeated"`
+	// 企业微应用标识
+	MicroappAgentId *int64 `json:"microappAgentId,omitempty" xml:"microappAgentId,omitempty"`
+	// 审批发起人的userId
+	OriginatorUserId *string `json:"originatorUserId,omitempty" xml:"originatorUserId,omitempty"`
+	// 审批流的唯一码
+	ProcessCode *string `json:"processCode,omitempty" xml:"processCode,omitempty"`
+	// 使用审批流模板时,模板上的自选操作人列表
+	TargetSelectActioners []*StartProcessInstanceRequestTargetSelectActioners `json:"targetSelectActioners,omitempty" xml:"targetSelectActioners,omitempty" type:"Repeated"`
+}
+
+type StartProcessInstanceRequestApprovers struct {
+	// 审批类型
+	ActionType *string `json:"actionType,omitempty" xml:"actionType,omitempty"`
+	// 审批人列表
+	UserIds []*string `json:"userIds,omitempty" xml:"userIds,omitempty" type:"Repeated"`
+}
+
+type StartProcessInstanceRequestTargetSelectActioners struct {
+	// 自选节点的规则key
+	ActionerKey *string `json:"actionerKey,omitempty" xml:"actionerKey,omitempty"`
+	// 操作人userId列表
+	ActionerUserIds []*string `json:"actionerUserIds,omitempty" xml:"actionerUserIds,omitempty" type:"Repeated"`
+}
+
+type StartProcessInstanceRequestFormComponentValues struct {
+	// 控件别名
+	BizAlias *string `json:"bizAlias,omitempty" xml:"bizAlias,omitempty"`
+	// 控件类型
+	ComponentType *string                                                  `json:"componentType,omitempty" xml:"componentType,omitempty"`
+	Details       []*StartProcessInstanceRequestFormComponentValuesDetails `json:"details,omitempty" xml:"details,omitempty" type:"Repeated"`
+	// 控件扩展值
+	ExtValue *string `json:"extValue,omitempty" xml:"extValue,omitempty"`
+	// 控件id
+	Id *string `json:"id,omitempty" xml:"id,omitempty"`
+	// 控件名称
+	Name *string `json:"name,omitempty" xml:"name,omitempty"`
+	// 控件值
+	Value *string `json:"value,omitempty" xml:"value,omitempty"`
+}
+
+type StartProcessInstanceRequestFormComponentValuesDetails struct {
+	// 控件别名
+	BizAlias *string                                                         `json:"bizAlias,omitempty" xml:"bizAlias,omitempty"`
+	Details  []*StartProcessInstanceRequestFormComponentValuesDetailsDetails `json:"details,omitempty" xml:"details,omitempty" type:"Repeated"`
+	// 控件扩展值
+	ExtValue *string `json:"extValue,omitempty" xml:"extValue,omitempty"`
+	// 控件id
+	Id *string `json:"id,omitempty" xml:"id,omitempty"`
+	// 控件名称
+	Name *string `json:"name,omitempty" xml:"name,omitempty"`
+	// 控件值
+	Value *string `json:"value,omitempty" xml:"value,omitempty"`
+}
+
+type StartProcessInstanceRequestFormComponentValuesDetailsDetails struct {
+	// 控件别名
+	BizAlias *string `json:"bizAlias,omitempty" xml:"bizAlias,omitempty"`
+	// 控件类型
+	ComponentType *string `json:"componentType,omitempty" xml:"componentType,omitempty"`
+	// 控件扩展值
+	ExtValue *string `json:"extValue,omitempty" xml:"extValue,omitempty"`
+	// 控件id
+	Id *string `json:"id,omitempty" xml:"id,omitempty"`
+	// 控件名称
+	Name *string `json:"name,omitempty" xml:"name,omitempty"`
+	// 控件值
+	Value *string `json:"value,omitempty" xml:"value,omitempty"`
+}

+ 54 - 0
opms_libary/plugin/dingtalk/workflow/workflow.go

@@ -0,0 +1,54 @@
+package workflow
+
+import (
+	"dashoo.cn/opms_libary/plugin/dingtalk/base"
+	"dashoo.cn/opms_libary/plugin/dingtalk/context"
+	"github.com/alibabacloud-go/tea/tea"
+	"github.com/gogf/gf/frame/g"
+	"github.com/gogf/gf/util/gconv"
+)
+
+const (
+	FormSchemasUrl    = "/v1.0/workflow/forms/schemas/processCodes"
+	CreateInstanceUrl = "/v1.0/workflow/processInstances"
+)
+
+//Workflow OA审批
+type Workflow struct {
+	base.Base
+}
+
+//NewWorkflow init
+func NewWorkflow(context *context.Context) *Workflow {
+	material := new(Workflow)
+	material.Context = context
+	return material
+}
+
+//GetFormSchema 获取表单 schema
+func (w *Workflow) GetFormSchema(processCode string) (mediaID string, err error) {
+	resp, _ := w.HTTPGetWithAccessToken(FormSchemasUrl, g.Map{"processCode": processCode})
+	return gconv.String(resp), nil
+}
+
+//CreateProcessInstance 发起审批实例
+func (w *Workflow) CreateProcessInstance(originUserId, processCode string, deptId int64) (mediaID string, err error) {
+	inst1 := new(StartProcessInstanceRequest)
+	inst1.OriginatorUserId = &originUserId
+	inst1.ProcessCode = &processCode
+	inst1.DeptId = &deptId
+
+	formComponentValues0 := &StartProcessInstanceRequestFormComponentValues{
+		Name:  tea.String("单行输入框"),
+		Value: tea.String("22222"),
+		Id:    tea.String("TextField-K2AD4O5B"),
+	}
+	//approvers0 := &StartProcessInstanceRequestApprovers{
+	//	ActionType: tea.String("NONE"),
+	//	UserIds:    []*string{tea.String("47073111989114")},
+	//}
+	inst1.FormComponentValues = []*StartProcessInstanceRequestFormComponentValues{formComponentValues0}
+	//inst1.Approvers = []*StartProcessInstanceRequestApprovers{approvers0}
+	resp, _ := w.HTTPPostJSONWithAccessToken(CreateInstanceUrl, inst1)
+	return gconv.String(resp), nil
+}

+ 49 - 0
opms_libary/plugin/email/auth.go

@@ -0,0 +1,49 @@
+package email
+
+import (
+	"bytes"
+	"errors"
+	"fmt"
+	"net/smtp"
+)
+
+// loginAuth is an smtp.Auth that implements the LOGIN authentication mechanism.
+type loginAuth struct {
+	username string
+	password string
+	host     string
+}
+
+func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
+	if !server.TLS {
+		advertised := false
+		for _, mechanism := range server.Auth {
+			if mechanism == "LOGIN" {
+				advertised = true
+				break
+			}
+		}
+		if !advertised {
+			return "", nil, errors.New("gomail: unencrypted connection")
+		}
+	}
+	if server.Name != a.host {
+		return "", nil, errors.New("gomail: wrong host name")
+	}
+	return "LOGIN", nil, nil
+}
+
+func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
+	if !more {
+		return nil, nil
+	}
+
+	switch {
+	case bytes.Equal(fromServer, []byte("Username:")):
+		return []byte(a.username), nil
+	case bytes.Equal(fromServer, []byte("Password:")):
+		return []byte(a.password), nil
+	default:
+		return nil, fmt.Errorf("gomail: unexpected server challenge: %s", fromServer)
+	}
+}

+ 9 - 0
opms_libary/plugin/email/config.go

@@ -0,0 +1,9 @@
+package email
+
+// Config for user
+type Config struct {
+	MailHost     string
+	MailPort     int
+	MailUser     string
+	MailPassword string
+}

+ 220 - 0
opms_libary/plugin/email/example_test.go

@@ -0,0 +1,220 @@
+package email_test
+
+import (
+	"dashoo.cn/opms_libary/plugin/email"
+	"fmt"
+	"html/template"
+	"io"
+	"log"
+	"time"
+)
+
+func Example() {
+	m := email.NewMessage()
+	m.SetHeader("From", "alex@example.com")
+	m.SetHeader("To", "bob@example.com", "cora@example.com")
+	m.SetAddressHeader("Cc", "dan@example.com", "Dan")
+	m.SetHeader("Subject", "Hello!")
+	m.SetBody("text/html", "Hello <b>Bob</b> and <i>Cora</i>!")
+	m.Attach("/home/Alex/lolcat.jpg")
+
+	// Send the email to Bob, Cora and Dan.
+	if err := email.Client.DialAndSend(m); err != nil {
+		panic(err)
+	}
+}
+
+// A daemon that listens to a channel and sends all incoming messages.
+func Example_daemon() {
+	ch := make(chan *email.Message)
+
+	go func() {
+		d := email.NewClient()
+
+		var s email.SendCloser
+		var err error
+		open := false
+		for {
+			select {
+			case m, ok := <-ch:
+				if !ok {
+					return
+				}
+				if !open {
+					if s, err = d.Dial(); err != nil {
+						panic(err)
+					}
+					open = true
+				}
+				if err := email.Send(s, m); err != nil {
+					log.Print(err)
+				}
+			// Close the connection to the SMTP server if no email was sent in
+			// the last 30 seconds.
+			case <-time.After(30 * time.Second):
+				if open {
+					if err := s.Close(); err != nil {
+						panic(err)
+					}
+					open = false
+				}
+			}
+		}
+	}()
+
+	// Use the channel in your program to send emails.
+
+	// Close the channel to stop the mail daemon.
+	close(ch)
+}
+
+// Efficiently send a customized newsletter to a list of recipients.
+func Example_newsletter() {
+	// The list of recipients.
+	var list []struct {
+		Name    string
+		Address string
+	}
+
+	d := email.NewClient()
+	s, err := d.Dial()
+	if err != nil {
+		panic(err)
+	}
+
+	m := email.NewMessage()
+	for _, r := range list {
+		m.SetHeader("From", "no-reply@example.com")
+		m.SetAddressHeader("To", r.Address, r.Name)
+		m.SetHeader("Subject", "Newsletter #1")
+		m.SetBody("text/html", fmt.Sprintf("Hello %s!", r.Name))
+
+		if err := email.Send(s, m); err != nil {
+			log.Printf("Could not send email to %q: %v", r.Address, err)
+		}
+		m.Reset()
+	}
+}
+
+// Send an email using a local SMTP server.
+func Example_noAuth() {
+	m := email.NewMessage()
+	m.SetHeader("From", "from@example.com")
+	m.SetHeader("To", "to@example.com")
+	m.SetHeader("Subject", "Hello!")
+	m.SetBody("text/plain", "Hello!")
+
+	d := email.ClientImpl{Host: "localhost", Port: 587}
+	if err := d.DialAndSend(m); err != nil {
+		panic(err)
+	}
+}
+
+// Send an email using an API or postfix.
+func Example_noSMTP() {
+	m := email.NewMessage()
+	m.SetHeader("From", "from@example.com")
+	m.SetHeader("To", "to@example.com")
+	m.SetHeader("Subject", "Hello!")
+	m.SetBody("text/plain", "Hello!")
+
+	s := email.SendFunc(func(from string, to []string, msg io.WriterTo) error {
+		// Implements you email-sending function, for example by calling
+		// an API, or running postfix, etc.
+		fmt.Println("From:", from)
+		fmt.Println("To:", to)
+		return nil
+	})
+
+	if err := email.Send(s, m); err != nil {
+		panic(err)
+	}
+	// Output:
+	// From: from@example.com
+	// To: [to@example.com]
+}
+
+var m *email.Message
+
+func ExampleSetCopyFunc() {
+	m.Attach("foo.txt", email.SetCopyFunc(func(w io.Writer) error {
+		_, err := w.Write([]byte("Content of foo.txt"))
+		return err
+	}))
+}
+
+func ExampleSetHeader() {
+	h := map[string][]string{"Content-ID": {"<foo@bar.mail>"}}
+	m.Attach("foo.jpg", email.SetHeader(h))
+}
+
+func ExampleRename() {
+	m.Attach("/tmp/0000146.jpg", email.Rename("picture.jpg"))
+}
+
+func ExampleMessage_AddAlternative() {
+	m.SetBody("text/plain", "Hello!")
+	m.AddAlternative("text/html", "<p>Hello!</p>")
+}
+
+func ExampleMessage_AddAlternativeWriter() {
+	t := template.Must(template.New("example").Parse("Hello {{.}}!"))
+	m.AddAlternativeWriter("text/plain", func(w io.Writer) error {
+		return t.Execute(w, "Bob")
+	})
+}
+
+func ExampleMessage_Attach() {
+	m.Attach("/tmp/image.jpg")
+}
+
+func ExampleMessage_Embed() {
+	m.Embed("/tmp/image.jpg")
+	m.SetBody("text/html", `<img src="cid:image.jpg" alt="My image" />`)
+}
+
+func ExampleMessage_FormatAddress() {
+	m.SetHeader("To", m.FormatAddress("bob@example.com", "Bob"), m.FormatAddress("cora@example.com", "Cora"))
+}
+
+func ExampleMessage_FormatDate() {
+	m.SetHeaders(map[string][]string{
+		"X-Date": {m.FormatDate(time.Now())},
+	})
+}
+
+func ExampleMessage_SetAddressHeader() {
+	m.SetAddressHeader("To", "bob@example.com", "Bob")
+}
+
+func ExampleMessage_SetBody() {
+	m.SetBody("text/plain", "Hello!")
+}
+
+func ExampleMessage_SetDateHeader() {
+	m.SetDateHeader("X-Date", time.Now())
+}
+
+func ExampleMessage_SetHeader() {
+	m.SetHeader("Subject", "Hello!")
+}
+
+func ExampleMessage_SetHeaders() {
+	m.SetHeaders(map[string][]string{
+		"From":    {m.FormatAddress("alex@example.com", "Alex")},
+		"To":      {"bob@example.com", "cora@example.com"},
+		"Subject": {"Hello"},
+	})
+}
+
+func ExampleSetCharset() {
+	m = email.NewMessage(email.SetCharset("ISO-8859-1"))
+}
+
+func ExampleSetEncoding() {
+	m = email.NewMessage(email.SetEncoding(email.Base64))
+}
+
+func ExampleSetPartEncoding() {
+	m.SetBody("text/plain", "Hello!", email.SetPartEncoding(email.Unencoded))
+}

+ 322 - 0
opms_libary/plugin/email/message.go

@@ -0,0 +1,322 @@
+package email
+
+import (
+	"bytes"
+	"io"
+	"os"
+	"path/filepath"
+	"time"
+)
+
+// Message represents an email.
+type Message struct {
+	header      header
+	parts       []*part
+	attachments []*file
+	embedded    []*file
+	charset     string
+	encoding    Encoding
+	hEncoder    mimeEncoder
+	buf         bytes.Buffer
+}
+
+type header map[string][]string
+
+type part struct {
+	contentType string
+	copier      func(io.Writer) error
+	encoding    Encoding
+}
+
+// NewMessage creates a new message. It uses UTF-8 and quoted-printable encoding
+// by default.
+func NewMessage(settings ...MessageSetting) *Message {
+	m := &Message{
+		header:   make(header),
+		charset:  "UTF-8",
+		encoding: QuotedPrintable,
+	}
+
+	m.applySettings(settings)
+
+	if m.encoding == Base64 {
+		m.hEncoder = bEncoding
+	} else {
+		m.hEncoder = qEncoding
+	}
+
+	return m
+}
+
+// Reset resets the message so it can be reused. The message keeps its previous
+// settings so it is in the same state that after a call to NewMessage.
+func (m *Message) Reset() {
+	for k := range m.header {
+		delete(m.header, k)
+	}
+	m.parts = nil
+	m.attachments = nil
+	m.embedded = nil
+}
+
+func (m *Message) applySettings(settings []MessageSetting) {
+	for _, s := range settings {
+		s(m)
+	}
+}
+
+// A MessageSetting can be used as an argument in NewMessage to configure an
+// email.
+type MessageSetting func(m *Message)
+
+// SetCharset is a message setting to set the charset of the email.
+func SetCharset(charset string) MessageSetting {
+	return func(m *Message) {
+		m.charset = charset
+	}
+}
+
+// SetEncoding is a message setting to set the encoding of the email.
+func SetEncoding(enc Encoding) MessageSetting {
+	return func(m *Message) {
+		m.encoding = enc
+	}
+}
+
+// Encoding represents a MIME encoding scheme like quoted-printable or base64.
+type Encoding string
+
+const (
+	// QuotedPrintable represents the quoted-printable encoding as defined in
+	// RFC 2045.
+	QuotedPrintable Encoding = "quoted-printable"
+	// Base64 represents the base64 encoding as defined in RFC 2045.
+	Base64 Encoding = "base64"
+	// Unencoded can be used to avoid encoding the body of an email. The headers
+	// will still be encoded using quoted-printable encoding.
+	Unencoded Encoding = "8bit"
+)
+
+// SetHeader sets a value to the given header field.
+func (m *Message) SetHeader(field string, value ...string) {
+	m.encodeHeader(value)
+	m.header[field] = value
+}
+
+func (m *Message) encodeHeader(values []string) {
+	for i := range values {
+		values[i] = m.encodeString(values[i])
+	}
+}
+
+func (m *Message) encodeString(value string) string {
+	return m.hEncoder.Encode(m.charset, value)
+}
+
+// SetHeaders sets the message headers.
+func (m *Message) SetHeaders(h map[string][]string) {
+	for k, v := range h {
+		m.SetHeader(k, v...)
+	}
+}
+
+// SetAddressHeader sets an address to the given header field.
+func (m *Message) SetAddressHeader(field, address, name string) {
+	m.header[field] = []string{m.FormatAddress(address, name)}
+}
+
+// FormatAddress formats an address and a name as a valid RFC 5322 address.
+func (m *Message) FormatAddress(address, name string) string {
+	if name == "" {
+		return address
+	}
+
+	enc := m.encodeString(name)
+	if enc == name {
+		m.buf.WriteByte('"')
+		for i := 0; i < len(name); i++ {
+			b := name[i]
+			if b == '\\' || b == '"' {
+				m.buf.WriteByte('\\')
+			}
+			m.buf.WriteByte(b)
+		}
+		m.buf.WriteByte('"')
+	} else if hasSpecials(name) {
+		m.buf.WriteString(bEncoding.Encode(m.charset, name))
+	} else {
+		m.buf.WriteString(enc)
+	}
+	m.buf.WriteString(" <")
+	m.buf.WriteString(address)
+	m.buf.WriteByte('>')
+
+	addr := m.buf.String()
+	m.buf.Reset()
+	return addr
+}
+
+func hasSpecials(text string) bool {
+	for i := 0; i < len(text); i++ {
+		switch c := text[i]; c {
+		case '(', ')', '<', '>', '[', ']', ':', ';', '@', '\\', ',', '.', '"':
+			return true
+		}
+	}
+
+	return false
+}
+
+// SetDateHeader sets a date to the given header field.
+func (m *Message) SetDateHeader(field string, date time.Time) {
+	m.header[field] = []string{m.FormatDate(date)}
+}
+
+// FormatDate formats a date as a valid RFC 5322 date.
+func (m *Message) FormatDate(date time.Time) string {
+	return date.Format(time.RFC1123Z)
+}
+
+// GetHeader gets a header field.
+func (m *Message) GetHeader(field string) []string {
+	return m.header[field]
+}
+
+// SetBody sets the body of the message. It replaces any content previously set
+// by SetBody, AddAlternative or AddAlternativeWriter.
+func (m *Message) SetBody(contentType, body string, settings ...PartSetting) {
+	m.parts = []*part{m.newPart(contentType, newCopier(body), settings)}
+}
+
+// AddAlternative adds an alternative part to the message.
+//
+// It is commonly used to send HTML emails that default to the plain text
+// version for backward compatibility. AddAlternative appends the new part to
+// the end of the message. So the plain text part should be added before the
+// HTML part. See http://en.wikipedia.org/wiki/MIME#Alternative
+func (m *Message) AddAlternative(contentType, body string, settings ...PartSetting) {
+	m.AddAlternativeWriter(contentType, newCopier(body), settings...)
+}
+
+func newCopier(s string) func(io.Writer) error {
+	return func(w io.Writer) error {
+		_, err := io.WriteString(w, s)
+		return err
+	}
+}
+
+// AddAlternativeWriter adds an alternative part to the message. It can be
+// useful with the text/template or html/template packages.
+func (m *Message) AddAlternativeWriter(contentType string, f func(io.Writer) error, settings ...PartSetting) {
+	m.parts = append(m.parts, m.newPart(contentType, f, settings))
+}
+
+func (m *Message) newPart(contentType string, f func(io.Writer) error, settings []PartSetting) *part {
+	p := &part{
+		contentType: contentType,
+		copier:      f,
+		encoding:    m.encoding,
+	}
+
+	for _, s := range settings {
+		s(p)
+	}
+
+	return p
+}
+
+// A PartSetting can be used as an argument in Message.SetBody,
+// Message.AddAlternative or Message.AddAlternativeWriter to configure the part
+// added to a message.
+type PartSetting func(*part)
+
+// SetPartEncoding sets the encoding of the part added to the message. By
+// default, parts use the same encoding than the message.
+func SetPartEncoding(e Encoding) PartSetting {
+	return PartSetting(func(p *part) {
+		p.encoding = e
+	})
+}
+
+type file struct {
+	Name     string
+	Header   map[string][]string
+	CopyFunc func(w io.Writer) error
+}
+
+func (f *file) setHeader(field, value string) {
+	f.Header[field] = []string{value}
+}
+
+// A FileSetting can be used as an argument in Message.Attach or Message.Embed.
+type FileSetting func(*file)
+
+// SetHeader is a file setting to set the MIME header of the message part that
+// contains the file content.
+//
+// Mandatory headers are automatically added if they are not set when sending
+// the email.
+func SetHeader(h map[string][]string) FileSetting {
+	return func(f *file) {
+		for k, v := range h {
+			f.Header[k] = v
+		}
+	}
+}
+
+// Rename is a file setting to set the name of the attachment if the name is
+// different than the filename on disk.
+func Rename(name string) FileSetting {
+	return func(f *file) {
+		f.Name = name
+	}
+}
+
+// SetCopyFunc is a file setting to replace the function that runs when the
+// message is sent. It should copy the content of the file to the io.Writer.
+//
+// The default copy function opens the file with the given filename, and copy
+// its content to the io.Writer.
+func SetCopyFunc(f func(io.Writer) error) FileSetting {
+	return func(fi *file) {
+		fi.CopyFunc = f
+	}
+}
+
+func (m *Message) appendFile(list []*file, name string, settings []FileSetting) []*file {
+	f := &file{
+		Name:   filepath.Base(name),
+		Header: make(map[string][]string),
+		CopyFunc: func(w io.Writer) error {
+			h, err := os.Open(name)
+			if err != nil {
+				return err
+			}
+			if _, err := io.Copy(w, h); err != nil {
+				h.Close()
+				return err
+			}
+			return h.Close()
+		},
+	}
+
+	for _, s := range settings {
+		s(f)
+	}
+
+	if list == nil {
+		return []*file{f}
+	}
+
+	return append(list, f)
+}
+
+// Attach attaches the files to the email.
+func (m *Message) Attach(filename string, settings ...FileSetting) {
+	m.attachments = m.appendFile(m.attachments, filename, settings)
+}
+
+// Embed embeds the images to the email.
+func (m *Message) Embed(filename string, settings ...FileSetting) {
+	m.embedded = m.appendFile(m.embedded, filename, settings)
+}

+ 22 - 0
opms_libary/plugin/email/mime.go

@@ -0,0 +1,22 @@
+//go:build go1.5
+// +build go1.5
+
+package email
+
+import (
+	"mime"
+	"mime/quotedprintable"
+	"strings"
+)
+
+var newQPWriter = quotedprintable.NewWriter
+
+type mimeEncoder struct {
+	mime.WordEncoder
+}
+
+var (
+	bEncoding     = mimeEncoder{mime.BEncoding}
+	qEncoding     = mimeEncoder{mime.QEncoding}
+	lastIndexByte = strings.LastIndexByte
+)

+ 116 - 0
opms_libary/plugin/email/send.go

@@ -0,0 +1,116 @@
+package email
+
+import (
+	"errors"
+	"fmt"
+	"io"
+	"net/mail"
+)
+
+// Sender is the interface that wraps the Send method.
+//
+// Send sends an email to the given addresses.
+type Sender interface {
+	Send(from string, to []string, msg io.WriterTo) error
+}
+
+// SendCloser is the interface that groups the Send and Close methods.
+type SendCloser interface {
+	Sender
+	Close() error
+}
+
+// A SendFunc is a function that sends emails to the given addresses.
+//
+// The SendFunc type is an adapter to allow the use of ordinary functions as
+// email senders. If f is a function with the appropriate signature, SendFunc(f)
+// is a Sender object that calls f.
+type SendFunc func(from string, to []string, msg io.WriterTo) error
+
+// Send calls f(from, to, msg).
+func (f SendFunc) Send(from string, to []string, msg io.WriterTo) error {
+	return f(from, to, msg)
+}
+
+// Send sends emails using the given Sender.
+func Send(s Sender, msg ...*Message) error {
+	for i, m := range msg {
+		if err := send(s, m); err != nil {
+			return fmt.Errorf("gomail: could not send email %d: %v", i+1, err)
+		}
+	}
+
+	return nil
+}
+
+func send(s Sender, m *Message) error {
+	from, err := m.getFrom()
+	if err != nil {
+		return err
+	}
+
+	to, err := m.getRecipients()
+	if err != nil {
+		return err
+	}
+
+	if err := s.Send(from, to, m); err != nil {
+		return err
+	}
+
+	return nil
+}
+
+func (m *Message) getFrom() (string, error) {
+	from := m.header["Sender"]
+	if len(from) == 0 {
+		from = m.header["From"]
+		if len(from) == 0 {
+			return "", errors.New(`gomail: invalid message, "From" field is absent`)
+		}
+	}
+
+	return parseAddress(from[0])
+}
+
+func (m *Message) getRecipients() ([]string, error) {
+	n := 0
+	for _, field := range []string{"To", "Cc", "Bcc"} {
+		if addresses, ok := m.header[field]; ok {
+			n += len(addresses)
+		}
+	}
+	list := make([]string, 0, n)
+
+	for _, field := range []string{"To", "Cc", "Bcc"} {
+		if addresses, ok := m.header[field]; ok {
+			for _, a := range addresses {
+				addr, err := parseAddress(a)
+				if err != nil {
+					return nil, err
+				}
+				list = addAddress(list, addr)
+			}
+		}
+	}
+
+	return list, nil
+}
+
+func addAddress(list []string, addr string) []string {
+	for _, a := range list {
+		if addr == a {
+			return list
+		}
+	}
+
+	return append(list, addr)
+}
+
+func parseAddress(field string) (string, error) {
+	addr, err := mail.ParseAddress(field)
+	if err != nil {
+		return "", fmt.Errorf("gomail: invalid address %q: %v", field, err)
+	}
+	return addr.Address, nil
+}

+ 213 - 0
opms_libary/plugin/email/smtp.go

@@ -0,0 +1,213 @@
+package email
+
+import (
+	"crypto/tls"
+	"fmt"
+	"github.com/gogf/gf/frame/g"
+	"io"
+	"net"
+	"net/smtp"
+	"strings"
+	"time"
+)
+
+var Client *ClientImpl
+
+func init() {
+	Client = NewClient()
+}
+
+// A ClientImpl is a dialer to an SMTP server.
+type ClientImpl struct {
+	// Host represents the host of the SMTP server.
+	Host string
+	// Port represents the port of the SMTP server.
+	Port int
+	// Username is the username to use to authenticate to the SMTP server.
+	Username string
+	// Password is the password to use to authenticate to the SMTP server.
+	Password string
+	// Auth represents the authentication mechanism used to authenticate to the
+	// SMTP server.
+	Auth smtp.Auth
+	// SSL defines whether an SSL connection is used. It should be false in
+	// most cases since the authentication mechanism should use the STARTTLS
+	// extension instead.
+	SSL bool
+	// TSLConfig represents the TLS configuration used for the TLS (when the
+	// STARTTLS extension is used) or SSL connection.
+	TLSConfig *tls.Config
+	// LocalName is the hostname sent to the SMTP server with the HELO command.
+	// By default, "localhost" is sent.
+	LocalName string
+}
+
+// NewClient returns a new SMTP ClientImpl. The given parameters are used to connect
+// to the SMTP server.
+func NewClient() *ClientImpl {
+	var config = Config{
+		MailHost:     g.Config().GetString("email.host"),
+		MailPort:     g.Config().GetInt("email.port"),
+		MailUser:     g.Config().GetString("email.user"),
+		MailPassword: g.Config().GetString("email.password"),
+	}
+	return newClient(config)
+}
+
+// NewClient returns a new SMTP ClientImpl. The given parameters are used to connect
+// to the SMTP server.
+func newClient(cfg Config) *ClientImpl {
+	return &ClientImpl{
+		Host:     cfg.MailHost,
+		Port:     cfg.MailPort,
+		Username: cfg.MailUser,
+		Password: cfg.MailPassword,
+		SSL:      cfg.MailPort == 465,
+	}
+}
+
+// Dial dials and authenticates to an SMTP server. The returned SendCloser
+// should be closed when done using it.
+func (d *ClientImpl) Dial() (SendCloser, error) {
+	conn, err := netDialTimeout("tcp", addr(d.Host, d.Port), 10*time.Second)
+	if err != nil {
+		return nil, err
+	}
+
+	if d.SSL {
+		conn = tlsClient(conn, d.tlsConfig())
+	}
+
+	c, err := smtpNewClient(conn, d.Host)
+	if err != nil {
+		return nil, err
+	}
+
+	if d.LocalName != "" {
+		if err := c.Hello(d.LocalName); err != nil {
+			return nil, err
+		}
+	}
+
+	if !d.SSL {
+		if ok, _ := c.Extension("STARTTLS"); ok {
+			if err := c.StartTLS(d.tlsConfig()); err != nil {
+				c.Close()
+				return nil, err
+			}
+		}
+	}
+
+	if d.Auth == nil && d.Username != "" {
+		if ok, auths := c.Extension("AUTH"); ok {
+			if strings.Contains(auths, "CRAM-MD5") {
+				d.Auth = smtp.CRAMMD5Auth(d.Username, d.Password)
+			} else if strings.Contains(auths, "LOGIN") &&
+				!strings.Contains(auths, "PLAIN") {
+				d.Auth = &loginAuth{
+					username: d.Username,
+					password: d.Password,
+					host:     d.Host,
+				}
+			} else {
+				d.Auth = smtp.PlainAuth("", d.Username, d.Password, d.Host)
+			}
+		}
+	}
+
+	if d.Auth != nil {
+		if err = c.Auth(d.Auth); err != nil {
+			c.Close()
+			return nil, err
+		}
+	}
+
+	return &smtpSender{c, d}, nil
+}
+
+func (d *ClientImpl) tlsConfig() *tls.Config {
+	if d.TLSConfig == nil {
+		return &tls.Config{ServerName: d.Host}
+	}
+	return d.TLSConfig
+}
+
+func addr(host string, port int) string {
+	return fmt.Sprintf("%s:%d", host, port)
+}
+
+// DialAndSend opens a connection to the SMTP server, sends the given emails and
+// closes the connection.
+func (d *ClientImpl) DialAndSend(m ...*Message) error {
+	s, err := d.Dial()
+	if err != nil {
+		return err
+	}
+	defer s.Close()
+
+	return Send(s, m...)
+}
+
+type smtpSender struct {
+	smtpClient
+	d *ClientImpl
+}
+
+func (c *smtpSender) Send(from string, to []string, msg io.WriterTo) error {
+	if err := c.Mail(from); err != nil {
+		if err == io.EOF {
+			// This is probably due to a timeout, so reconnect and try again.
+			sc, derr := c.d.Dial()
+			if derr == nil {
+				if s, ok := sc.(*smtpSender); ok {
+					*c = *s
+					return c.Send(from, to, msg)
+				}
+			}
+		}
+		return err
+	}
+
+	for _, addr := range to {
+		if err := c.Rcpt(addr); err != nil {
+			return err
+		}
+	}
+
+	w, err := c.Data()
+	if err != nil {
+		return err
+	}
+
+	if _, err = msg.WriteTo(w); err != nil {
+		w.Close()
+		return err
+	}
+
+	return w.Close()
+}
+
+func (c *smtpSender) Close() error {
+	return c.Quit()
+}
+
+// Stubbed out for tests.
+var (
+	netDialTimeout = net.DialTimeout
+	tlsClient      = tls.Client
+	smtpNewClient  = func(conn net.Conn, host string) (smtpClient, error) {
+		return smtp.NewClient(conn, host)
+	}
+)
+
+type smtpClient interface {
+	Hello(string) error
+	Extension(string) (bool, string)
+	StartTLS(*tls.Config) error
+	Auth(smtp.Auth) error
+	Mail(string) error
+	Rcpt(string) error
+	Data() (io.WriteCloser, error)
+	Quit() error
+	Close() error
+}

+ 306 - 0
opms_libary/plugin/email/writeto.go

@@ -0,0 +1,306 @@
+package email
+
+import (
+	"encoding/base64"
+	"errors"
+	"io"
+	"mime"
+	"mime/multipart"
+	"path/filepath"
+	"strings"
+	"time"
+)
+
+// WriteTo implements io.WriterTo. It dumps the whole message into w.
+func (m *Message) WriteTo(w io.Writer) (int64, error) {
+	mw := &messageWriter{w: w}
+	mw.writeMessage(m)
+	return mw.n, mw.err
+}
+
+func (w *messageWriter) writeMessage(m *Message) {
+	if _, ok := m.header["Mime-Version"]; !ok {
+		w.writeString("Mime-Version: 1.0\r\n")
+	}
+	if _, ok := m.header["Date"]; !ok {
+		w.writeHeader("Date", m.FormatDate(now()))
+	}
+	w.writeHeaders(m.header)
+
+	if m.hasMixedPart() {
+		w.openMultipart("mixed")
+	}
+
+	if m.hasRelatedPart() {
+		w.openMultipart("related")
+	}
+
+	if m.hasAlternativePart() {
+		w.openMultipart("alternative")
+	}
+	for _, part := range m.parts {
+		w.writePart(part, m.charset)
+	}
+	if m.hasAlternativePart() {
+		w.closeMultipart()
+	}
+
+	w.addFiles(m.embedded, false)
+	if m.hasRelatedPart() {
+		w.closeMultipart()
+	}
+
+	w.addFiles(m.attachments, true)
+	if m.hasMixedPart() {
+		w.closeMultipart()
+	}
+}
+
+func (m *Message) hasMixedPart() bool {
+	return (len(m.parts) > 0 && len(m.attachments) > 0) || len(m.attachments) > 1
+}
+
+func (m *Message) hasRelatedPart() bool {
+	return (len(m.parts) > 0 && len(m.embedded) > 0) || len(m.embedded) > 1
+}
+
+func (m *Message) hasAlternativePart() bool {
+	return len(m.parts) > 1
+}
+
+type messageWriter struct {
+	w          io.Writer
+	n          int64
+	writers    [3]*multipart.Writer
+	partWriter io.Writer
+	depth      uint8
+	err        error
+}
+
+func (w *messageWriter) openMultipart(mimeType string) {
+	mw := multipart.NewWriter(w)
+	contentType := "multipart/" + mimeType + ";\r\n boundary=" + mw.Boundary()
+	w.writers[w.depth] = mw
+
+	if w.depth == 0 {
+		w.writeHeader("Content-Type", contentType)
+		w.writeString("\r\n")
+	} else {
+		w.createPart(map[string][]string{
+			"Content-Type": {contentType},
+		})
+	}
+	w.depth++
+}
+
+func (w *messageWriter) createPart(h map[string][]string) {
+	w.partWriter, w.err = w.writers[w.depth-1].CreatePart(h)
+}
+
+func (w *messageWriter) closeMultipart() {
+	if w.depth > 0 {
+		w.writers[w.depth-1].Close()
+		w.depth--
+	}
+}
+
+func (w *messageWriter) writePart(p *part, charset string) {
+	w.writeHeaders(map[string][]string{
+		"Content-Type":              {p.contentType + "; charset=" + charset},
+		"Content-Transfer-Encoding": {string(p.encoding)},
+	})
+	w.writeBody(p.copier, p.encoding)
+}
+
+func (w *messageWriter) addFiles(files []*file, isAttachment bool) {
+	for _, f := range files {
+		if _, ok := f.Header["Content-Type"]; !ok {
+			mediaType := mime.TypeByExtension(filepath.Ext(f.Name))
+			if mediaType == "" {
+				mediaType = "application/octet-stream"
+			}
+			f.setHeader("Content-Type", mediaType+`; name="`+f.Name+`"`)
+		}
+
+		if _, ok := f.Header["Content-Transfer-Encoding"]; !ok {
+			f.setHeader("Content-Transfer-Encoding", string(Base64))
+		}
+
+		if _, ok := f.Header["Content-Disposition"]; !ok {
+			var disp string
+			if isAttachment {
+				disp = "attachment"
+			} else {
+				disp = "inline"
+			}
+			f.setHeader("Content-Disposition", disp+`; filename="`+f.Name+`"`)
+		}
+
+		if !isAttachment {
+			if _, ok := f.Header["Content-ID"]; !ok {
+				f.setHeader("Content-ID", "<"+f.Name+">")
+			}
+		}
+		w.writeHeaders(f.Header)
+		w.writeBody(f.CopyFunc, Base64)
+	}
+}
+
+func (w *messageWriter) Write(p []byte) (int, error) {
+	if w.err != nil {
+		return 0, errors.New("gomail: cannot write as writer is in error")
+	}
+
+	var n int
+	n, w.err = w.w.Write(p)
+	w.n += int64(n)
+	return n, w.err
+}
+
+func (w *messageWriter) writeString(s string) {
+	n, _ := io.WriteString(w.w, s)
+	w.n += int64(n)
+}
+
+func (w *messageWriter) writeHeader(k string, v ...string) {
+	w.writeString(k)
+	if len(v) == 0 {
+		w.writeString(":\r\n")
+		return
+	}
+	w.writeString(": ")
+
+	// Max header line length is 78 characters in RFC 5322 and 76 characters
+	// in RFC 2047. So for the sake of simplicity we use the 76 characters
+	// limit.
+	charsLeft := 76 - len(k) - len(": ")
+
+	for i, s := range v {
+		// If the line is already too long, insert a newline right away.
+		if charsLeft < 1 {
+			if i == 0 {
+				w.writeString("\r\n ")
+			} else {
+				w.writeString(",\r\n ")
+			}
+			charsLeft = 75
+		} else if i != 0 {
+			w.writeString(", ")
+			charsLeft -= 2
+		}
+
+		// While the header content is too long, fold it by inserting a newline.
+		for len(s) > charsLeft {
+			s = w.writeLine(s, charsLeft)
+			charsLeft = 75
+		}
+		w.writeString(s)
+		if i := lastIndexByte(s, '\n'); i != -1 {
+			charsLeft = 75 - (len(s) - i - 1)
+		} else {
+			charsLeft -= len(s)
+		}
+	}
+	w.writeString("\r\n")
+}
+
+func (w *messageWriter) writeLine(s string, charsLeft int) string {
+	// If there is already a newline before the limit. Write the line.
+	if i := strings.IndexByte(s, '\n'); i != -1 && i < charsLeft {
+		w.writeString(s[:i+1])
+		return s[i+1:]
+	}
+
+	for i := charsLeft - 1; i >= 0; i-- {
+		if s[i] == ' ' {
+			w.writeString(s[:i])
+			w.writeString("\r\n ")
+			return s[i+1:]
+		}
+	}
+
+	// We could not insert a newline cleanly so look for a space or a newline
+	// even if it is after the limit.
+	for i := 75; i < len(s); i++ {
+		if s[i] == ' ' {
+			w.writeString(s[:i])
+			w.writeString("\r\n ")
+			return s[i+1:]
+		}
+		if s[i] == '\n' {
+			w.writeString(s[:i+1])
+			return s[i+1:]
+		}
+	}
+
+	// Too bad, no space or newline in the whole string. Just write everything.
+	w.writeString(s)
+	return ""
+}
+
+func (w *messageWriter) writeHeaders(h map[string][]string) {
+	if w.depth == 0 {
+		for k, v := range h {
+			if k != "Bcc" {
+				w.writeHeader(k, v...)
+			}
+		}
+	} else {
+		w.createPart(h)
+	}
+}
+
+func (w *messageWriter) writeBody(f func(io.Writer) error, enc Encoding) {
+	var subWriter io.Writer
+	if w.depth == 0 {
+		w.writeString("\r\n")
+		subWriter = w.w
+	} else {
+		subWriter = w.partWriter
+	}
+
+	if enc == Base64 {
+		wc := base64.NewEncoder(base64.StdEncoding, newBase64LineWriter(subWriter))
+		w.err = f(wc)
+		wc.Close()
+	} else if enc == Unencoded {
+		w.err = f(subWriter)
+	} else {
+		wc := newQPWriter(subWriter)
+		w.err = f(wc)
+		wc.Close()
+	}
+}
+
+// As required by RFC 2045, 6.7. (page 21) for quoted-printable, and
+// RFC 2045, 6.8. (page 25) for base64.
+const maxLineLen = 76
+
+// base64LineWriter limits text encoded in base64 to 76 characters per line
+type base64LineWriter struct {
+	w       io.Writer
+	lineLen int
+}
+
+func newBase64LineWriter(w io.Writer) *base64LineWriter {
+	return &base64LineWriter{w: w}
+}
+
+func (w *base64LineWriter) Write(p []byte) (int, error) {
+	n := 0
+	for len(p)+w.lineLen > maxLineLen {
+		w.w.Write(p[:maxLineLen-w.lineLen])
+		w.w.Write([]byte("\r\n"))
+		p = p[maxLineLen-w.lineLen:]
+		n += maxLineLen - w.lineLen
+		w.lineLen = 0
+	}
+
+	w.w.Write(p)
+	w.lineLen += len(p)
+
+	return n + len(p), nil
+}
+
+// Stubbed out for testing.
+var now = time.Now

+ 77 - 0
opms_libary/plugin/wechat/client.go

@@ -0,0 +1,77 @@
+package wechat
+
+import (
+	"dashoo.cn/opms_libary/plugin/wechat/context"
+	"fmt"
+	"github.com/gogf/gf/os/gcache"
+	"sync"
+)
+
+var Client *ClientImpl
+
+var memCache *gcache.Cache
+
+// ClientImpl struct
+type ClientImpl struct {
+	Context *context.Context
+}
+
+func init() {
+	Client = NewClient()
+}
+
+// NewClient init
+func NewClient() *ClientImpl {
+	var config = context.Config{
+		//微信公众平台,需要填写的信息
+		AppID:          "wx7a7372d6b94c0ee9",                          //g.Config().GetString("wechat.app-id"),     //"your app id",
+		AppSecret:      "5733eee31e2625dd2ebf18e2d4cd3cbc",            //g.Config().GetString("wechat.app-secret"), //"your app secret",
+		Token:          "WEIXIN_dashoo_labsop_171210",                 //g.Config().GetString("wechat.token"),      //"your token",
+		EncodingAESKey: "9b2TW1dend4Vsu4prELD7Wfg0WHpHf48i6OtViYimfZ", //g.Config().GetString("wechat.aes-key"),    //"your encoding aes key",
+	}
+	return newClient(config)
+}
+
+func newClient(cfg context.Config) *ClientImpl {
+	context := new(context.Context)
+	initContext(&cfg, context)
+	return &ClientImpl{context}
+}
+
+func initContext(cfg *context.Config, context *context.Context) {
+	if cfg.Cache == nil {
+		if memCache == nil {
+			memCache = gcache.New()
+		}
+		cfg.Cache = memCache
+	}
+	context.Config = cfg
+
+	context.SetAccessTokenLock(new(sync.RWMutex))
+	context.SetJsAPITicketLock(new(sync.RWMutex))
+}
+
+//MpClient 公众平台
+func (wc *ClientImpl) MpClient() (media *Media, err error) {
+	err = wc.checkCfgBase()
+	if err != nil {
+		return
+	}
+	media = NewMedia()
+	media.ClientImpl = wc
+	return
+}
+
+//checkCfgBase 检查配置基本信息
+func (wc *ClientImpl) checkCfgBase() (err error) {
+	if wc.Context.AppID == "" {
+		return fmt.Errorf("%s", "配置中没有AppID")
+	}
+	if wc.Context.AppSecret == "" {
+		return fmt.Errorf("%s", "配置中没有AppSecret")
+	}
+	if wc.Context.Token == "" {
+		return fmt.Errorf("%s", "配置中没有Token")
+	}
+	return
+}

+ 38 - 0
opms_libary/plugin/wechat/client_test.go

@@ -0,0 +1,38 @@
+package wechat
+
+import (
+	"dashoo.cn/opms_libary/plugin/wechat/mp/template"
+	"fmt"
+	"testing"
+)
+
+func TestSendMsg(t *testing.T) {
+	//微信公众平台
+	mp, err := Client.MpClient()
+	if err != nil {
+		return
+	}
+
+	api := mp.GetTemplate()
+	tmplMsg := new(template.Message)
+	tmplMsg.URL = ""
+	tmplMsg.ToUser = "oZ2X-wbYWx-XbsHXl6aYo5zUezHo"
+	tmplMsg.TemplateID = "nD-R2NHxUTXdG91pSXQlva3XJj2M-KhB1V1njpc4Lrg"
+	tmplMsg.Data = makeMsgMessageData()
+	id, err := api.Send(tmplMsg)
+	if err != nil {
+		fmt.Println(err.Error())
+	}
+	fmt.Println(id)
+
+}
+func makeMsgMessageData() (data map[string]*template.DataItem) {
+	data = make(map[string]*template.DataItem)
+	data["first"] = &template.DataItem{Value: "小王发起了一个审批请求", Color: "#173177"}
+	data["keyword1"] = &template.DataItem{Value: "小王", Color: "#173177"}
+	data["keyword2"] = &template.DataItem{Value: "办公用品采购单", Color: "#173177"}
+	data["keyword3"] = &template.DataItem{Value: "D201728712294821", Color: "#173177"}
+	data["keyword4"] = &template.DataItem{Value: "2017-10-18 18:00", Color: "#173177"}
+	data["remark"] = &template.DataItem{Value: "麻烦周五之前审批", Color: "#2eb3ff"}
+	return
+}

+ 75 - 0
opms_libary/plugin/wechat/context/access_token.go

@@ -0,0 +1,75 @@
+package context
+
+import (
+	"encoding/json"
+	"fmt"
+	"github.com/gogf/gf/frame/g"
+	"sync"
+	"time"
+)
+
+const (
+	//AccessTokenURL 获取access_token的接口
+	AccessTokenURL = "https://api.weixin.qq.com/cgi-bin/token"
+)
+
+//ResAccessToken 结构体
+type ResAccessToken struct {
+	WxError
+
+	AccessToken string `json:"access_token"`
+	ExpiresIn   int64  `json:"expires_in"`
+}
+
+//SetAccessTokenLock 设置读写锁(一个appID一个读写锁)
+func (ctx *Context) SetAccessTokenLock(l *sync.RWMutex) {
+	ctx.accessTokenLock = l
+}
+
+//GetAccessToken 获取access_token
+func (ctx *Context) GetAccessToken() (accessToken string, err error) {
+	ctx.accessTokenLock.Lock()
+	defer ctx.accessTokenLock.Unlock()
+
+	accessTokenCacheKey := fmt.Sprintf("access_token_%s", ctx.AppID)
+	val, _ := ctx.Cache.Get(accessTokenCacheKey)
+	if val != nil {
+		accessToken = val.(string)
+		return
+	}
+
+	//从微信服务器获取
+	var resAccessToken ResAccessToken
+	resAccessToken, err = ctx.GetAccessTokenFromServer()
+	if err != nil {
+		return
+	}
+
+	accessToken = resAccessToken.AccessToken
+	return
+}
+
+//CleanAccessTokenCache clean cache
+func (ctx *Context) CleanAccessTokenCache() {
+	accessTokenCacheKey := fmt.Sprintf("access_token_%s", ctx.AppID)
+	ctx.Cache.Remove(accessTokenCacheKey)
+}
+
+//GetAccessTokenFromServer 强制从微信服务器获取token
+func (ctx *Context) GetAccessTokenFromServer() (resAccessToken ResAccessToken, err error) {
+	url := fmt.Sprintf("%s?grant_type=client_credential&appid=%s&secret=%s", AccessTokenURL, ctx.AppID, ctx.AppSecret)
+	body := g.Client().GetBytes(url)
+	err = json.Unmarshal(body, &resAccessToken)
+	if err != nil {
+		return
+	}
+	if resAccessToken.Msg != "" {
+		err = fmt.Errorf("get access_token error : errcode=%v , errormsg=%v", resAccessToken.Code, resAccessToken.Msg)
+		return
+	}
+
+	accessTokenCacheKey := fmt.Sprintf("access_token_%s", ctx.AppID)
+	expires := resAccessToken.ExpiresIn - 1500
+	err = ctx.Cache.Set(accessTokenCacheKey, resAccessToken.AccessToken, time.Duration(expires)*time.Second)
+	return
+}

+ 12 - 0
opms_libary/plugin/wechat/context/config.go

@@ -0,0 +1,12 @@
+package context
+
+import "github.com/gogf/gf/os/gcache"
+
+// Config for user
+type Config struct {
+	AppID          string
+	AppSecret      string
+	Token          string
+	EncodingAESKey string
+	Cache          *gcache.Cache
+}

+ 86 - 0
opms_libary/plugin/wechat/context/context.go

@@ -0,0 +1,86 @@
+package context
+
+import (
+	"encoding/xml"
+	"net/http"
+	"sync"
+)
+
+// Context struct
+type Context struct {
+	*Config
+
+	Writer  http.ResponseWriter
+	Request *http.Request
+
+	//accessTokenLock 读写锁 同一个AppID一个
+	accessTokenLock *sync.RWMutex
+
+	//jsAPITicket 读写锁 同一个AppID一个
+	jsAPITicketLock *sync.RWMutex
+
+	HTTPClient  *http.Client
+	SHTTPClient *http.Client //SSL client
+}
+
+// Query 返回键入的url查询值(如果存在)
+func (ctx *Context) Query(key string) string {
+	value, _ := ctx.GetQuery(key)
+	return value
+}
+
+// GetQuery 类似于Query(),它返回键入的url查询值
+func (ctx *Context) GetQuery(key string) (string, bool) {
+	req := ctx.Request
+	if values, ok := req.URL.Query()[key]; ok && len(values) > 0 {
+		return values[0], true
+	}
+	return "", false
+}
+
+// SetJsAPITicketLock 设置jsAPITicket的lock
+func (ctx *Context) SetJsAPITicketLock(lock *sync.RWMutex) {
+	ctx.jsAPITicketLock = lock
+}
+
+// GetJsAPITicketLock 获取jsAPITicket 的lock
+func (ctx *Context) GetJsAPITicketLock() *sync.RWMutex {
+	return ctx.jsAPITicketLock
+}
+
+var xmlContentType = []string{"application/xml; charset=utf-8"}
+var plainContentType = []string{"text/plain; charset=utf-8"}
+
+//Render render from bytes
+func (ctx *Context) Render(bytes []byte) {
+	//debug
+	// fmt.Println("response msg = ", string(bytes))
+	ctx.Writer.WriteHeader(200)
+	_, err := ctx.Writer.Write(bytes)
+	if err != nil {
+		panic(err)
+	}
+}
+
+//String render from string
+func (ctx *Context) String(str string) {
+	writeContextType(ctx.Writer, plainContentType)
+	ctx.Render([]byte(str))
+}
+
+//XML render to xml
+func (ctx *Context) XML(obj interface{}) {
+	writeContextType(ctx.Writer, xmlContentType)
+	bytes, err := xml.Marshal(obj)
+	if err != nil {
+		panic(err)
+	}
+	ctx.Render(bytes)
+}
+
+func writeContextType(w http.ResponseWriter, value []string) {
+	header := w.Header()
+	if val := header["Content-Type"]; len(val) == 0 {
+		header["Content-Type"] = value
+	}
+}

+ 183 - 0
opms_libary/plugin/wechat/context/crypto.go

@@ -0,0 +1,183 @@
+package context
+
+import (
+	"crypto/aes"
+	"crypto/cipher"
+	"encoding/base64"
+	"fmt"
+)
+
+//EncryptMsg 加密消息
+func EncryptMsg(random, rawXMLMsg []byte, appID, aesKey string) (encrtptMsg []byte, err error) {
+	defer func() {
+		if e := recover(); e != nil {
+			err = fmt.Errorf("panic error: err=%v", e)
+			return
+		}
+	}()
+	var key []byte
+	key, err = aesKeyDecode(aesKey)
+	if err != nil {
+		panic(err)
+	}
+	ciphertext := AESEncryptMsg(random, rawXMLMsg, appID, key)
+	encrtptMsg = []byte(base64.StdEncoding.EncodeToString(ciphertext))
+	return
+}
+
+//AESEncryptMsg ciphertext = AES_Encrypt[random(16B) + msg_len(4B) + rawXMLMsg + appId]
+//参考:github.com/chanxuehong/wechat.v2
+func AESEncryptMsg(random, rawXMLMsg []byte, appID string, aesKey []byte) (ciphertext []byte) {
+	const (
+		BlockSize = 32            // PKCS#7
+		BlockMask = BlockSize - 1 // BLOCK_SIZE 为 2^n 时, 可以用 mask 获取针对 BLOCK_SIZE 的余数
+	)
+
+	appIDOffset := 20 + len(rawXMLMsg)
+	contentLen := appIDOffset + len(appID)
+	amountToPad := BlockSize - contentLen&BlockMask
+	plaintextLen := contentLen + amountToPad
+
+	plaintext := make([]byte, plaintextLen)
+
+	// 拼接
+	copy(plaintext[:16], random)
+	encodeNetworkByteOrder(plaintext[16:20], uint32(len(rawXMLMsg)))
+	copy(plaintext[20:], rawXMLMsg)
+	copy(plaintext[appIDOffset:], appID)
+
+	// PKCS#7 补位
+	for i := contentLen; i < plaintextLen; i++ {
+		plaintext[i] = byte(amountToPad)
+	}
+
+	// 加密
+	block, err := aes.NewCipher(aesKey[:])
+	if err != nil {
+		panic(err)
+	}
+	mode := cipher.NewCBCEncrypter(block, aesKey[:16])
+	mode.CryptBlocks(plaintext, plaintext)
+
+	ciphertext = plaintext
+	return
+}
+
+//DecryptMsg 消息解密
+func DecryptMsg(appID, encryptedMsg, aesKey string) (random, rawMsgXMLBytes []byte, err error) {
+	defer func() {
+		if e := recover(); e != nil {
+			err = fmt.Errorf("panic error: err=%v", e)
+			return
+		}
+	}()
+	var encryptedMsgBytes, key, getAppIDBytes []byte
+	encryptedMsgBytes, err = base64.StdEncoding.DecodeString(encryptedMsg)
+	if err != nil {
+		return
+	}
+	key, err = aesKeyDecode(aesKey)
+	if err != nil {
+		panic(err)
+	}
+	random, rawMsgXMLBytes, getAppIDBytes, err = AESDecryptMsg(encryptedMsgBytes, key)
+	if err != nil {
+		err = fmt.Errorf("消息解密失败,%v", err)
+		return
+	}
+	if appID != string(getAppIDBytes) {
+		err = fmt.Errorf("消息解密校验APPID失败")
+		return
+	}
+	return
+}
+
+func aesKeyDecode(encodedAESKey string) (key []byte, err error) {
+	if len(encodedAESKey) != 43 {
+		err = fmt.Errorf("the length of encodedAESKey must be equal to 43")
+		return
+	}
+	key, err = base64.StdEncoding.DecodeString(encodedAESKey + "=")
+	if err != nil {
+		return
+	}
+	if len(key) != 32 {
+		err = fmt.Errorf("encodingAESKey invalid")
+		return
+	}
+	return
+}
+
+// AESDecryptMsg ciphertext = AES_Encrypt[random(16B) + msg_len(4B) + rawXMLMsg + appId]
+//参考:github.com/chanxuehong/wechat.v2
+func AESDecryptMsg(ciphertext []byte, aesKey []byte) (random, rawXMLMsg, appID []byte, err error) {
+	const (
+		BlockSize = 32            // PKCS#7
+		BlockMask = BlockSize - 1 // BLOCK_SIZE 为 2^n 时, 可以用 mask 获取针对 BLOCK_SIZE 的余数
+	)
+
+	if len(ciphertext) < BlockSize {
+		err = fmt.Errorf("the length of ciphertext too short: %d", len(ciphertext))
+		return
+	}
+	if len(ciphertext)&BlockMask != 0 {
+		err = fmt.Errorf("ciphertext is not a multiple of the block size, the length is %d", len(ciphertext))
+		return
+	}
+
+	plaintext := make([]byte, len(ciphertext)) // len(plaintext) >= BLOCK_SIZE
+
+	// 解密
+	block, err := aes.NewCipher(aesKey)
+	if err != nil {
+		panic(err)
+	}
+	mode := cipher.NewCBCDecrypter(block, aesKey[:16])
+	mode.CryptBlocks(plaintext, ciphertext)
+
+	// PKCS#7 去除补位
+	amountToPad := int(plaintext[len(plaintext)-1])
+	if amountToPad < 1 || amountToPad > BlockSize {
+		err = fmt.Errorf("the amount to pad is incorrect: %d", amountToPad)
+		return
+	}
+	plaintext = plaintext[:len(plaintext)-amountToPad]
+
+	// 反拼接
+	// len(plaintext) == 16+4+len(rawXMLMsg)+len(appId)
+	if len(plaintext) <= 20 {
+		err = fmt.Errorf("plaintext too short, the length is %d", len(plaintext))
+		return
+	}
+	rawXMLMsgLen := int(decodeNetworkByteOrder(plaintext[16:20]))
+	if rawXMLMsgLen < 0 {
+		err = fmt.Errorf("incorrect msg length: %d", rawXMLMsgLen)
+		return
+	}
+	appIDOffset := 20 + rawXMLMsgLen
+	if len(plaintext) <= appIDOffset {
+		err = fmt.Errorf("msg length too large: %d", rawXMLMsgLen)
+		return
+	}
+
+	random = plaintext[:16:20]
+	rawXMLMsg = plaintext[20:appIDOffset:appIDOffset]
+	appID = plaintext[appIDOffset:]
+	return
+}
+
+// 把整数 n 格式化成 4 字节的网络字节序
+func encodeNetworkByteOrder(orderBytes []byte, n uint32) {
+	orderBytes[0] = byte(n >> 24)
+	orderBytes[1] = byte(n >> 16)
+	orderBytes[2] = byte(n >> 8)
+	orderBytes[3] = byte(n)
+}
+
+// 从 4 字节的网络字节序里解析出整数
+func decodeNetworkByteOrder(orderBytes []byte) (n uint32) {
+	return uint32(orderBytes[0])<<24 |
+		uint32(orderBytes[1])<<16 |
+		uint32(orderBytes[2])<<8 |
+		uint32(orderBytes[3])
+}

+ 39 - 0
opms_libary/plugin/wechat/context/error.go

@@ -0,0 +1,39 @@
+package context
+
+import (
+	"encoding/json"
+	"errors"
+	"fmt"
+)
+
+//ErrUnmarshall err when unmarshall
+var ErrUnmarshall = errors.New("json Unmarshal Error")
+
+//WxError 微信返回的错误信息
+type WxError struct {
+	Code int64  `json:"errcode"`
+	Msg  string `json:"errmsg"`
+}
+
+//NewWxError new NewWxError
+func NewWxError(code int64, msg string) *WxError {
+	return &WxError{Code: code, Msg: msg}
+}
+
+func (e *WxError) Error() string {
+	return e.Msg
+}
+
+//CheckCommonError check CommonError
+func CheckCommonError(jsonData []byte) error {
+	var errmsg WxError
+	if err := json.Unmarshal(jsonData, &errmsg); err != nil {
+		return ErrUnmarshall
+	}
+
+	if errmsg.Code != 0 {
+		return fmt.Errorf("Error , errcode=%d , errmsg=%s", errmsg.Code, errmsg.Msg)
+	}
+
+	return nil
+}

+ 18 - 0
opms_libary/plugin/wechat/context/sign.go

@@ -0,0 +1,18 @@
+package context
+
+import (
+	"crypto/sha1"
+	"fmt"
+	"io"
+	"sort"
+)
+
+//Sign sha1签名
+func Sign(params ...string) string {
+	sort.Strings(params)
+	h := sha1.New()
+	for _, s := range params {
+		io.WriteString(h, s)
+	}
+	return fmt.Sprintf("%x", h.Sum(nil))
+}

+ 77 - 0
opms_libary/plugin/wechat/media.go

@@ -0,0 +1,77 @@
+package wechat
+
+import (
+	"dashoo.cn/opms_libary/plugin/wechat/mp/account"
+	"dashoo.cn/opms_libary/plugin/wechat/mp/bridge"
+	"dashoo.cn/opms_libary/plugin/wechat/mp/jssdk"
+	"dashoo.cn/opms_libary/plugin/wechat/mp/material"
+	"dashoo.cn/opms_libary/plugin/wechat/mp/menu"
+	"dashoo.cn/opms_libary/plugin/wechat/mp/oauth"
+	"dashoo.cn/opms_libary/plugin/wechat/mp/template"
+	"dashoo.cn/opms_libary/plugin/wechat/mp/user"
+
+	"net/http"
+)
+
+type Media struct {
+	*ClientImpl
+}
+
+func NewMedia() *Media {
+	return &Media{}
+}
+
+//GetAccessToken 获取access_token
+func (c *Media) GetAccessToken() (string, error) {
+	return c.Context.GetAccessToken()
+}
+
+// GetOauth oauth2网页授权
+func (c *Media) GetOauth() *oauth.Oauth {
+	return oauth.NewOauth(c.Context)
+}
+
+// GetMaterial 素材管理
+func (c *Media) GetMaterial() *material.Material {
+	return material.NewMaterial(c.Context)
+}
+
+// GetJs js-sdk配置
+func (c *Media) GetJs() *jssdk.Js {
+	return jssdk.NewJs(c.Context)
+}
+
+// GetMenu 菜单管理接口
+func (c *Media) GetMenu() *menu.Menu {
+	return menu.NewMenu(c.Context)
+}
+
+// GetUser 用户管理接口
+func (c *Media) GetUser() *user.User {
+	return user.NewUser(c.Context)
+}
+
+// GetTemplate 模板消息接口
+func (c *Media) GetTemplate() *template.Template {
+	return template.NewTemplate(c.Context)
+}
+
+// GetMsgHandler 消息管理
+func (c *Media) GetMsgHandler(req *http.Request, writer http.ResponseWriter) *bridge.MsgHandler {
+	c.Context.Request = req
+	c.Context.Writer = writer
+	return bridge.NewMsgHandler(c.Context)
+}
+
+//GetPageOAuthHandler 网页授权
+func (c *Media) GetPageOAuthHandler(req *http.Request, writer http.ResponseWriter, myURLOfPageOAuthCallback string) *bridge.PageOAuthHandler {
+	c.Context.Request = req
+	c.Context.Writer = writer
+	handler := bridge.NewPageOAuthHandler(c.Context, myURLOfPageOAuthCallback)
+	return handler
+}
+
+// GetQrcode 带参数的二维码
+func (c *Media) GetQrcode() *account.Qrcode {
+	return account.NewQrcode(c.Context)
+}

+ 3 - 0
opms_libary/plugin/wechat/mp/README.md

@@ -0,0 +1,3 @@
+# 微信公众平台(订阅号,服务号) 
+
+[官方文档](https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1445241432)

+ 171 - 0
opms_libary/plugin/wechat/mp/account/qrcode.go

@@ -0,0 +1,171 @@
+package account
+
+import (
+	"dashoo.cn/opms_libary/plugin/wechat/context"
+	"dashoo.cn/opms_libary/plugin/wechat/mp/base"
+
+	"encoding/json"
+	"errors"
+	"fmt"
+	"net/url"
+)
+
+const (
+	qrcodeURL      = "https://api.weixin.qq.com/cgi-bin/qrcode/create"
+	ticketToImgURL = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=%s"
+)
+
+//Qrcode 带参数的二维码
+type Qrcode struct {
+	base.MpBase
+}
+
+//NewQrcode 实例化
+func NewQrcode(context *context.Context) *Qrcode {
+	qrcode := new(Qrcode)
+	qrcode.Context = context
+	return qrcode
+}
+
+const (
+	//TemporaryQRCodeExpireSecondsLimit 临时二维码 expire_seconds 限制
+	TemporaryQRCodeExpireSecondsLimit = 2592000
+	//PermanentQRCodeSceneIDLimit 永久二维码 scene_id 限制
+	PermanentQRCodeSceneIDLimit = 100000
+)
+
+//QrcodeResult Qrcode Result
+type QrcodeResult struct {
+	Ticket        string `json:"ticket"`                   // 获取的二维码ticket, 凭借此ticket可以在有效时间内换取二维码.
+	URL           string `json:"url"`                      // 二维码图片解析后的地址, 开发者可根据该地址自行生成需要的二维码图片
+	ExpireSeconds int    `json:"expire_seconds,omitempty"` // 二维码的有效时间, 以秒为单位. 最大不超过 604800.
+}
+
+//ImageURL ticket 换取二维码图片
+func (c *QrcodeResult) ImageURL() (imgURL string) {
+	return fmt.Sprintf(ticketToImgURL, url.QueryEscape(c.Ticket))
+}
+
+//CreateTemporaryQRCode  创建临时二维码
+//  SceneId:       场景值ID, 为32位非0整型
+//  ExpireSeconds: 二维码有效时间, 以秒为单位.  最大不超过 604800.
+func (c *Qrcode) CreateTemporaryQRCode(SceneID uint32, ExpireSeconds int) (result *QrcodeResult, err error) {
+	if SceneID == 0 {
+		err = errors.New("SceneId should be greater than 0")
+		return
+	}
+	if ExpireSeconds <= 0 {
+		err = errors.New("ExpireSeconds should be greater than 0")
+		return
+	}
+	var request struct {
+		ExpireSeconds int    `json:"expire_seconds"`
+		ActionName    string `json:"action_name"`
+		ActionInfo    struct {
+			Scene struct {
+				SceneID uint32 `json:"scene_id"`
+			} `json:"scene"`
+		} `json:"action_info"`
+	}
+	request.ExpireSeconds = ExpireSeconds
+	request.ActionName = "QR_SCENE"
+	request.ActionInfo.Scene.SceneID = SceneID
+
+	result = new(QrcodeResult)
+
+	response, err := c.HTTPPostJSONWithAccessToken(qrcodeURL, &request)
+	if err != nil {
+		return nil, err
+	}
+	err = json.Unmarshal(response, result)
+	return
+}
+
+//CreateTemporaryQRCodeWithSceneString 创建临时二维码 scene_str
+func (c *Qrcode) CreateTemporaryQRCodeWithSceneString(SceneString string, ExpireSeconds int) (result *QrcodeResult, err error) {
+	if SceneString == "" {
+		err = errors.New("SceneString should not be empty")
+		return
+	}
+	if ExpireSeconds <= 0 {
+		err = errors.New("ExpireSeconds should be greater than 0")
+		return
+	}
+	var request struct {
+		ExpireSeconds int    `json:"expire_seconds"`
+		ActionName    string `json:"action_name"`
+		ActionInfo    struct {
+			Scene struct {
+				SceneString string `json:"scene_str"`
+			} `json:"scene"`
+		} `json:"action_info"`
+	}
+	request.ExpireSeconds = ExpireSeconds
+	request.ActionName = "QR_STR_SCENE"
+	request.ActionInfo.Scene.SceneString = SceneString
+
+	result = new(QrcodeResult)
+
+	response, err := c.HTTPPostJSONWithAccessToken(qrcodeURL, &request)
+	if err != nil {
+		return nil, err
+	}
+	err = json.Unmarshal(response, result)
+	return
+}
+
+//CreatePermanentQRCode 创建永久二维码
+//  SceneId: 场景值ID, 目前参数只支持1--100000
+func (c *Qrcode) CreatePermanentQRCode(sceneID uint32) (result *QrcodeResult, err error) {
+	if sceneID == 0 {
+		err = errors.New("SceneId should be greater than 0")
+		return
+	}
+	var request struct {
+		ActionName string `json:"action_name"`
+		ActionInfo struct {
+			Scene struct {
+				SceneID uint32 `json:"scene_id"`
+			} `json:"scene"`
+		} `json:"action_info"`
+	}
+	request.ActionName = "QR_LIMIT_SCENE"
+	request.ActionInfo.Scene.SceneID = sceneID
+
+	result = new(QrcodeResult)
+
+	response, err := c.HTTPPostJSONWithAccessToken(qrcodeURL, &request)
+	if err != nil {
+		return nil, err
+	}
+	err = json.Unmarshal(response, result)
+	return
+}
+
+//CreatePermanentQRCodeWithSceneString 创建永久二维码
+//  SceneString: 场景值ID(字符串形式的ID), 字符串类型, 长度限制为1到64
+func (c *Qrcode) CreatePermanentQRCodeWithSceneString(SceneString string) (result *QrcodeResult, err error) {
+	if SceneString == "" {
+		err = errors.New("SceneString should not be empty")
+		return
+	}
+	var request struct {
+		ActionName string `json:"action_name"`
+		ActionInfo struct {
+			Scene struct {
+				SceneString string `json:"scene_str"`
+			} `json:"scene"`
+		} `json:"action_info"`
+	}
+	request.ActionName = "QR_LIMIT_STR_SCENE"
+	request.ActionInfo.Scene.SceneString = SceneString
+
+	result = new(QrcodeResult)
+
+	response, err := c.HTTPPostJSONWithAccessToken(qrcodeURL, &request)
+	if err != nil {
+		return nil, err
+	}
+	err = json.Unmarshal(response, result)
+	return
+}

+ 87 - 0
opms_libary/plugin/wechat/mp/base/base.go

@@ -0,0 +1,87 @@
+package base
+
+import (
+	"dashoo.cn/opms_libary/plugin/wechat/context"
+	"fmt"
+	"github.com/gogf/gf/frame/g"
+	"io/ioutil"
+	"strings"
+)
+
+//MpBase 微信公众平台,基本类
+type MpBase struct {
+	*context.Context
+}
+
+//HTTPGetWithAccessToken 微信公众平台中,自动加上access_token变量的GET调用,
+//如果失败,会清空AccessToken cache, 再试一次
+func (c *MpBase) HTTPGetWithAccessToken(url string) (resp []byte, err error) {
+	retry := 1
+Do:
+	var accessToken string
+	accessToken, err = c.GetAccessToken()
+	if err != nil {
+		return
+	}
+
+	var target = ""
+	if strings.Contains(url, "?") {
+		target = fmt.Sprintf("%s&access_token=%s", url, accessToken)
+	} else {
+		target = fmt.Sprintf("%s?access_token=%s", url, accessToken)
+	}
+	response, err := g.Client().Get(target)
+	if err != nil {
+		return
+	}
+	defer response.Body.Close()
+
+	resp, err = ioutil.ReadAll(response.Body)
+	err = context.CheckCommonError(resp)
+	if err == context.ErrUnmarshall {
+		return
+	}
+	if err != nil {
+		if retry > 0 {
+			retry--
+			c.CleanAccessTokenCache()
+			goto Do
+		}
+		return
+	}
+	return
+}
+
+//HTTPPostJSONWithAccessToken post json 自动加上access token, 并retry
+func (c *MpBase) HTTPPostJSONWithAccessToken(url string, obj interface{}) (resp []byte, err error) {
+	retry := 1
+Do:
+	var accessToken string
+	accessToken, err = c.GetAccessToken()
+	if err != nil {
+		return
+	}
+
+	var target = ""
+	if strings.Contains(url, "?") {
+		target = fmt.Sprintf("%s&access_token=%s", url, accessToken)
+	} else {
+		target = fmt.Sprintf("%s?access_token=%s", url, accessToken)
+	}
+
+	resp = g.Client().ContentJson().PostBytes(target, obj)
+
+	err = context.CheckCommonError(resp)
+	if err == context.ErrUnmarshall {
+		return
+	}
+	if err != nil {
+		if retry > 0 {
+			retry--
+			c.CleanAccessTokenCache()
+			goto Do
+		}
+		return
+	}
+	return
+}

+ 0 - 0
opms_libary/plugin/wechat/mp/bridge/README.md


+ 235 - 0
opms_libary/plugin/wechat/mp/bridge/msg_handler.go

@@ -0,0 +1,235 @@
+package bridge
+
+import (
+	"dashoo.cn/opms_libary/plugin/wechat/context"
+	"dashoo.cn/opms_libary/plugin/wechat/mp/message"
+	"encoding/xml"
+	"errors"
+	"fmt"
+	"github.com/gogf/gf/os/gtime"
+	"io/ioutil"
+	"reflect"
+	"runtime/debug"
+	"strconv"
+	"strings"
+)
+
+//MsgHandler struct
+type MsgHandler struct {
+	*context.Context
+
+	handleMessageFunc func(message.MixMessage) *message.Reply
+
+	requestRawXMLMsg  []byte
+	requestMsg        message.MixMessage
+	responseRawXMLMsg []byte
+	responseMsg       interface{}
+
+	isSafeMode bool
+	random     []byte
+	nonce      string
+	timestamp  int64
+}
+
+//NewMsgHandler init
+func NewMsgHandler(context *context.Context) *MsgHandler {
+	srv := new(MsgHandler)
+	fmt.Println("NewMsgHandler:", srv)
+	srv.Context = context
+	return srv
+}
+
+//Handle 处理微信的请求消息
+func (srv *MsgHandler) Handle() error {
+	//Request is GET
+	//微信公众平台,设置服务器后保存,会调用此方法来做验证
+	if strings.ToLower(srv.Context.Request.Method) == "get" {
+		if !srv.Validate() {
+			return fmt.Errorf("请求校验失败")
+		}
+
+		echostr, exists := srv.GetQuery("echostr")
+		if exists {
+			srv.String(echostr) //微信公众平台需要将此值发送回去,来完成验证
+		}
+		return nil
+	}
+
+	//Request is POST
+	//微信公众平台将消息post到服务器上
+	if strings.ToLower(srv.Context.Request.Method) == "post" {
+		replyMsg, err := srv.handleRequest()
+		if err != nil {
+			return err
+		}
+		//debug
+		// fmt.Println("request msg = ", string(srv.requestRawXMLMsg))
+		err = srv.buildResponse(replyMsg)
+		if err == nil {
+			srv.Send()
+		} else {
+			return err
+		}
+	}
+	return nil
+}
+
+//Validate 校验请求是否合法
+func (srv *MsgHandler) Validate() bool {
+	timestamp := srv.Query("timestamp")
+	nonce := srv.Query("nonce")
+	signature := srv.Query("signature")
+	return signature == context.Sign(srv.Token, timestamp, nonce)
+}
+
+//HandleRequest 处理微信的请求
+func (srv *MsgHandler) handleRequest() (reply *message.Reply, err error) {
+	//set isSafeMode
+	srv.isSafeMode = false
+	encryptType := srv.Query("encrypt_type")
+	if encryptType == "aes" {
+		srv.isSafeMode = true
+	}
+
+	var msg interface{}
+	msg, err = srv.getMessage()
+	if err != nil {
+		return
+	}
+	mixMessage, success := msg.(message.MixMessage)
+	if !success {
+		err = errors.New("消息类型转换失败")
+	}
+	srv.requestMsg = mixMessage
+	reply = srv.handleMessageFunc(mixMessage)
+	return
+}
+
+//getMessage 解析微信返回的消息
+func (srv *MsgHandler) getMessage() (interface{}, error) {
+	var rawXMLMsgBytes []byte
+	var err error
+	if srv.isSafeMode {
+		var encryptedXMLMsg message.EncryptedXMLMsg
+		if err := xml.NewDecoder(srv.Request.Body).Decode(&encryptedXMLMsg); err != nil {
+			return nil, fmt.Errorf("从body中解析xml失败,err=%v", err)
+		}
+
+		//验证消息签名
+		timestamp := srv.Query("timestamp")
+		srv.timestamp, err = strconv.ParseInt(timestamp, 10, 32)
+		if err != nil {
+			return nil, err
+		}
+		nonce := srv.Query("nonce")
+		srv.nonce = nonce
+		msgSignature := srv.Query("msg_signature")
+		msgSignatureGen := context.Sign(srv.Token, timestamp, nonce, encryptedXMLMsg.EncryptedMsg)
+		if msgSignature != msgSignatureGen {
+			return nil, fmt.Errorf("消息不合法,验证签名失败")
+		}
+
+		//解密
+		srv.random, rawXMLMsgBytes, err = context.DecryptMsg(srv.AppID, encryptedXMLMsg.EncryptedMsg, srv.EncodingAESKey)
+		if err != nil {
+			return nil, fmt.Errorf("消息解密失败, err=%v", err)
+		}
+	} else {
+		rawXMLMsgBytes, err = ioutil.ReadAll(srv.Request.Body)
+		if err != nil {
+			return nil, fmt.Errorf("从body中解析xml失败, err=%v", err)
+		}
+	}
+
+	srv.requestRawXMLMsg = rawXMLMsgBytes
+
+	return srv.parseRequestMessage(rawXMLMsgBytes)
+}
+
+func (srv *MsgHandler) parseRequestMessage(rawXMLMsgBytes []byte) (msg message.MixMessage, err error) {
+	msg = message.MixMessage{}
+	err = xml.Unmarshal(rawXMLMsgBytes, &msg)
+	return
+}
+
+//SetHandleMessageFunc 设置用户自定义的回调方法
+func (srv *MsgHandler) SetHandleMessageFunc(handler func(message.MixMessage) *message.Reply) {
+	srv.handleMessageFunc = handler
+}
+
+func (srv *MsgHandler) buildResponse(reply *message.Reply) (err error) {
+	defer func() {
+		if e := recover(); e != nil {
+			err = fmt.Errorf("panic error: %v\n%s", e, debug.Stack())
+		}
+	}()
+	if reply == nil {
+		//do nothing
+		return nil
+	}
+	msgType := reply.MsgType
+	switch msgType {
+	case message.MsgTypeText:
+	case message.MsgTypeImage:
+	case message.MsgTypeVoice:
+	case message.MsgTypeVideo:
+	case message.MsgTypeMusic:
+	case message.MsgTypeNews:
+	case message.MsgTypeTransfer:
+	default:
+		err = message.ErrUnsupportReply
+		return
+	}
+
+	msgData := reply.MsgData
+	value := reflect.ValueOf(msgData)
+	//msgData must be a ptr
+	kind := value.Kind().String()
+	if "ptr" != kind {
+		return message.ErrUnsupportReply
+	}
+
+	params := make([]reflect.Value, 1)
+	params[0] = reflect.ValueOf(srv.requestMsg.FromUserName)
+	value.MethodByName("SetToUserName").Call(params)
+
+	params[0] = reflect.ValueOf(srv.requestMsg.ToUserName)
+	value.MethodByName("SetFromUserName").Call(params)
+
+	params[0] = reflect.ValueOf(msgType)
+	value.MethodByName("SetMsgType").Call(params)
+
+	params[0] = reflect.ValueOf(gtime.Now().Unix())
+	value.MethodByName("SetCreateTime").Call(params)
+
+	srv.responseMsg = msgData
+	srv.responseRawXMLMsg, err = xml.Marshal(msgData)
+	return
+}
+
+//Send 将自定义的消息发送
+func (srv *MsgHandler) Send() (err error) {
+	replyMsg := srv.responseMsg
+	if srv.isSafeMode {
+		//安全模式下对消息进行加密
+		var encryptedMsg []byte
+		encryptedMsg, err = context.EncryptMsg(srv.random, srv.responseRawXMLMsg, srv.AppID, srv.EncodingAESKey)
+		if err != nil {
+			return
+		}
+		//TODO 如果获取不到timestamp nonce 则自己生成
+		timestamp := srv.timestamp
+		timestampStr := strconv.FormatInt(timestamp, 10)
+		msgSignature := context.Sign(srv.Token, timestampStr, srv.nonce, string(encryptedMsg))
+		replyMsg = message.ResponseEncryptedXMLMsg{
+			EncryptedMsg: string(encryptedMsg),
+			MsgSignature: msgSignature,
+			Timestamp:    timestamp,
+			Nonce:        srv.nonce,
+		}
+	}
+	if replyMsg != nil {
+		srv.XML(replyMsg)
+	}
+	return
+}

+ 108 - 0
opms_libary/plugin/wechat/mp/bridge/page_auth_handler.go

@@ -0,0 +1,108 @@
+package bridge
+
+import (
+	"dashoo.cn/opms_libary/plugin/wechat/context"
+	"dashoo.cn/opms_libary/plugin/wechat/mp/oauth"
+	"dashoo.cn/opms_libary/plugin/wechat/mp/user"
+	"fmt"
+	"net/http"
+	"net/url"
+)
+
+//PageOAuthHandler 微信网页授权
+type PageOAuthHandler struct {
+	// *wxcontext.Context
+	*oauth.Oauth
+
+	myURLOfPageOAuthCallback string
+	myURLNeedPageOAuth       string
+
+	openID                  string
+	openIDExisting          bool
+	checkOpenIDExistingFunc func(openID string) (existing bool, stopNow bool)
+
+	user.Info
+	afterGetUserInfoFunc func(user user.Info) (stopNow bool)
+}
+
+//NewPageOAuthHandler PageOAuthHandler初始化
+func NewPageOAuthHandler(context *context.Context, myURLOfPageOAuthCallback string) *PageOAuthHandler {
+	pa := new(PageOAuthHandler)
+	pa.Oauth = oauth.NewOauth(context)
+	pa.myURLOfPageOAuthCallback = myURLOfPageOAuthCallback
+	return pa
+}
+
+func (c *PageOAuthHandler) getCallbackURL() (u string) {
+	return fmt.Sprintf("%s?target=%s", c.myURLOfPageOAuthCallback, url.QueryEscape(c.myURLNeedPageOAuth))
+}
+
+/*SetFuncCheckOpenIDExisting 设置检查OpenID在您的系统中是否已经存在
+
+handler:
+
+	func(openID string) (existing bool){
+		//用获得的openID,检查是否在你的系统中已经存在此用户
+		//如果存在,调用你的Login方法,设置cookie, session等,然后return true
+
+		//如果你的系统中不存在此openID用户, return false, handler会自动去获取用户信息
+	}
+
+*/
+func (c *PageOAuthHandler) SetFuncCheckOpenIDExisting(handler func(string) (existing bool, stopNow bool)) {
+	c.checkOpenIDExistingFunc = handler
+}
+
+/*SetFuncAfterGetUserInfo 设置获得用户信息后执行
+
+handler:
+
+	func(user oauth.UserInfo) (needStop bool) {
+		//handler已经获得了用户信息,你可以用此信息,自动为用户完成一些动作,比如注册,头像等
+
+		//默认needStop为false, 表示handler会自动redirect到你最开始需要授权的网页,此时你的系统已经完成了自动登陆等动作
+		//如果你需要redirect到你需要的url,直接调用http.redirect; return true。 表示需要停止后面的动作
+	}
+
+
+*/
+func (c *PageOAuthHandler) SetFuncAfterGetUserInfo(handler func(user.Info) bool) {
+	c.afterGetUserInfoFunc = handler
+}
+
+//Handle handler
+func (c *PageOAuthHandler) Handle() (err error) {
+	code := c.Query("code")
+	c.myURLNeedPageOAuth = c.Query("target")
+	if code != "" {
+		var acsTkn oauth.ResAccessToken
+		acsTkn, err = c.GetUserAccessToken(code)
+		if err != nil {
+			return
+		}
+		openID := acsTkn.OpenID
+		existing, stopNow := c.checkOpenIDExistingFunc(openID)
+		if stopNow {
+			return
+		}
+		if existing {
+			http.Redirect(c.Writer, c.Request, c.myURLNeedPageOAuth, 302)
+			return
+		}
+		//用 user模块的,没用oauth模板,可以获得更多信息
+		u, err := user.NewUser(c.Oauth.Context).GetUserInfo(openID)
+		if err != nil {
+			return err
+		}
+		stopNow = c.afterGetUserInfoFunc(*u)
+		if stopNow {
+			return nil
+		}
+		http.Redirect(c.Writer, c.Request, c.myURLNeedPageOAuth, 302)
+		return nil
+	} else {
+		//code为空时
+		c.Redirect(c.getCallbackURL(), "snsapi_base", "base")
+	}
+	return
+}

+ 120 - 0
opms_libary/plugin/wechat/mp/jssdk/jssdk.go

@@ -0,0 +1,120 @@
+package jssdk
+
+import (
+	"dashoo.cn/opms_libary/plugin/wechat/context"
+	"encoding/json"
+	"fmt"
+	"github.com/gogf/gf/frame/g"
+	"github.com/gogf/gf/os/gtime"
+	"github.com/gogf/gf/util/grand"
+	"time"
+)
+
+const getTicketURL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi"
+
+// Js struct
+type Js struct {
+	*context.Context
+}
+
+// Config 返回给用户jssdk配置信息
+type Config struct {
+	AppID     string `json:"app_id"`
+	Timestamp int64  `json:"timestamp"`
+	NonceStr  string `json:"nonce_str"`
+	Signature string `json:"signature"`
+}
+
+//ToMap wx.config中的配置
+func (c *Config) ToMap() (cfg map[string]interface{}) {
+	cfg = make(map[string]interface{})
+	cfg["appId"] = c.AppID
+	cfg["timestamp"] = c.Timestamp
+	cfg["nonceStr"] = c.NonceStr
+	cfg["signature"] = c.Signature
+	return
+}
+
+// resTicket 请求jsapi_tikcet返回结果
+type resTicket struct {
+	context.WxError
+
+	Ticket    string `json:"ticket"`
+	ExpiresIn int64  `json:"expires_in"`
+}
+
+//NewJs init
+func NewJs(context *context.Context) *Js {
+	js := new(Js)
+	js.Context = context
+	return js
+}
+
+//GetConfig 获取jssdk需要的配置参数
+//uri 为当前网页地址
+func (js *Js) GetConfig(url string) (config *Config, err error) {
+	config = new(Config)
+	var ticketStr string
+	ticketStr, err = js.GetTicket()
+	if err != nil {
+		return
+	}
+
+	nonceStr := grand.S(16, false)
+	timestamp := gtime.Now().Unix()
+	str := fmt.Sprintf("jsapi_ticket=%s&noncestr=%s&timestamp=%d&url=%s", ticketStr, nonceStr, timestamp, url)
+	sigStr := context.Sign(str)
+
+	config.AppID = js.AppID
+	config.NonceStr = nonceStr
+	config.Timestamp = timestamp
+	config.Signature = sigStr
+	return
+}
+
+//GetTicket 获取jsapi_tocket
+func (js *Js) GetTicket() (ticketStr string, err error) {
+	js.GetJsAPITicketLock().Lock()
+	defer js.GetJsAPITicketLock().Unlock()
+
+	//先从cache中取
+	jsAPITicketCacheKey := fmt.Sprintf("jsapi_ticket_%s", js.AppID)
+	val, _ := js.Cache.Get(jsAPITicketCacheKey)
+	if val != nil {
+		ticketStr = val.(string)
+		return
+	}
+	var ticket resTicket
+	ticket, err = js.getTicketFromServer()
+	if err != nil {
+		return
+	}
+	ticketStr = ticket.Ticket
+	return
+}
+
+//getTicketFromServer 强制从服务器中获取ticket
+func (js *Js) getTicketFromServer() (ticket resTicket, err error) {
+	var accessToken string
+	accessToken, err = js.GetAccessToken()
+	if err != nil {
+		return
+	}
+
+	var response []byte
+	url := fmt.Sprintf(getTicketURL, accessToken)
+	response = g.Client().GetBytes(url)
+	err = json.Unmarshal(response, &ticket)
+	if err != nil {
+		return
+	}
+	if ticket.Code != 0 {
+		err = fmt.Errorf("getTicket Error : errcode=%d , errmsg=%s", ticket.Code, ticket.Msg)
+		return
+	}
+
+	jsAPITicketCacheKey := fmt.Sprintf("jsapi_ticket_%s", js.AppID)
+	expires := ticket.ExpiresIn - 1500
+	err = js.Cache.Set(jsAPITicketCacheKey, ticket.Ticket, time.Duration(expires)*time.Second)
+	return
+}

+ 178 - 0
opms_libary/plugin/wechat/mp/material/material.go

@@ -0,0 +1,178 @@
+package material
+
+import (
+	"dashoo.cn/opms_libary/plugin/wechat/context"
+	"dashoo.cn/opms_libary/plugin/wechat/mp/base"
+	"encoding/json"
+)
+
+const (
+	addNewsURL     = "https://api.weixin.qq.com/cgi-bin/material/add_news"
+	addMaterialURL = "https://api.weixin.qq.com/cgi-bin/material/add_material"
+	delMaterialURL = "https://api.weixin.qq.com/cgi-bin/material/del_material"
+)
+
+//Material 素材管理
+type Material struct {
+	base.MpBase
+}
+
+//NewMaterial init
+func NewMaterial(context *context.Context) *Material {
+	material := new(Material)
+	material.Context = context
+	return material
+}
+
+//Article 永久图文素材
+type Article struct {
+	Title            string `json:"title"`
+	ThumbMediaID     string `json:"thumb_media_id"`
+	Author           string `json:"author"`
+	Digest           string `json:"digest"`
+	ShowCoverPic     int    `json:"show_cover_pic"`
+	Content          string `json:"content"`
+	ContentSourceURL string `json:"content_source_url"`
+}
+
+//reqArticles 永久性图文素材请求信息
+type reqArticles struct {
+	Articles []*Article `json:"articles"`
+}
+
+//resArticles 永久性图文素材返回结果
+type resArticles struct {
+	context.WxError
+
+	MediaID string `json:"media_id"`
+}
+
+//AddNews 新增永久图文素材
+func (material *Material) AddNews(articles []*Article) (mediaID string, err error) {
+	req := &reqArticles{articles}
+
+	responseBytes, err := material.HTTPPostJSONWithAccessToken(addNewsURL, req)
+	if err != nil {
+		return
+	}
+
+	var res resArticles
+	err = json.Unmarshal(responseBytes, res)
+	if err != nil {
+		return
+	}
+	mediaID = res.MediaID
+	return
+}
+
+//resAddMaterial 永久性素材上传返回的结果
+type resAddMaterial struct {
+	context.WxError
+
+	MediaID string `json:"media_id"`
+	URL     string `json:"url"`
+}
+
+//AddMaterial 上传永久性素材(处理视频需要单独上传)
+func (material *Material) AddMaterial(mediaType MediaType, filename string) (mediaID string, url string, err error) {
+	//if mediaType == MediaTypeVideo {
+	//	err = errors.New("永久视频素材上传使用 AddVideo 方法")
+	//}
+	//var accessToken string
+	//accessToken, err = material.GetAccessToken()
+	//if err != nil {
+	//	return
+	//}
+	//
+	//uri := fmt.Sprintf("%s?access_token=%s&type=%s", addMaterialURL, accessToken, mediaType)
+	//var response []byte
+	//response, err = util.PostFile("media", filename, uri)
+	//if err != nil {
+	//	return
+	//}
+	//var resMaterial resAddMaterial
+	//err = json.Unmarshal(response, &resMaterial)
+	//if err != nil {
+	//	return
+	//}
+	//if resMaterial.Code != 0 {
+	//	err = fmt.Errorf("AddMaterial error : errcode=%v , errmsg=%v", resMaterial.Code, resMaterial.Msg)
+	//	return
+	//}
+	//mediaID = resMaterial.MediaID
+	//url = resMaterial.URL
+	return
+}
+
+type reqVideo struct {
+	Title        string `json:"title"`
+	Introduction string `json:"introduction"`
+}
+
+//AddVideo 永久视频素材文件上传
+func (material *Material) AddVideo(filename, title, introduction string) (mediaID string, url string, err error) {
+	//var accessToken string
+	//accessToken, err = material.GetAccessToken()
+	//if err != nil {
+	//	return
+	//}
+	//
+	//uri := fmt.Sprintf("%s?access_token=%s&type=video", addMaterialURL, accessToken)
+	//
+	//videoDesc := &reqVideo{
+	//	Title:        title,
+	//	Introduction: introduction,
+	//}
+	//var fieldValue []byte
+	//fieldValue, err = json.Marshal(videoDesc)
+	//if err != nil {
+	//	return
+	//}
+	//
+	//fields := []util.MultipartFormField{
+	//	{
+	//		IsFile:    true,
+	//		Fieldname: "video",
+	//		Filename:  filename,
+	//	},
+	//	{
+	//		IsFile:    true,
+	//		Fieldname: "description",
+	//		Value:     fieldValue,
+	//	},
+	//}
+	//
+	//var response []byte
+	//response, err = util.PostMultipartForm(fields, uri)
+	//
+	//
+	//if err != nil {
+	//	return
+	//}
+	//
+	//var resMaterial resAddMaterial
+	//err = json.Unmarshal(response, &resMaterial)
+	//if err != nil {
+	//	return
+	//}
+	//if resMaterial.Code != 0 {
+	//	err = fmt.Errorf("AddMaterial error : errcode=%v , errmsg=%v", resMaterial.Code, resMaterial.Msg)
+	//	return
+	//}
+	//mediaID = resMaterial.MediaID
+	//url = resMaterial.URL
+	return
+}
+
+type reqDeleteMaterial struct {
+	MediaID string `json:"media_id"`
+}
+
+//DeleteMaterial 删除永久素材
+func (material *Material) DeleteMaterial(mediaID string) error {
+	_, err := material.HTTPPostJSONWithAccessToken(delMaterialURL, reqDeleteMaterial{mediaID})
+	if err != nil {
+		return err
+	}
+	return nil
+}

+ 112 - 0
opms_libary/plugin/wechat/mp/material/media.go

@@ -0,0 +1,112 @@
+package material
+
+import (
+	"dashoo.cn/opms_libary/plugin/wechat/context"
+	"encoding/json"
+	"fmt"
+	"github.com/gogf/gf/frame/g"
+)
+
+//MediaType 媒体文件类型
+type MediaType string
+
+const (
+	//MediaTypeImage 媒体文件:图片
+	MediaTypeImage MediaType = "image"
+	//MediaTypeVoice 媒体文件:声音
+	MediaTypeVoice = "voice"
+	//MediaTypeVideo 媒体文件:视频
+	MediaTypeVideo = "video"
+	//MediaTypeThumb 媒体文件:缩略图
+	MediaTypeThumb = "thumb"
+)
+
+const (
+	mediaUploadURL      = "https://api.weixin.qq.com/cgi-bin/media/upload"
+	mediaUploadImageURL = "https://api.weixin.qq.com/cgi-bin/media/uploadimg"
+	mediaGetURL         = "https://api.weixin.qq.com/cgi-bin/media/get"
+)
+
+//Media 临时素材上传返回信息
+type Media struct {
+	context.WxError
+
+	Type         MediaType `json:"type"`
+	MediaID      string    `json:"media_id"`
+	ThumbMediaID string    `json:"thumb_media_id"`
+	CreatedAt    int64     `json:"created_at"`
+}
+
+//MediaUpload 临时素材上传
+func (material *Material) MediaUpload(mediaType MediaType, filepath string) (media Media, err error) {
+	var accessToken string
+	accessToken, err = material.GetAccessToken()
+	if err != nil {
+		return
+	}
+
+	uri := fmt.Sprintf("%s?access_token=%s&type=%s", mediaUploadURL, accessToken, mediaType)
+
+	result, err := g.Client().Post(uri, "media=@file:"+filepath)
+
+	if err != nil {
+		return
+	}
+	defer result.Close()
+	err = json.Unmarshal(result.ReadAll(), &media)
+	if err != nil {
+		return
+	}
+	if media.Code != 0 {
+		err = fmt.Errorf("MediaUpload error : errcode=%v , errmsg=%v", media.Code, media.Msg)
+		return
+	}
+	return
+}
+
+//GetMediaURL 返回临时素材的下载地址供用户自己处理
+//NOTICE: URL 不可公开,因为含access_token 需要立即另存文件
+func (material *Material) GetMediaURL(mediaID string) (mediaURL string, err error) {
+	var accessToken string
+	accessToken, err = material.GetAccessToken()
+	if err != nil {
+		return
+	}
+	mediaURL = fmt.Sprintf("%s?access_token=%s&media_id=%s", mediaGetURL, accessToken, mediaID)
+	return
+}
+
+//resMediaImage 图片上传返回结果
+type resMediaImage struct {
+	context.WxError
+
+	URL string `json:"url"`
+}
+
+//ImageUpload 图片上传
+func (material *Material) ImageUpload(filepath string) (url string, err error) {
+	var accessToken string
+	accessToken, err = material.GetAccessToken()
+	if err != nil {
+		return
+	}
+
+	uri := fmt.Sprintf("%s?access_token=%s", mediaUploadImageURL, accessToken)
+	result, err := g.Client().Post(uri, "media=@file:"+filepath)
+	if err != nil {
+		return
+	}
+	var image resMediaImage
+	defer result.Close()
+	err = json.Unmarshal(result.ReadAll(), &image)
+	if err != nil {
+		return
+	}
+	if image.Code != 0 {
+		err = fmt.Errorf("UploadImage error : errcode=%v , errmsg=%v", image.Code, image.Msg)
+		return
+	}
+	url = image.URL
+	return
+
+}

+ 142 - 0
opms_libary/plugin/wechat/mp/menu/button.go

@@ -0,0 +1,142 @@
+package menu
+
+//Button 菜单按钮
+type Button struct {
+	Type       string    `json:"type,omitempty"`
+	Name       string    `json:"name,omitempty"`
+	Key        string    `json:"key,omitempty"`
+	URL        string    `json:"url,omitempty"`
+	MediaID    string    `json:"media_id,omitempty"`
+	AppID      string    `json:"appid,omitempty"`
+	PagePath   string    `json:"pagepath,omitempty"`
+	SubButtons []*Button `json:"sub_button,omitempty"`
+}
+
+//SetSubButton 设置二级菜单
+func (btn *Button) SetSubButton(name string, subButtons []*Button) {
+	btn.Name = name
+	btn.SubButtons = subButtons
+	btn.Type = ""
+	btn.Key = ""
+	btn.URL = ""
+	btn.MediaID = ""
+}
+
+//SetClickButton btn 为click类型
+func (btn *Button) SetClickButton(name, key string) {
+	btn.Type = "click"
+	btn.Name = name
+	btn.Key = key
+	btn.URL = ""
+	btn.MediaID = ""
+	btn.SubButtons = nil
+}
+
+//SetViewButton view类型
+func (btn *Button) SetViewButton(name, url string) {
+	btn.Type = "view"
+	btn.Name = name
+	btn.URL = url
+	btn.Key = ""
+	btn.MediaID = ""
+	btn.SubButtons = nil
+}
+
+// SetScanCodePushButton 扫码推事件
+func (btn *Button) SetScanCodePushButton(name, key string) {
+	btn.Type = "scancode_push"
+	btn.Name = name
+	btn.Key = key
+	btn.URL = ""
+	btn.MediaID = ""
+	btn.SubButtons = nil
+}
+
+//SetScanCodeWaitMsgButton 设置 扫码推事件且弹出"消息接收中"提示框
+func (btn *Button) SetScanCodeWaitMsgButton(name, key string) {
+	btn.Type = "scancode_waitmsg"
+	btn.Name = name
+	btn.Key = key
+
+	btn.URL = ""
+	btn.MediaID = ""
+	btn.SubButtons = nil
+}
+
+//SetPicSysPhotoButton 设置弹出系统拍照发图按钮
+func (btn *Button) SetPicSysPhotoButton(name, key string) {
+	btn.Type = "pic_sysphoto"
+	btn.Name = name
+	btn.Key = key
+
+	btn.URL = ""
+	btn.MediaID = ""
+	btn.SubButtons = nil
+}
+
+//SetPicPhotoOrAlbumButton 设置弹出拍照或者相册发图类型按钮
+func (btn *Button) SetPicPhotoOrAlbumButton(name, key string) {
+	btn.Type = "pic_photo_or_album"
+	btn.Name = name
+	btn.Key = key
+
+	btn.URL = ""
+	btn.MediaID = ""
+	btn.SubButtons = nil
+}
+
+// SetPicWeixinButton 设置弹出微信相册发图器类型按钮
+func (btn *Button) SetPicWeixinButton(name, key string) {
+	btn.Type = "pic_weixin"
+	btn.Name = name
+	btn.Key = key
+
+	btn.URL = ""
+	btn.MediaID = ""
+	btn.SubButtons = nil
+}
+
+// SetLocationSelectButton 设置 弹出地理位置选择器 类型按钮
+func (btn *Button) SetLocationSelectButton(name, key string) {
+	btn.Type = "location_select"
+	btn.Name = name
+	btn.Key = key
+
+	btn.URL = ""
+	btn.MediaID = ""
+	btn.SubButtons = nil
+}
+
+//SetMediaIDButton  设置 下发消息(除文本消息) 类型按钮
+func (btn *Button) SetMediaIDButton(name, mediaID string) {
+	btn.Type = "media_id"
+	btn.Name = name
+	btn.MediaID = mediaID
+
+	btn.Key = ""
+	btn.URL = ""
+	btn.SubButtons = nil
+}
+
+//SetViewLimitedButton  设置 跳转图文消息URL 类型按钮
+func (btn *Button) SetViewLimitedButton(name, mediaID string) {
+	btn.Type = "view_limited"
+	btn.Name = name
+	btn.MediaID = mediaID
+
+	btn.Key = ""
+	btn.URL = ""
+	btn.SubButtons = nil
+}
+
+//SetminiprogramButton  设置 跳转mini类型按钮
+func (btn *Button) SetMiniButton(name, url, appid, pagepath string) {
+	btn.Type = "miniprogram"
+	btn.Name = name
+	btn.URL = url
+	btn.AppID = appid
+	btn.PagePath = pagepath
+	btn.Key = ""
+	btn.MediaID = ""
+	btn.SubButtons = nil
+}

+ 199 - 0
opms_libary/plugin/wechat/mp/menu/menu.go

@@ -0,0 +1,199 @@
+package menu
+
+import (
+	"dashoo.cn/opms_libary/plugin/wechat/context"
+	"dashoo.cn/opms_libary/plugin/wechat/mp/base"
+	"encoding/json"
+)
+
+const (
+	menuCreateURL            = "https://api.weixin.qq.com/cgi-bin/menu/create"
+	menuGetURL               = "https://api.weixin.qq.com/cgi-bin/menu/get"
+	menuDeleteURL            = "https://api.weixin.qq.com/cgi-bin/menu/delete"
+	menuAddConditionalURL    = "https://api.weixin.qq.com/cgi-bin/menu/addconditional"
+	menuDeleteConditionalURL = "https://api.weixin.qq.com/cgi-bin/menu/delconditional"
+	menuTryMatchURL          = "https://api.weixin.qq.com/cgi-bin/menu/trymatch"
+	menuSelfMenuInfoURL      = "https://api.weixin.qq.com/cgi-bin/get_current_selfmenu_info"
+)
+
+//Menu struct
+type Menu struct {
+	base.MpBase
+}
+
+//reqMenu 设置菜单请求数据
+type reqMenu struct {
+	Button    []*Button  `json:"button,omitempty"`
+	MatchRule *MatchRule `json:"matchrule,omitempty"`
+}
+
+//reqDeleteConditional 删除个性化菜单请求数据
+type reqDeleteConditional struct {
+	MenuID int64 `json:"menuid"`
+}
+
+//reqMenuTryMatch 菜单匹配请求
+type reqMenuTryMatch struct {
+	UserID string `json:"user_id"`
+}
+
+//resConditionalMenu 个性化菜单返回结果
+type resConditionalMenu struct {
+	Button    []Button  `json:"button"`
+	MatchRule MatchRule `json:"matchrule"`
+	MenuID    int64     `json:"menuid"`
+}
+
+//resMenuTryMatch 菜单匹配请求结果
+type resMenuTryMatch struct {
+	context.WxError
+
+	Button []Button `json:"button"`
+}
+
+//ResMenu 查询菜单的返回数据
+type ResMenu struct {
+	context.WxError
+
+	Menu struct {
+		Button []Button `json:"button"`
+		MenuID int64    `json:"menuid"`
+	} `json:"menu"`
+	Conditionalmenu []resConditionalMenu `json:"conditionalmenu"`
+}
+
+//ResSelfMenuInfo 自定义菜单配置返回结果
+type ResSelfMenuInfo struct {
+	context.WxError
+
+	IsMenuOpen   int32 `json:"is_menu_open"`
+	SelfMenuInfo struct {
+		Button []SelfMenuButton `json:"button"`
+	} `json:"selfmenu_info"`
+}
+
+//SelfMenuButton 自定义菜单配置详情
+type SelfMenuButton struct {
+	Type      string `json:"type"`
+	Name      string `json:"name"`
+	Key       string `json:"key"`
+	URL       string `json:"url,omitempty"`
+	Value     string `json:"value,omitempty"`
+	SubButton struct {
+		List []SelfMenuButton `json:"list"`
+	} `json:"sub_button,omitempty"`
+	NewsInfo struct {
+		List []ButtonNew `json:"list"`
+	} `json:"news_info,omitempty"`
+}
+
+//ButtonNew 图文消息菜单
+type ButtonNew struct {
+	Title      string `json:"title"`
+	Author     string `json:"author"`
+	Digest     string `json:"digest"`
+	ShowCover  int32  `json:"show_cover"`
+	CoverURL   string `json:"cover_url"`
+	ContentURL string `json:"content_url"`
+	SourceURL  string `json:"source_url"`
+}
+
+//MatchRule 个性化菜单规则
+type MatchRule struct {
+	GroupID            int32  `json:"group_id,omitempty"`
+	Sex                int32  `json:"sex,omitempty"`
+	Country            string `json:"country,omitempty"`
+	Province           string `json:"province,omitempty"`
+	City               string `json:"city,omitempty"`
+	ClientPlatformType int32  `json:"client_platform_type,omitempty"`
+	Language           string `json:"language,omitempty"`
+}
+
+//NewMenu 实例
+func NewMenu(context *context.Context) *Menu {
+	menu := new(Menu)
+	menu.Context = context
+	return menu
+}
+
+//SetMenu 设置按钮
+func (menu *Menu) SetMenu(buttons []*Button) error {
+	reqMenu := &reqMenu{
+		Button: buttons,
+	}
+	_, err := menu.HTTPPostJSONWithAccessToken(menuCreateURL, reqMenu)
+	if err != nil {
+		return err
+	}
+	return nil
+}
+
+//GetMenu 获取菜单配置
+func (menu *Menu) GetMenu() (resMenu ResMenu, err error) {
+	var response []byte
+	response, err = menu.HTTPGetWithAccessToken(menuGetURL)
+	if err != nil {
+		return
+	}
+	err = json.Unmarshal(response, &resMenu)
+	return
+}
+
+//DeleteMenu 删除菜单
+func (menu *Menu) DeleteMenu() (err error) {
+	_, err = menu.HTTPGetWithAccessToken(menuDeleteURL)
+	return
+}
+
+//AddConditional 添加个性化菜单
+func (menu *Menu) AddConditional(buttons []*Button, matchRule *MatchRule) error {
+	reqMenu := &reqMenu{
+		Button:    buttons,
+		MatchRule: matchRule,
+	}
+	_, err := menu.HTTPPostJSONWithAccessToken(menuAddConditionalURL, reqMenu)
+	if err != nil {
+		return err
+	}
+	return nil
+}
+
+//DeleteConditional 删除个性化菜单
+func (menu *Menu) DeleteConditional(menuID int64) error {
+	reqDeleteConditional := &reqDeleteConditional{
+		MenuID: menuID,
+	}
+	_, err := menu.HTTPPostJSONWithAccessToken(menuDeleteConditionalURL, reqDeleteConditional)
+	if err != nil {
+		return err
+	}
+	return nil
+}
+
+//MenuTryMatch 菜单匹配
+func (menu *Menu) MenuTryMatch(userID string) (buttons []Button, err error) {
+	reqMenuTryMatch := &reqMenuTryMatch{userID}
+	var response []byte
+	response, err = menu.HTTPPostJSONWithAccessToken(menuTryMatchURL, reqMenuTryMatch)
+	if err != nil {
+		return
+	}
+	var resMenuTryMatch resMenuTryMatch
+	err = json.Unmarshal(response, &resMenuTryMatch)
+	if err != nil {
+		return
+	}
+	buttons = resMenuTryMatch.Button
+	return
+}
+
+//GetCurrentSelfMenuInfo 获取自定义菜单配置接口
+func (menu *Menu) GetCurrentSelfMenuInfo() (resSelfMenuInfo ResSelfMenuInfo, err error) {
+	var response []byte
+	response, err = menu.HTTPGetWithAccessToken(menuSelfMenuInfoURL)
+	if err != nil {
+		return
+	}
+	err = json.Unmarshal(response, &resSelfMenuInfo)
+	return
+}

+ 17 - 0
opms_libary/plugin/wechat/mp/message/image.go

@@ -0,0 +1,17 @@
+package message
+
+//Image 图片消息
+type Image struct {
+	CommonToken
+
+	Image struct {
+		MediaID string `xml:"MediaId"`
+	} `xml:"Image"`
+}
+
+//NewImage 回复图片消息
+func NewImage(mediaID string) *Image {
+	image := new(Image)
+	image.Image.MediaID = mediaID
+	return image
+}

+ 158 - 0
opms_libary/plugin/wechat/mp/message/message.go

@@ -0,0 +1,158 @@
+package message
+
+import "encoding/xml"
+
+// MsgType 基本消息类型
+type MsgType string
+
+// EventType 事件类型
+type EventType string
+
+const (
+	//MsgTypeText 表示文本消息
+	MsgTypeText MsgType = "text"
+	//MsgTypeImage 表示图片消息
+	MsgTypeImage = "image"
+	//MsgTypeVoice 表示语音消息
+	MsgTypeVoice = "voice"
+	//MsgTypeVideo 表示视频消息
+	MsgTypeVideo = "video"
+	//MsgTypeShortVideo 表示短视频消息[限接收]
+	MsgTypeShortVideo = "shortvideo"
+	//MsgTypeLocation 表示坐标消息[限接收]
+	MsgTypeLocation = "location"
+	//MsgTypeLink 表示链接消息[限接收]
+	MsgTypeLink = "link"
+	//MsgTypeMusic 表示音乐消息[限回复]
+	MsgTypeMusic = "music"
+	//MsgTypeNews 表示图文消息[限回复]
+	MsgTypeNews = "news"
+	//MsgTypeTransfer 表示消息消息转发到客服
+	MsgTypeTransfer = "transfer_customer_service"
+	//MsgTypeEvent 表示事件推送消息
+	MsgTypeEvent = "event"
+)
+
+const (
+	//EventSubscribe 订阅
+	EventSubscribe EventType = "subscribe"
+	//EventUnsubscribe 取消订阅
+	EventUnsubscribe = "unsubscribe"
+	//EventScan 用户已经关注公众号,则微信会将带场景值扫描事件推送给开发者
+	EventScan = "SCAN"
+	//EventLocation 上报地理位置事件
+	EventLocation = "LOCATION"
+	//EventClick 点击菜单拉取消息时的事件推送
+	EventClick = "CLICK"
+	//EventView 点击菜单跳转链接时的事件推送
+	EventView = "VIEW"
+	//EventScancodePush 扫码推事件的事件推送
+	EventScancodePush = "scancode_push"
+	//EventScancodeWaitmsg 扫码推事件且弹出“消息接收中”提示框的事件推送
+	EventScancodeWaitmsg = "scancode_waitmsg"
+	//EventPicSysphoto 弹出系统拍照发图的事件推送
+	EventPicSysphoto = "pic_sysphoto"
+	//EventPicPhotoOrAlbum 弹出拍照或者相册发图的事件推送
+	EventPicPhotoOrAlbum = "pic_photo_or_album"
+	//EventPicWeixin 弹出微信相册发图器的事件推送
+	EventPicWeixin = "pic_weixin"
+	//EventLocationSelect 弹出地理位置选择器的事件推送
+	EventLocationSelect = "location_select"
+)
+
+//MixMessage 存放所有微信发送过来的消息和事件
+type MixMessage struct {
+	CommonToken
+
+	//基本消息
+	MsgID        int64   `xml:"MsgId"`
+	Content      string  `xml:"Content"`
+	PicURL       string  `xml:"PicUrl"`
+	MediaID      string  `xml:"MediaId"`
+	Format       string  `xml:"Format"`
+	ThumbMediaID string  `xml:"ThumbMediaId"`
+	LocationX    float64 `xml:"Location_X"`
+	LocationY    float64 `xml:"Location_Y"`
+	Scale        float64 `xml:"Scale"`
+	Label        string  `xml:"Label"`
+	Title        string  `xml:"Title"`
+	Description  string  `xml:"Description"`
+	URL          string  `xml:"Url"`
+
+	//事件相关
+	Event     EventType `xml:"Event"`
+	EventKey  string    `xml:"EventKey"`
+	Ticket    string    `xml:"Ticket"`
+	Latitude  string    `xml:"Latitude"`
+	Longitude string    `xml:"Longitude"`
+	Precision string    `xml:"Precision"`
+	MenuID    string    `xml:"MenuId"`
+
+	ScanCodeInfo struct {
+		ScanType   string `xml:"ScanType"`
+		ScanResult string `xml:"ScanResult"`
+	} `xml:"ScanCodeInfo"`
+
+	SendPicsInfo struct {
+		Count   int32      `xml:"Count"`
+		PicList []EventPic `xml:"PicList>item"`
+	} `xml:"SendPicsInfo"`
+
+	SendLocationInfo struct {
+		LocationX float64 `xml:"Location_X"`
+		LocationY float64 `xml:"Location_Y"`
+		Scale     float64 `xml:"Scale"`
+		Label     string  `xml:"Label"`
+		Poiname   string  `xml:"Poiname"`
+	}
+}
+
+//EventPic 发图事件推送
+type EventPic struct {
+	PicMd5Sum string `xml:"PicMd5Sum"`
+}
+
+//EncryptedXMLMsg 安全模式下的消息体
+type EncryptedXMLMsg struct {
+	XMLName      struct{} `xml:"xml" json:"-"`
+	ToUserName   string   `xml:"ToUserName" json:"ToUserName"`
+	EncryptedMsg string   `xml:"Encrypt"    json:"Encrypt"`
+}
+
+//ResponseEncryptedXMLMsg 需要返回的消息体
+type ResponseEncryptedXMLMsg struct {
+	XMLName      struct{} `xml:"xml" json:"-"`
+	EncryptedMsg string   `xml:"Encrypt"      json:"Encrypt"`
+	MsgSignature string   `xml:"MsgSignature" json:"MsgSignature"`
+	Timestamp    int64    `xml:"TimeStamp"    json:"TimeStamp"`
+	Nonce        string   `xml:"Nonce"        json:"Nonce"`
+}
+
+// CommonToken 消息中通用的结构
+type CommonToken struct {
+	XMLName      xml.Name `xml:"xml"`
+	ToUserName   string   `xml:"ToUserName"`
+	FromUserName string   `xml:"FromUserName"`
+	CreateTime   int64    `xml:"CreateTime"`
+	MsgType      MsgType  `xml:"MsgType"`
+}
+
+//SetToUserName set ToUserName
+func (msg *CommonToken) SetToUserName(toUserName string) {
+	msg.ToUserName = toUserName
+}
+
+//SetFromUserName set FromUserName
+func (msg *CommonToken) SetFromUserName(fromUserName string) {
+	msg.FromUserName = fromUserName
+}
+
+//SetCreateTime set createTime
+func (msg *CommonToken) SetCreateTime(createTime int64) {
+	msg.CreateTime = createTime
+}
+
+//SetMsgType set MsgType
+func (msg *CommonToken) SetMsgType(msgType MsgType) {
+	msg.MsgType = msgType
+}

+ 24 - 0
opms_libary/plugin/wechat/mp/message/music.go

@@ -0,0 +1,24 @@
+package message
+
+//Music 音乐消息
+type Music struct {
+	CommonToken
+
+	Music struct {
+		Title        string `xml:"Title"        `
+		Description  string `xml:"Description"  `
+		MusicURL     string `xml:"MusicUrl"     `
+		HQMusicURL   string `xml:"HQMusicUrl"   `
+		ThumbMediaID string `xml:"ThumbMediaId"`
+	} `xml:"Music"`
+}
+
+//NewMusic  回复音乐消息
+func NewMusic(title, description, musicURL, hQMusicURL, thumbMediaID string) *Music {
+	music := new(Music)
+	music.Music.Title = title
+	music.Music.Description = description
+	music.Music.MusicURL = musicURL
+	music.Music.ThumbMediaID = thumbMediaID
+	return music
+}

+ 35 - 0
opms_libary/plugin/wechat/mp/message/news.go

@@ -0,0 +1,35 @@
+package message
+
+//News 图文消息
+type News struct {
+	CommonToken
+
+	ArticleCount int        `xml:"ArticleCount"`
+	Articles     []*Article `xml:"Articles>item,omitempty"`
+}
+
+//NewNews 初始化图文消息
+func NewNews(articles []*Article) *News {
+	news := new(News)
+	news.ArticleCount = len(articles)
+	news.Articles = articles
+	return news
+}
+
+//Article 单篇文章
+type Article struct {
+	Title       string `xml:"Title,omitempty"`
+	Description string `xml:"Description,omitempty"`
+	PicURL      string `xml:"PicUrl,omitempty"`
+	URL         string `xml:"Url,omitempty"`
+}
+
+//NewArticle 初始化文章
+func NewArticle(title, description, picURL, url string) *Article {
+	article := new(Article)
+	article.Title = title
+	article.Description = description
+	article.PicURL = picURL
+	article.URL = url
+	return article
+}

+ 24 - 0
opms_libary/plugin/wechat/mp/message/ransfer_customer.go

@@ -0,0 +1,24 @@
+package message
+
+//TransferCustomer 转发客服消息
+type TransferCustomer struct {
+	CommonToken
+
+	TransInfo *TransInfo `xml:"TransInfo,omitempty"`
+}
+
+//TransInfo 转发到指定客服
+type TransInfo struct {
+	KfAccount string `xml:"KfAccount"`
+}
+
+//NewTransferCustomer 实例化
+func NewTransferCustomer(KfAccount string) *TransferCustomer {
+	tc := new(TransferCustomer)
+	if KfAccount != "" {
+		transInfo := new(TransInfo)
+		transInfo.KfAccount = KfAccount
+		tc.TransInfo = transInfo
+	}
+	return tc
+}

+ 15 - 0
opms_libary/plugin/wechat/mp/message/reply.go

@@ -0,0 +1,15 @@
+package message
+
+import "errors"
+
+//ErrInvalidReply 无效的回复
+var ErrInvalidReply = errors.New("无效的回复消息")
+
+//ErrUnsupportReply 不支持的回复类型
+var ErrUnsupportReply = errors.New("不支持的回复消息")
+
+//Reply 消息回复
+type Reply struct {
+	MsgType MsgType
+	MsgData interface{}
+}

+ 14 - 0
opms_libary/plugin/wechat/mp/message/text.go

@@ -0,0 +1,14 @@
+package message
+
+//Text 文本消息
+type Text struct {
+	CommonToken
+	Content string `xml:"Content"`
+}
+
+//NewText 初始化文本消息
+func NewText(content string) *Text {
+	text := new(Text)
+	text.Content = content
+	return text
+}

+ 21 - 0
opms_libary/plugin/wechat/mp/message/video.go

@@ -0,0 +1,21 @@
+package message
+
+//Video 视频消息
+type Video struct {
+	CommonToken
+
+	Video struct {
+		MediaID     string `xml:"MediaId"`
+		Title       string `xml:"Title,omitempty"`
+		Description string `xml:"Description,omitempty"`
+	} `xml:"Video"`
+}
+
+//NewVideo 回复图片消息
+func NewVideo(mediaID, title, description string) *Video {
+	video := new(Video)
+	video.Video.MediaID = mediaID
+	video.Video.Title = title
+	video.Video.Description = description
+	return video
+}

+ 17 - 0
opms_libary/plugin/wechat/mp/message/voice.go

@@ -0,0 +1,17 @@
+package message
+
+//Voice 语音消息
+type Voice struct {
+	CommonToken
+
+	Voice struct {
+		MediaID string `xml:"MediaId"`
+	} `xml:"Voice"`
+}
+
+//NewVoice 回复语音消息
+func NewVoice(mediaID string) *Voice {
+	voice := new(Voice)
+	voice.Voice.MediaID = mediaID
+	return voice
+}

+ 145 - 0
opms_libary/plugin/wechat/mp/oauth/oauth.go

@@ -0,0 +1,145 @@
+package oauth
+
+import (
+	"dashoo.cn/opms_libary/plugin/wechat/context"
+	"encoding/json"
+	"fmt"
+	"github.com/gogf/gf/frame/g"
+	"net/http"
+	"net/url"
+)
+
+const (
+	redirectOauthURL      = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect"
+	accessTokenURL        = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code"
+	refreshAccessTokenURL = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=%s&grant_type=refresh_token&refresh_token=%s"
+	userInfoURL           = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN"
+	checkAccessTokenURL   = "https://api.weixin.qq.com/sns/auth?access_token=%s&openid=%s"
+)
+
+//Oauth 保存用户授权信息
+type Oauth struct {
+	*context.Context
+}
+
+//NewOauth 实例化授权信息
+func NewOauth(context *context.Context) *Oauth {
+	auth := new(Oauth)
+	auth.Context = context
+	return auth
+}
+
+//GetRedirectURL 获取跳转的url地址
+func (oauth *Oauth) GetRedirectURL(redirectURI, scope, state string) string {
+	//url encode
+	urlStr := url.QueryEscape(redirectURI)
+	return fmt.Sprintf(redirectOauthURL, oauth.AppID, urlStr, scope, state)
+}
+
+//Redirect 跳转到网页授权
+func (oauth *Oauth) Redirect(redirectURI, scope, state string) error {
+	location := oauth.GetRedirectURL(redirectURI, scope, state)
+	//location 为完整地址,所以不需要request
+	http.Redirect(oauth.Writer, oauth.Request, location, 302)
+	return nil
+}
+
+// ResAccessToken 获取用户授权access_token的返回结果
+type ResAccessToken struct {
+	context.WxError
+
+	AccessToken  string `json:"access_token"`
+	ExpiresIn    int64  `json:"expires_in"`
+	RefreshToken string `json:"refresh_token"`
+	OpenID       string `json:"openid"`
+	Scope        string `json:"scope"`
+}
+
+// GetUserAccessToken 通过网页授权的code 换取access_token(区别于context中的access_token)
+func (oauth *Oauth) GetUserAccessToken(code string) (result ResAccessToken, err error) {
+	url := fmt.Sprintf(accessTokenURL, oauth.AppID, oauth.AppSecret, code)
+	response := g.Client().GetBytes(url)
+	if err != nil {
+		return
+	}
+	err = json.Unmarshal(response, &result)
+	if err != nil {
+		return
+	}
+	if result.Code != 0 {
+		err = fmt.Errorf("GetUserAccessToken error : errcode=%v , errmsg=%v", result.Code, result.Msg)
+		return
+	}
+	return
+}
+
+//RefreshAccessToken 刷新access_token
+func (oauth *Oauth) RefreshAccessToken(refreshToken string) (result ResAccessToken, err error) {
+	url := fmt.Sprintf(refreshAccessTokenURL, oauth.AppID, refreshToken)
+	response := g.Client().GetBytes(url)
+	if err != nil {
+		return
+	}
+	err = json.Unmarshal(response, &result)
+	if err != nil {
+		return
+	}
+	if result.Code != 0 {
+		err = fmt.Errorf("GetUserAccessToken error : errcode=%v , errmsg=%v", result.Code, result.Msg)
+		return
+	}
+	return
+}
+
+//CheckAccessToken 检验access_token是否有效
+func (oauth *Oauth) CheckAccessToken(accessToken, openID string) (b bool, err error) {
+	url := fmt.Sprintf(checkAccessTokenURL, accessToken, openID)
+	response := g.Client().GetBytes(url)
+	if err != nil {
+		return
+	}
+	var result context.WxError
+	err = json.Unmarshal(response, &result)
+	if err != nil {
+		return
+	}
+	if result.Code != 0 {
+		b = false
+		return
+	}
+	b = true
+	return
+}
+
+//UserInfo 用户授权获取到用户信息
+type UserInfo struct {
+	context.WxError
+
+	OpenID     string   `json:"openid"`
+	Nickname   string   `json:"nickname"`
+	Sex        int      `json:"sex"`
+	Province   string   `json:"province"`
+	City       string   `json:"city"`
+	Country    string   `json:"country"`
+	HeadImgURL string   `json:"headimgurl"`
+	Privilege  []string `json:"privilege"`
+	Unionid    string   `json:"unionid"`
+}
+
+//GetUserInfo 如果scope为 snsapi_userinfo 则可以通过此方法获取到用户基本信息
+func (oauth *Oauth) GetUserInfo(accessToken, openID string) (result UserInfo, err error) {
+	url := fmt.Sprintf(userInfoURL, accessToken, openID)
+	response := g.Client().GetBytes(url)
+	if err != nil {
+		return
+	}
+	err = json.Unmarshal(response, &result)
+	if err != nil {
+		return
+	}
+	if result.Code != 0 {
+		err = fmt.Errorf("GetUserInfo error : errcode=%v , errmsg=%v", result.Code, result.Msg)
+		return
+	}
+	return
+}

+ 148 - 0
opms_libary/plugin/wechat/mp/template/template.go

@@ -0,0 +1,148 @@
+package template
+
+import (
+	"dashoo.cn/opms_libary/plugin/wechat/context"
+	"dashoo.cn/opms_libary/plugin/wechat/mp/base"
+	"encoding/json"
+)
+
+const (
+	templateSendURL = "https://api.weixin.qq.com/cgi-bin/message/template/send"
+
+	templateAddURL         = "https://api.weixin.qq.com/cgi-bin/template/api_add_template"
+	templateAllURL         = "https://api.weixin.qq.com/cgi-bin/template/get_all_private_template"
+	templateSetIndustryURL = "https://api.weixin.qq.com/cgi-bin/template/api_set_industry"
+	templateGetIndustryURL = "https://api.weixin.qq.com/cgi-bin/template/get_industry"
+)
+
+//Template 模板消息
+type Template struct {
+	base.MpBase
+}
+
+//NewTemplate 实例化
+func NewTemplate(context *context.Context) *Template {
+	tpl := new(Template)
+	tpl.Context = context
+	return tpl
+}
+
+//Message 发送的模板消息内容
+type Message struct {
+	ToUser     string               `json:"touser"`          // 必须, 接受者OpenID
+	TemplateID string               `json:"template_id"`     // 必须, 模版ID
+	URL        string               `json:"url,omitempty"`   // 可选, 用户点击后跳转的URL, 该URL必须处于开发者在公众平台网站中设置的域中
+	Color      string               `json:"color,omitempty"` // 可选, 整个消息的颜色, 可以不设置
+	Data       map[string]*DataItem `json:"data"`            // 必须, 模板数据
+
+	MiniProgram struct {
+		AppID    string `json:"appid"`    //所需跳转到的小程序appid(该小程序appid必须与发模板消息的公众号是绑定关联关系)
+		PagePath string `json:"pagepath"` //所需跳转到小程序的具体页面路径,支持带参数,(示例index?foo=bar)
+	} `json:"miniprogram"` //可选,跳转至小程序地址
+}
+
+//DataItem 模版内某个 .DATA 的值
+type DataItem struct {
+	Value string `json:"value"`
+	Color string `json:"color,omitempty"`
+}
+
+type resTemplateSend struct {
+	context.WxError
+
+	MsgID int64 `json:"msgid"`
+}
+
+//Send 发送模板消息
+func (tpl *Template) Send(msg *Message) (msgID int64, err error) {
+	response, err := tpl.HTTPPostJSONWithAccessToken(templateSendURL, msg)
+	if err != nil {
+		return 0, err
+	}
+
+	var result resTemplateSend
+	err = json.Unmarshal(response, &result)
+	if err != nil {
+		return
+	}
+	msgID = result.MsgID
+	return
+}
+
+//IndustryList 行业列表
+type IndustryList struct {
+	PrimaryIndustry *Industry `json:"primary_industry"`
+	SecondIndustry  *Industry `json:"secondary_industry"`
+}
+
+//Industry 行业
+type Industry struct {
+	FirstClass  string `json:"first_class"`
+	SecondClass string `json:"second_class"`
+}
+
+//Tmpl 模板
+type Tmpl struct {
+	TemplateId      string `json:"template_id"`
+	Title           string `json:"title"`
+	PrimaryIndustry string `json:"primary_industry"`
+	DeputyIndustry  string `json:"deputy_industry"`
+}
+
+//TmplList 模板列表
+type TmplList struct {
+	Templates []*Tmpl `json:"template_list"`
+}
+
+//AddTemplate 增加一个模板
+func (tpl *Template) AddTemplate(templateIDShort string) (templateID string, err error) {
+	type reqAddTmpl struct {
+		TemplateIDShort string `json:"template_id_short"`
+	}
+	var response []byte
+	response, err = tpl.HTTPPostJSONWithAccessToken(templateAddURL, reqAddTmpl{TemplateIDShort: templateIDShort})
+	if err != nil {
+		return "", err
+	}
+
+	var result Tmpl
+	err = json.Unmarshal(response, &result)
+	if err != nil {
+		return
+	}
+	templateID = result.TemplateId
+	return
+}
+
+//GetTemplateList 查询模板列表
+func (tpl *Template) GetTemplateList(templateIDShort string) (list TmplList, err error) {
+	var response []byte
+	response, err = tpl.HTTPGetWithAccessToken(templateAllURL)
+	err = json.Unmarshal(response, &list)
+	return
+}
+
+//GetTemplateIndustry 获得模板行业
+func (tpl *Template) GetTemplateIndustry() (industryList IndustryList, err error) {
+	var response []byte
+	response, err = tpl.HTTPGetWithAccessToken(templateGetIndustryURL)
+	err = json.Unmarshal(response, &industryList)
+	return
+}
+
+//SetTemplateIndustry 设置模板行业
+func (tpl *Template) SetTemplateIndustry(industry1, industry2 int) (err error) {
+	type reqSetIndustry struct {
+		Industry1 int `json:"industry_id1"`
+		Industry2 int `json:"industry_id2"`
+	}
+	var req reqSetIndustry
+	if industry1 > 0 {
+		req.Industry1 = industry1
+	}
+	if industry2 > 0 {
+		req.Industry2 = industry2
+	}
+	_, err = tpl.HTTPPostJSONWithAccessToken(templateSetIndustryURL, req)
+	return
+}

+ 68 - 0
opms_libary/plugin/wechat/mp/user/user.go

@@ -0,0 +1,68 @@
+package user
+
+import (
+	"dashoo.cn/opms_libary/plugin/wechat/context"
+	"dashoo.cn/opms_libary/plugin/wechat/mp/base"
+	"encoding/json"
+	"fmt"
+)
+
+const (
+	userInfoURL = "https://api.weixin.qq.com/cgi-bin/user/info"
+)
+
+//User 用户管理
+type User struct {
+	base.MpBase
+}
+
+//NewUser 实例化
+func NewUser(context *context.Context) *User {
+	user := new(User)
+	user.Context = context
+	return user
+}
+
+//Info 用户基本信息
+type Info struct {
+	context.WxError
+
+	Subscribe     int32    `json:"subscribe"`
+	OpenID        string   `json:"openid"`
+	Nickname      string   `json:"nickname"`
+	Sex           int      `json:"sex"`
+	City          string   `json:"city"`
+	Country       string   `json:"country"`
+	Province      string   `json:"province"`
+	Language      string   `json:"language"`
+	Headimgurl    string   `json:"headimgurl"`
+	SubscribeTime int64    `json:"subscribe_time"`
+	UnionID       string   `json:"unionid"`
+	Remark        string   `json:"remark"`
+	GroupID       int32    `json:"groupid"`
+	TagidList     []string `json:"tagid_list"`
+}
+
+//GetUserInfo 获取用户基本信息
+func (user *User) GetUserInfo(openID string) (userInfo *Info, err error) {
+	url := fmt.Sprintf("%s?openid=%s&lang=zh_CN", userInfoURL, openID)
+	var response []byte
+	response, err = user.HTTPGetWithAccessToken(url)
+	if err != nil {
+		return
+	}
+	userInfo = new(Info)
+	err = json.Unmarshal(response, userInfo)
+	return
+}
+
+//IsSubscribed 是否已经关注公众号
+func (user *User) IsSubscribed(openID string) (subscribed bool, err error) {
+	var userInfo *Info
+	userInfo, err = user.GetUserInfo(openID)
+	if err != nil {
+		return
+	}
+	subscribed = userInfo.Subscribe == 1
+	return
+}

Some files were not shown because too many files changed in this diff